# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# Path: myDevices/system/cpu.py
# class CpuInfo(object):
#     """Class for retrieving CPU info"""
# 
#     @staticmethod
#     def get_cpu_info():
#         """Return CPU temperature, load average and usage info as a dict"""
#         info = {}
#         info['temperature'] = self.get_cpu_temp()
#         info["loadavg"] = self.get_load_avg()
#         info["usage"] = self.get_cpu_usage()
#         return info
# 
#     @staticmethod
#     def get_cpu_usage():
#         """Return dict with overall CPU usage"""
#         usage = {}
#         try:
#             fields = ('user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal')
#             usage = {key: value for key, value in psutil.cpu_times()._asdict().items() if key in fields}
#             usage['total'] = round(sum(usage.values()), 2)
#         except:
#             exception('Error getting CPU usage info')
#         return usage
#     
#     @staticmethod
#     def get_cpu_load(interval = 1):
#         """Return CPU load
# 
#         :param interval: time interval in seconds to wait when calculating CPU usage
#         :returns: dict containing overall CPU load, as a percentage
#         """
#         cpu_load = {}
#         try:
#             cpu_load['cpu'] = psutil.cpu_percent(interval)
#         except:
#             exception('Error getting CPU load info')
#         return cpu_load
# 
#     @staticmethod
#     def get_cpu_temp():
#         """Get CPU temperature"""
#         info = {}
#         thermal_dirs = glob('/sys/class/thermal/thermal_zone*')
#         thermal_dirs.sort()
#         temp = 0.0
#         try:
#             for thermal_dir in thermal_dirs:
#                 try:
#                     thermal_type = ''
#                     with open(thermal_dir + '/type', 'r') as type_file:
#                         thermal_type = type_file.read().strip()
#                     if thermal_type != 'gpu_thermal':
#                         with open(thermal_dir + '/temp', 'r') as temp_file:
#                             content = int(temp_file.read().strip())
#                             temp = content / 1000.0
#                             break
#                 except:
#                     pass
#         except Exception:
#             exception('Error getting CPU temperature')
#         return temp
# 
#     @staticmethod
#     def get_load_avg():
#         """Get CPU average load for the last one, five, and 10 minute periods"""
#         info = {}
#         file = "/proc/loadavg"
#         one     = 0
#         five    = 0
#         ten     = 0
#         try:
#             with open(file, 'r') as f_stat:
#                 content = f_stat.read().strip().split(' ')
#                 one = float(content[0])
#                 five = float(content[1])
#                 ten = float(content[2])
#         except Exception:
#             exception('Error getting CPU load average')
#         info['one']     = one
#         info['five']    = five
#         info['ten']     = ten
#         return info
# 
# Path: myDevices/cloud/cayennemqtt.py
# DATA_TOPIC = 'data/json'
# COMMAND_TOPIC = 'cmd'
# COMMAND_JSON_TOPIC = 'cmd.json'
# COMMAND_RESPONSE_TOPIC = 'response'
# JOBS_TOPIC = 'jobs.json'
# SYS_HARDWARE_MAKE = 'sys:hw:make'
# SYS_HARDWARE_MODEL = 'sys:hw:model'
# SYS_OS_NAME = 'sys:os:name'
# SYS_OS_VERSION = 'sys:os:version'
# SYS_NET = 'sys:net'
# SYS_STORAGE = 'sys:storage'
# SYS_RAM = 'sys:ram'
# SYS_CPU = 'sys:cpu'
# SYS_I2C = 'sys:i2c'
# SYS_SPI = 'sys:spi'
# SYS_UART = 'sys:uart'
# SYS_ONEWIRE = 'sys:1wire'
# SYS_DEVICETREE = 'sys:devicetree'
# SYS_GPIO = 'sys:gpio'
# SYS_POWER_RESET = 'sys:pwr:reset'
# SYS_POWER_HALT = 'sys:pwr:halt'
# AGENT_VERSION = 'agent:version'
# AGENT_DEVICES = 'agent:devices'
# AGENT_MANAGE = 'agent:manage'
# AGENT_SCHEDULER = 'agent:scheduler'
# DEV_SENSOR = 'dev'
# IP = 'ip'
# SPEEDTEST = 'speedtest'
# SSID = 'ssid'
# USAGE = 'usage'
# CAPACITY = 'capacity'
# LOAD = 'load'
# TEMPERATURE = 'temp'
# VALUE = 'value'
# FUNCTION = 'function'
# class DataChannel:
# class CayenneMQTTClient:
#     def add(data_list, prefix, channel=None, suffix=None, value=None, type=None, unit=None, name=None):
#     def add_unique(data_list, prefix, channel=None, suffix=None, value=None, type=None, unit=None, name=None):
#     def begin(self, username, password, clientid, hostname='mqtt.mydevices.com', port=8883):
#     def connect_callback(self, client, userdata, flags, rc):
#     def disconnect_callback(self, client, userdata, rc):
#     def transform_command(self, command, payload=[], channel=[]):
#     def message_callback(self, client, userdata, msg):
#     def get_topic_string(self, topic, append_wildcard=False):
#     def disconnect(self):
#     def loop(self, timeout=1.0):
#     def loop_start(self):
#     def loop_stop(self):
#     def publish_packet(self, topic, packet, qos=0, retain=False):
#     def publish_response(self, msg_id, error_message=None):


import psutil
import netifaces
from myDevices.utils.logger import exception
from myDevices.system.cpu import CpuInfo
from myDevices.cloud import cayennemqtt
"""
This module retrieves information about the system, including CPU, RAM, disk and network data.
"""



class SystemInfo():
    """Class to get system CPU, memory, uptime, storage and network info"""

    def getSystemInformation(self):
        """Get a dict containing CPU, memory, uptime, storage and network info"""
        system_info = []
        try:
            system_info += self.getCpuInfo()
            system_info += self.getMemoryInfo((cayennemqtt.USAGE,))
            system_info += self.getDiskInfo((cayennemqtt.USAGE,))
            system_info += self.getNetworkInfo()
        except:

# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# Path: myDevices/system/cpu.py
# class CpuInfo(object):
#     """Class for retrieving CPU info"""
# 
#     @staticmethod
#     def get_cpu_info():
#         """Return CPU temperature, load average and usage info as a dict"""
#         info = {}
#         info['temperature'] = self.get_cpu_temp()
#         info["loadavg"] = self.get_load_avg()
#         info["usage"] = self.get_cpu_usage()
#         return info
# 
#     @staticmethod
#     def get_cpu_usage():
#         """Return dict with overall CPU usage"""
#         usage = {}
#         try:
#             fields = ('user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal')
#             usage = {key: value for key, value in psutil.cpu_times()._asdict().items() if key in fields}
#             usage['total'] = round(sum(usage.values()), 2)
#         except:
#             exception('Error getting CPU usage info')
#         return usage
#     
#     @staticmethod
#     def get_cpu_load(interval = 1):
#         """Return CPU load
# 
#         :param interval: time interval in seconds to wait when calculating CPU usage
#         :returns: dict containing overall CPU load, as a percentage
#         """
#         cpu_load = {}
#         try:
#             cpu_load['cpu'] = psutil.cpu_percent(interval)
#         except:
#             exception('Error getting CPU load info')
#         return cpu_load
# 
#     @staticmethod
#     def get_cpu_temp():
#         """Get CPU temperature"""
#         info = {}
#         thermal_dirs = glob('/sys/class/thermal/thermal_zone*')
#         thermal_dirs.sort()
#         temp = 0.0
#         try:
#             for thermal_dir in thermal_dirs:
#                 try:
#                     thermal_type = ''
#                     with open(thermal_dir + '/type', 'r') as type_file:
#                         thermal_type = type_file.read().strip()
#                     if thermal_type != 'gpu_thermal':
#                         with open(thermal_dir + '/temp', 'r') as temp_file:
#                             content = int(temp_file.read().strip())
#                             temp = content / 1000.0
#                             break
#                 except:
#                     pass
#         except Exception:
#             exception('Error getting CPU temperature')
#         return temp
# 
#     @staticmethod
#     def get_load_avg():
#         """Get CPU average load for the last one, five, and 10 minute periods"""
#         info = {}
#         file = "/proc/loadavg"
#         one     = 0
#         five    = 0
#         ten     = 0
#         try:
#             with open(file, 'r') as f_stat:
#                 content = f_stat.read().strip().split(' ')
#                 one = float(content[0])
#                 five = float(content[1])
#                 ten = float(content[2])
#         except Exception:
#             exception('Error getting CPU load average')
#         info['one']     = one
#         info['five']    = five
#         info['ten']     = ten
#         return info
# 
# Path: myDevices/cloud/cayennemqtt.py
# DATA_TOPIC = 'data/json'
# COMMAND_TOPIC = 'cmd'
# COMMAND_JSON_TOPIC = 'cmd.json'
# COMMAND_RESPONSE_TOPIC = 'response'
# JOBS_TOPIC = 'jobs.json'
# SYS_HARDWARE_MAKE = 'sys:hw:make'
# SYS_HARDWARE_MODEL = 'sys:hw:model'
# SYS_OS_NAME = 'sys:os:name'
# SYS_OS_VERSION = 'sys:os:version'
# SYS_NET = 'sys:net'
# SYS_STORAGE = 'sys:storage'
# SYS_RAM = 'sys:ram'
# SYS_CPU = 'sys:cpu'
# SYS_I2C = 'sys:i2c'
# SYS_SPI = 'sys:spi'
# SYS_UART = 'sys:uart'
# SYS_ONEWIRE = 'sys:1wire'
# SYS_DEVICETREE = 'sys:devicetree'
# SYS_GPIO = 'sys:gpio'
# SYS_POWER_RESET = 'sys:pwr:reset'
# SYS_POWER_HALT = 'sys:pwr:halt'
# AGENT_VERSION = 'agent:version'
# AGENT_DEVICES = 'agent:devices'
# AGENT_MANAGE = 'agent:manage'
# AGENT_SCHEDULER = 'agent:scheduler'
# DEV_SENSOR = 'dev'
# IP = 'ip'
# SPEEDTEST = 'speedtest'
# SSID = 'ssid'
# USAGE = 'usage'
# CAPACITY = 'capacity'
# LOAD = 'load'
# TEMPERATURE = 'temp'
# VALUE = 'value'
# FUNCTION = 'function'
# class DataChannel:
# class CayenneMQTTClient:
#     def add(data_list, prefix, channel=None, suffix=None, value=None, type=None, unit=None, name=None):
#     def add_unique(data_list, prefix, channel=None, suffix=None, value=None, type=None, unit=None, name=None):
#     def begin(self, username, password, clientid, hostname='mqtt.mydevices.com', port=8883):
#     def connect_callback(self, client, userdata, flags, rc):
#     def disconnect_callback(self, client, userdata, rc):
#     def transform_command(self, command, payload=[], channel=[]):
#     def message_callback(self, client, userdata, msg):
#     def get_topic_string(self, topic, append_wildcard=False):
#     def disconnect(self):
#     def loop(self, timeout=1.0):
#     def loop_start(self):
#     def loop_stop(self):
#     def publish_packet(self, topic, packet, qos=0, retain=False):
#     def publish_response(self, msg_id, error_message=None):


# Path: myDevices/system/systeminfo.py
import psutil
import netifaces
from myDevices.utils.logger import exception
from myDevices.system.cpu import CpuInfo
from myDevices.cloud import cayennemqtt

"""
This module retrieves information about the system, including CPU, RAM, disk and network data.
"""



class SystemInfo():
    """Class to get system CPU, memory, uptime, storage and network info"""

    def getSystemInformation(self):
        """Get a dict containing CPU, memory, uptime, storage and network info"""
        system_info = []
        try:
            system_info += self.getCpuInfo()
            system_info += self.getMemoryInfo((cayennemqtt.USAGE,))
            system_info += self.getDiskInfo((cayennemqtt.USAGE,))
            system_info += self.getNetworkInfo()
        except:

            exception('Error retrieving system info')