def sendSerial(self, str_to_send):
     try:
         self.serialC.write(str(str_to_send).encode())
         print("Sent via serial: {0}".format(str_to_send))
         return 1
     except Exception as exc:
         print("Exception: {0}".format(exc))
         exceptionLogger("serialCOM.py", "sendSerial",
                         getframeinfo(currentframe()).lineno, exc)
         return 0
 def receiveSerial(self):
     try:
         answer = self.serialC.readline()
         answer = answer.decode().replace('\n', '')
         if answer != "":
             print("Received via serial: {0}".format(answer))
         return answer
     except Exception as exc:
         print("Exception: {0}".format(exc))
         exceptionLogger("serialCOM.py", "sendSerial",
                         getframeinfo(currentframe()).lineno, exc)
 def detUptime():
     # Pegando uptime
     uptime = "Error"
     try:
         uptime = syscall("uptime -p")[0].replace('\n', '')
         return str(uptime)
     except Exception as exc:
         uptime = "Error"
         print("Erro na coleta da uptime - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "uptime",
                         getframeinfo(currentframe()).lineno, exc)
         return "-1"
    def serviceStatus():
        try:
            try:
                arp_block_status = syscall("""systemctl | grep arp_block | awk '{print $3}'""")[0]
                arp_block_status = {"arp_block": str(arp_block_status)}
            except Exception as exc:
                arp_block_status = {"arp_block": str("stopped")}

            try:
                nginx_status = syscall("""systemctl | grep nginx | awk '{print $3}'""")[0]
                nginx_status = {"nginx": str(nginx_status)}
            except Exception as exc:
                nginx_status = {"nginx": str("stopped")}

            try:
                gunicorn_status = syscall("""systemctl | grep gunicorn | awk '{print $3}'""")[0]
                gunicorn_status = {"gunicorn": str(gunicorn_status)}
            except Exception as exc:
                gunicorn_status = {"gunicorn": str("stopped")}

            try:
                hostapd_status = syscall("""systemctl | grep hostapd | awk '{print $3}'""")[0]
                hostapd_status = {"hostapd": str(hostapd_status)}
            except Exception as exc:
                hostapd_status = {"hostapd": str("stopped")}

            try:
                dnsmasq_status = syscall("""systemctl | grep dnsmasq | awk '{print $3}'""")[0]
                dnsmasq_status = {"dnsmasq": str(dnsmasq_status)}
            except Exception as exc:
                dnsmasq_status = {"dnsmasq": str("stopped")}

            try:
                flaskAPIBridge_status = syscall("""systemctl | grep flaskAPIBridge | awk '{print $3}'""")[0]
                flaskAPIBridge_status = {"flaskAPIBridge": str(flaskAPIBridge_status)}
            except Exception as exc:
                flaskAPIBridge_status = {"flaskAPIBridge": str("stopped")}

            response = [arp_block_status, nginx_status, gunicorn_status, hostapd_status, dnsmasq_status,
                        flaskAPIBridge_status]
            return response
        except Exception as exc:
            exceptionLogger("General_Info.py", "serviceStatus", getframeinfo(currentframe()).lineno, exc)
            arp_block_status = {"arp_block": str("had exception")}
            nginx_status = {"nginx": str("had exception")}
            gunicorn_status = {"gunicorn": str("had exception")}
            hostapd_status = {"hostapd": str("had exception")}
            dnsmasq_status = {"dnsmasq": str("had exception")}
            flaskAPIBridge_status = {"flaskAPIBridge": str("had exception")}
            response = [arp_block_status, nginx_status, gunicorn_status, hostapd_status, dnsmasq_status,
                        flaskAPIBridge_status]
            return response
 def detInterface():
     # Pegando interface wlan
     interface = "Error"
     try:
         interface = syscall(
             """iw dev | awk '$1=="Interface"{print $2}'""")[0].replace(
                 '\n', '')
         return str(interface)
     except Exception as exc:
         interface = "None"
         print("Erro na coleta da interface - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "interface",
                         getframeinfo(currentframe()).lineno, exc)
         return interface
 def detMemory():
     # Pegando memory
     mem = "Error"
     try:
         mem = syscall(
             "free | grep Mem | awk '{usage=($3/$2)*100} END {print usage \"%\"}'"
         )[0].replace('\n', '')
         return str(mem)
     except Exception as exc:
         mem = "Error"
         print("Erro na coleta da memory - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "mem",
                         getframeinfo(currentframe()).lineno, exc)
         return "-1"
 def detCPU():
     # Pegando CPU%
     cpu = "Error"
     try:
         cpu = syscall(
             "grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'"
         )[0].replace('\n', '')
         return str(cpu)
     except Exception as exc:
         cpu = "Error"
         print("Erro na coleta da cpu - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "detCPU",
                         getframeinfo(currentframe()).lineno, exc)
         return "-1"
    def detMAC():
        # Pegando mac
        mac = "Error"
        try:
            mac = syscall("cat /sys/class/net/eth0/address")[0].replace(
                '\n', '')
            return str(mac)

        except Exception as exc:
            mac = "None"
            print("Erro na coleta do mac - Exception = %s" % (str(exc)))
            exceptionLogger("HWinfo.py", "mac",
                            getframeinfo(currentframe()).lineno, exc)
            return mac
 def detVersion():
     # Pegando version
     version = "Error"
     try:
         version_file = open('/root/info/version', 'r')
         version = version_file.read()
         version_file.close()
         version = version.replace("\n", "")
         return str(version)
     except Exception as exc:
         version = "Error"
         print("Erro na coleta de version - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "detStatusHotspot",
                         getframeinfo(currentframe()).lineno, exc)
         return "0"
 def detStatusHotspot():
     # Pegando status
     status = "Error"
     try:
         status_file = open('/root/info/status', 'r')
         status = status_file.read()
         status_file.close()
         if status == "\n" or status == "":
             status = 0
         status = status.replace("\n", "")
         return str(status)
     except Exception as exc:
         status = "Error"
         print("Erro na coleta de status - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "detStatusHotspot",
                         getframeinfo(currentframe()).lineno, exc)
         return "0"
 def detOnlineNumber():
     # Pegando online Number
     online = "Error"
     try:
         online_file = open('/root/info/online', 'r')
         online = online_file.read()
         online_file.close()
         if online == "\n" or online == "":
             online = 0
         online = online.replace("\n", "")
         return str(online)
     except Exception as exc:
         online = "Error"
         print("Erro na coleta de onlines - Exception = %s" % (str(exc)))
         exceptionLogger("HWinfo.py", "OnlineNumber",
                         getframeinfo(currentframe()).lineno, exc)
         return "0"
 def detTemperature():
     # Pegando temperatura
     temperature = "Error"
     try:
         temperature = syscall(
             "cat /sys/devices/virtual/thermal/thermal_zone0/temp"
         )[0].replace('\n', '')
         if syscall(
                 """uname -a | awk '{print $3}'""")[0] == '4.14.18-sunxi':
             temperature = int(temperature) / 1000
         else:
             temperature = int(temperature)
         return str(temperature)
     except Exception as exc:
         temperature = "Error"
         print("Erro na coleta da temperatura - Exception = %s" %
               (str(exc)))
         exceptionLogger("HWinfo.py", "detTemperature",
                         getframeinfo(currentframe()).lineno, exc)
         return "-1"
    def networking():
        try:
            try:
                interface = syscall(
                    """iw dev | awk '$1=="Interface"{print $2}'""")[0].replace(
                        '\n', '')
                interface = {"interface": str(interface)}
            except Exception as exc:
                interface = {"interface": str("error")}

            try:
                date = syscall("date +\"%d/%m/%Y %H:%M:%S\"")[0].replace(
                    "\n", "")
                date = {"datetime": str(date)}
            except Exception as exc:
                date = {"datetime": str("error")}

            try:
                wlan = str(
                    syscall(
                        """lsusb | grep '003 Device 002' | awk '{print $7}'""")
                    [0]).replace("\n", "")
                if wlan == 'Linux' or wlan == '':
                    wlan = "None"
                else:
                    wlan = {"antena": wlan}
            except Exception as exc:
                wlan = {"antena": str("None")}

            try:
                public_ip_file = open('/root/info/public_ip', 'r')
                public_ip = public_ip_file.read().replace("\n", "")
                public_ip_file.close()
                if public_ip == "\n" or public_ip == "":
                    public_ip = "error"
                public_ip = {'public_ip': str(public_ip)}
            except Exception as exc:
                public_ip = {'public_ip': str("error")}

            try:  # ifstat wlan tx rx
                speed_file = open('/root/info/download', 'r')
                download_speed = str(speed_file.read())
                speed_file.close()
                try:
                    if download_speed.split(' ')[0] == "Download:":
                        upload_speed = download_speed.split("\n")[1].replace(
                            "Upload: ", "")
                        upload_speed = {'upload_speed': upload_speed}
                        download_speed = download_speed.split("\n")[0].replace(
                            "Download: ", "")
                        download_speed = {'download_speed': download_speed}
                    else:
                        download_speed = {"download_speed": str("N/A")}
                        upload_speed = {"upload_speed": str("N/A")}
                except Exception as exc:
                    print(exc)
                    download_speed = {"download_speed": str("N/A")}
                    upload_speed = {"upload_speed": str("N/A")}
            except Exception as exc:
                print(exc)
                download_speed = {"download_speed": str("N/A")}
                upload_speed = {"upload_speed": str("N/A")}
            try:
                ping_uol = str(
                    syscall(
                        """ping -c 1 www.uol.com.br | head -2 | tail -1 | awk '{print $8 $9}' | sed 's/time//g' | sed 
                    's/=//g'""")[0]).replace("\n", "")
                ping_uol = {"ping_uol.com.br": ping_uol}
            except Exception as exc:
                ping_uol = {"ping_uol.com.br": str("fail")}

            try:
                ping_connecty = str(
                    syscall(
                        """ping -c 1 18.228.62.35 | head -2 | tail -1 | awk '{print $7 $8}' | sed 's/time//g' | sed 
                    's/=//g'""")[0]).replace("\n", "")
                ping_connecty = {"ping_api.connecty": ping_connecty}
            except Exception as exc:
                ping_connecty = {"ping_api.connecty": str("fail")}

            response = [
                date, wlan, interface, public_ip, download_speed, upload_speed,
                ping_uol, ping_connecty
            ]
            return response

        except Exception as exc:
            exceptionLogger("GeneralNetworking.py", "serviceStatus",
                            getframeinfo(currentframe()).lineno, exc)
            date = {"datetime": str("had exception")}
            wlan = {"antena": str("had exception")}
            interface = {"interface": str("had exception")}
            public_ip = {"public_ip": str("had exception")}
            upload_speed = {'upload_speed': str("had exception")}
            download_speed = {'download_speed': str("had exception")}
            ping_uol = {"ping_uol.com.br": str("had exception")}
            ping_connecty = {"ping_api.connecty": str("had exception")}
            response = [
                date, wlan, interface, public_ip, download_speed, upload_speed,
                ping_uol, ping_connecty
            ]
            return response
Example #14
0
from inspect import currentframe, getframeinfo
import threading
from helper import exceptionLogger
from helper import syscall
from serialCOM import serialControler
from flaskAPIBridge import WSHandler

if __name__ == "__main__":
    try:
        #Cria Objeto da classe serial
        serialObj = serialControler("/dev/ttyUSB0")
        threadSerialManager = threading.Thread(target=serialObj.serialManager,
                                               args=())
        threadSerialManager.start()
        #readThread = threading.Thread(target=serialObj.reader, args=(serialObj,))
        #readThread.start()
        #serialObj.whileSender()

        #Estabelece conexao websocket
        ws = WSHandler()
        ws.WSConnCreator
        threadGerenciaWS = threading.Thread(target=ws.WSConnManager, args=())
        threadGerenciaWS.start()

        thread_internalHwDataStreamer = threading.Thread(
            target=ws.socketReceiver, args=serialObj)
        thread_internalHwDataStreamer.start()
    except Exception as exc:
        print("main error, exception: {0}".format(exc))
        exceptionLogger("flaskAPIBridge.py", "main",
                        getframeinfo(currentframe()).lineno, exc)