Example #1
0
    def save(self, msg=None):
        valuestring = "?, " * (len(self.__class__.properties) +
                               len(self.__class__.fixed))
        valuestring = valuestring[0:-2]

        for object in self.objects:
            fields = ""
            values = []

            for property in self.__class__.properties:
                fields += str(property) + "=?, "
                values.append(getattr(object, property))

            for key, val in self.__class__.fixed.iteritems():
                fields += str(key) + "=?, "
                values.append(val)
            fields = fields[0:-2]
            values.append(getattr(object, self.__class__.id_property))

            query = "UPDATE " + self.__class__.table + " SET " + fields + " WHERE " +\
                    str(self.__class__.id_property)+ "=?;"
            try:
                LogHandler.log_info("Database: Save(" +
                                    str(self.__class__.__name__) + "): " +
                                    query + "\n" + str(tuple(values)))
                self.cur.execute(query, values)
            except sqlite3.Error, e:
                LogHandler.log_error("Database: Exception: %s" % e.args[0])
Example #2
0
def user_add(data, parameter, au):
    for property in TransactionBean.UserBean.properties:
        try:
            print("Setting UserBean" + str(property) + " To " + data["user"][str(property)])
            setattr(au.user_info, str(property), data["user"][str(property)])
        except ValueError, ve:
            LogHandler.log_warning("Value Error: " + str(ve[0]))
Example #3
0
 def close(self, msg=None):
     try:
         LogHandler.log_info("Database: Close(" +
                             str(self.__class__.__name__) + "): " +
                             str(msg))
         self.con.close()
     except sqlite3.Error, e:
         LogHandler.log_error("Database: Exception: %s" % e.args[0])
Example #4
0
def auth_login(data, parameter, user):
    username = str(data["username"])
    password = str(data["password"])
    LogHandler.log_info(str(username) + " is logging in")
    tb = TransactionBean.AuthenticationBean()
    auth = tb.get_object({"username": username, "password": password})
    if auth != None and auth.is_authed:
        return {"error": "success"}, auth.user_info
    else:
        return {"error": "failure"}
Example #5
0
def start():
    PORT = 8000
    HOSTNAME = ""
    httpd = BaseHTTPServer.HTTPServer((HOSTNAME, PORT), WebServer)
    print "serving at port", PORT
    while True:
        try:
            httpd.serve_forever()
        except:
            LogHandler.log_exception()
Example #6
0
    def __init__(self):
        if self.__class__.table == None:
            self.__class__.table = self.__class__.obj.__name__
        self.connection = None
        self.cursor = None

        # Connect to the database
        try:
            LogHandler.log_info("Database: Open(" +
                                str(self.__class__.__name__) + ")")
            self.con = sqlite3.connect('database.db')
            self.cur = self.con.cursor()
        except sqlite3.Error, e:
            LogHandler.log_error("Database: Exception: %s" % e.args[0])
Example #7
0
 def __init__(self,
              server_settings=settings.server_settings,
              run_dir=os.path.dirname(os.path.realpath(__file__)),
              log_handler=None):
     self.server_settings = server_settings
     self.run_dir = run_dir
     self.in_queue = None
     self.in_q_thr = None
     self.stop_event = threading.Event()
     self.running_server_event = threading.Event()
     self.processing_input_event = threading.Event()
     self.log_handler = log_handler
     if self.log_handler is None:
         self.log_handler = LogHandler.log_handler()
Example #8
0
def start():
    #TODO: Make sure this runs roughly every 5 minutes
    last_run = 0
    while True:
        # Run every 5 minutes
        LogHandler.log_warning("Checking Queues")

        finish_time = time.time()
        LogHandler.log_warning(str(finish_time - last_run))
        if finish_time - last_run > run_every:
            LogHandler.log_warning("Queues Getting too big to handle")
            big_queues = True
        else:
            big_queues = False
        sleep_length = time.time() % run_every
        LogHandler.log_warning(
            str(time.time()) + "/" + str(time.time() % run_every) +
            " Sleeping For: " + str(sleep_length))
        time.sleep(sleep_length)
        last_run = time.time()
Example #9
0
def Init():
    global driver, config, userName, password, likeClassName, unLikeClassName, logger, numberOfLikes

    logger = LogHandler.Start()
    logger.getLogger('AutoLike')

    try:
        driver = SeleniumConfig.InitSelenium()

        config = ConfigParser.ConfigParser()
        config.read('config.ini')
        userName = config.get('DEFAULT', 'userName')
        password = config.get('DEFAULT', 'password')
        likeClassName = config.get('DEFAULT', 'likeClassName')
        unLikeClassName = config.get('DEFAULT', 'unLikeClassName')
        numberOfLikes = config.get('DEFAULT', 'numberOfLikes')

    except Exception as e:
        logger.error(
            "Unable to init chrome driver or config file. Exception: %s", e)
        raise Exception('Unable to init')
Example #10
0
    def create_object(self):
        new_object = self.__class__.obj()
        self.objects = [new_object]

        valuestring = "?, " * (len(self.__class__.properties) +
                               len(self.__class__.fixed))
        valuestring = valuestring[0:-2]
        fields = ""
        values = []

        for property in self.__class__.properties:
            fields += str(property) + ", "
            values.append(getattr(new_object, property))

        for key, val in self.__class__.fixed.iteritems():
            fields += str(key) + ", "
            values.append(val)
        fields = fields[0:-2]

        query = "INSERT INTO " + self.__class__.table + " (" + fields + \
                ") VALUES (" + valuestring + ");"
        new_object
        try:
            LogHandler.log_info("Database: Create(" +
                                str(self.__class__.__name__) + "): Query:" +
                                query)
            LogHandler.log_info("Database: Create(" +
                                str(self.__class__.__name__) + "): Values:" +
                                str(values))
            self.cur.execute(query, values)
            returnid = self.cur.lastrowid
            print("SETTING: " + str(self.__class__.id_property) + " to " +
                  str(returnid))
            old = getattr(new_object, str(self.__class__.id_property))
            setattr(new_object, str(self.__class__.id_property), returnid)
            new = getattr(new_object, str(self.__class__.id_property))
            print("WAS: " + str(old) + " IS: " + str(new))
        except sqlite3.Error, e:
            LogHandler.log_error("Database: Exception: %s" % e.args[0])
Example #11
0
    def get_objects(self, searchterms=None, limit=None, start=None):
        selecting = ""
        for porperty in self.__class__.properties:
            selecting += porperty + ", "
        selecting += str(self.__class__.id_property)

        values = []
        search = ""
        if searchterms != None:
            for key, val in searchterms.iteritems():
                search += "AND " + str(key) + "=? "
                values.append(val)
            search = search[4:]
        else:
            search = "1==1"

        limiter = ""
        for key, val in self.__class__.fixed.iteritems():
            limiter += "AND " + str(key) + "=? "
            values.append(val)

        # Read record from table
        selectquery = "SELECT " + selecting + " FROM " + self.__class__.table + \
                " WHERE " + search + " " +  limiter + ";"
        data = None
        try:
            LogHandler.log_info("Database: Select(" +
                                str(self.__class__.__name__) + "): " +
                                selectquery)
            LogHandler.log_info("Database: Select(" +
                                str(self.__class__.__name__) + "): " +
                                str(tuple(values)))
            self.cur.execute(selectquery, tuple(values))
            data = self.cur.fetchall()
        except sqlite3.Error, e:
            LogHandler.log_error("Database: Exception: %s" % e.args[0])
Example #12
0
class PhosGui(QtGui.QMainWindow):
    """The main gui"""

    def __init__(self, parent=None):
        super(QtGui.QMainWindow, self).__init__(parent)
        
        print 'init phos gui'
        self.resize(1120, 880)
        self.initTabs()
        self.initMenuBar()
        self.initDialogs()

        self.setCentralWidget(self.tabControls)

        self.initConnections()

        self.rcuDialog = RcuDialog()
        self.configureElectronicsDialog = ConfigureElectronicsDialog()

    def initTabs(self):
        
        self.tabControls = QtGui.QTabWidget(self)
        
        self.moduleTabs = [None]*PHOS_MODS

        for i in range(PHOS_MODS):
            
            self.moduleTabs[i] = ModuleTabWidget(i,self)
            self.tabControls.addTab(self.moduleTabs[i], "Module " + str(i))
            self.moduleTabs[i].setEnabled(0)
        self.phosTab = PhosTabWidget(self)
        self.tabControls.addTab(self.phosTab, "PHOS Detector")
        
    def initMenuBar(self):
        
        self.connectMenu = self.menuBar().addMenu("&Connect")
        self.settingsMenu = self.menuBar().addMenu("&Settings")
        
        self.connectAction = QtGui.QAction("Connect &Now", self)
        self.connectSettingsAction = QtGui.QAction("Connection &Settings...", self)
        self.disconnectAction = QtGui.QAction("&Disconnect", self)
        self.connectMenu.addAction(self.connectAction)
        self.connectMenu.addAction(self.disconnectAction)
        self.connectMenu.addAction(self.connectSettingsAction)

    def initDialogs(self):
        
        self.feeServerNames = [None]*PHOS_MODS
        self.connectSettingsDialog = ConnectSettingsDialog(self.feeServerNames)

    def initConnections(self):

        self.connect(self.connectSettingsAction, QtCore.SIGNAL("triggered()"), self.showConnectDialog)
        self.connect(self.connectAction, QtCore.SIGNAL("triggered()"), self.connectToFeeServers)
        self.connect(self.disconnectAction, QtCore.SIGNAL("triggered()"), self.disconnectFromFeeServers)

        self.dcsInterface = DcsInterfaceThreadWrapper(DcsInterface())
        
        self.feeCardHandler = FeeCardHandler(self.dcsInterface)
        self.truCardHandler = TruCardHandler(self.dcsInterface)
        self.rcuHandler = RcuHandler(self.dcsInterface)
        self.moduleHandler = ModuleHandler(self.dcsInterface)
        self.detectorHandler = DetectorHandler(self.dcsInterface)
        self.logHandler = LogHandler(self.dcsInterface)
        self.databaseHandler = DatabaseHandler(self.dcsInterface)

        self.connect(self.feeCardHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.truCardHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.rcuHandler, QtCore.SIGNAL("fetchLog"), self.logHandler.getLogString)
        self.connect(self.moduleHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.detectorHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.logHandler, QtCore.SIGNAL("gotLog"), self.updateLogViewer)

        self.connect(self, QtCore.SIGNAL("viewFee"), self.showFeeDialog)
        self.connect(self, QtCore.SIGNAL("viewdTru"), self.showTruDialog)
        self.connect(self, QtCore.SIGNAL("viewRcu"), self.showRcuDialog)
        
        self.connect(self, QtCore.SIGNAL("toggleFee"), self.feeCardHandler.toggleOnOff)
        self.connect(self, QtCore.SIGNAL("toggleTru"), self.truCardHandler.toggleOnOff)
        self.connect(self, QtCore.SIGNAL("rcuUpdateStatus"), self.rcuHandler.updateStatus)
        self.connect(self, QtCore.SIGNAL("rcuToggleOnOff"), self.rcuHandler.toggleOnOff)
        
#        self.connect(self, QtCore.SIGNAL("turnOnModule"), self.moduleHandler.turnOn)
        self.connect(self, QtCore.SIGNAL("turnOnModule"), self.goReady)
        self.connect(self, QtCore.SIGNAL("shutdownModule"), self.moduleHandler.shutdown)

        self.connect(self, QtCore.SIGNAL("showModuleProperties"), self.showModulePropertiesDialog)
        self.connect(self, QtCore.SIGNAL("configureElectronicsModule"), self.showElectronicsConfigDialog)

        self.connect(self, QtCore.SIGNAL("enableTriggerModule"), self.moduleHandler.enableTrigger)
        self.connect(self, QtCore.SIGNAL("disableTriggerModule"), self.moduleHandler.disableTrigger)

        self.connect(self, QtCore.SIGNAL("FeeServerStarted"), self.enableConnectedFeeServers)        

        self.connect(self.detectorHandler, QtCore.SIGNAL("FeeServerStarted"), self.enableConnectedFeeServers)

        for i in range(PHOS_MODS):

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("toggleFee"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewFee"), self.extractSignal)
            
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("toggleTru"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewTru"), self.extractSignal)

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("rcuUpdateStatus"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("rcuToggleOnOff"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewRcu"), self.extractSignal)


            self.connect(self.moduleTabs[i], QtCore.SIGNAL("turnOnModule"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("shutdownModule"), self.extractSignal)
            
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("showModuleProperties"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("configureElectronicsModule"), self.extractSignal)

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("enableTriggerModule"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("disableTriggerModule"), self.extractSignal)

            self.connect(self, QtCore.SIGNAL("cardToggled" + str(i)), self.moduleTabs[i].updateFeeCard)
            self.connect(self, QtCore.SIGNAL("feeStateUpdated" + str(i)), self.moduleTabs[i].updateFeeCard)
            self.connect(self, QtCore.SIGNAL("statusUpdated" + str(i)), self.moduleTabs[i].updateRcu)


        self.connect(self.feeCardHandler, QtCore.SIGNAL("cardToggled"), self.translateFeeSignal)
        self.connect(self.rcuHandler, QtCore.SIGNAL("cardToggled"), self.translateFeeSignal)
        self.connect(self.rcuHandler, QtCore.SIGNAL("feeStateUpdated"), self.translateFeeSignal)

        self.connect(self.rcuHandler, QtCore.SIGNAL("statusUpdated"), self.translateRcuSignal)

    def translateFeeSignal(self, *args):
        
        feeId = args[1]
        res = args[2]
        module = feeId/(RCUS_PER_MODULE*CARDS_PER_RCU)
        self.emit(QtCore.SIGNAL(args[0] + str(module)), feeId, res)
        print args[0]

    def translateRcuSignal(self, *args):

        rcuId = args[1]
        res = args[2]
        module = rcuId/(RCUS_PER_MODULE)
        self.emit(QtCore.SIGNAL(args[0] + str(module)), rcuId, res)
        print args[0]

    def extractSignal(self, *args):
        
        params = []
        for i in range(1, len(args)):
            params.append(args[i])
        self.emit(QtCore.SIGNAL(args[0]), *params)

#     def rcuUpdateStatus(self, signal, rcuId):
        
#         self.emit(QtCore.SIGNAL("rcuUpdateStatus"), rcuId)

#     def rcuUpdateStatus(self, signal, rcuId):
        
#         self.emit(QtCore.SIGNAL("rcuUpdateStatus"), rcuId)

#     def rcuUpdateStatus(self, signal, rcuId):
        
#         self.emit(QtCore.SIGNAL("rcuUpdateStatus"), rcuId)

    def showFeeDialog(self, feeId):
        
        print 'Dialog not yet made...'

    def showTruDialog(self, feeId):

        print 'Dialog not yet made...'

    def showRcuDialog(self, rcuId):
        moduleId = 0
        self.rcuDialog.start(self.rcuHandler, rcuId, moduleId)

    def showModulePropertiesDialog(self, moduleId):
        
        print 'Dialog not yet made...'

    def showElectronicsConfigDialog(self, moduleId):
        
        self.configureElectronicsDialog.start(self.moduleHandler, self.databaseHandler, moduleId)
        
    def showConnectDialog(self):
        
        self.connectSettingsDialog.exec_()
       

    def connectToFeeServers(self):
        
        feeServerNames, feeServerEnabled = self.connectSettingsDialog.getFeeServers()
        self.detectorHandler.connectToFeeServers(feeServerNames, feeServerEnabled)

    def disconnectFromFeeServers(self):
        
        self.detectorHandler.disconnectFromFeeServers()
        
    def enableConnectedFeeServers(self, res):

        feeServerNames, feeServerEnabled = self.connectSettingsDialog.getFeeServers()
        for i in range(PHOS_MODS):
            for j in range(RCUS_PER_MODULE):
                if feeServerEnabled[i*(RCUS_PER_MODULE) + j] == True:
                    if res > 0:
                        self.moduleTabs[i].enableRcu(True, j)
                        self.moduleTabs[i].setEnabled(True)
#                    else:
#                        self.moduleTabs[i].enableRcu(False, j)
#                        self.moduleTabs[i].SetEnabled(False) #TODO: fix this such that the RCU is disabled on no connection
#                else:
                  #  self.moduleTabs[i].enableRcu(False, j)
                    
        # Need to enable TORs also ...

    def fetchLog(self, signal, moduleId):
        self.logHandler.getLogString(moduleId)
        
    def updateLogViewer(self, tmpSignal, logString):
        
        for i in range(PHOS_MODS):
            
            self.moduleTabs[i].addLogString(logString)

    def goReady(self, moduleId):

        self.moduleHandler.shutdown(moduleId)
        self.configureElectronicsDialog.start(self.moduleHandler, self.databaseHandler, moduleId, True)
        self.configureElectronicsDialog.doConfigure()
        self.moduleHandler.disableTrigger(moduleId)
        self.moduleHandler.enableTrigger(moduleId)
Example #13
0
    def initConnections(self):

        self.connect(self.connectSettingsAction, QtCore.SIGNAL("triggered()"), self.showConnectDialog)
        self.connect(self.connectAction, QtCore.SIGNAL("triggered()"), self.connectToFeeServers)
        self.connect(self.disconnectAction, QtCore.SIGNAL("triggered()"), self.disconnectFromFeeServers)

        self.dcsInterface = DcsInterfaceThreadWrapper(DcsInterface())
        
        self.feeCardHandler = FeeCardHandler(self.dcsInterface)
        self.truCardHandler = TruCardHandler(self.dcsInterface)
        self.rcuHandler = RcuHandler(self.dcsInterface)
        self.moduleHandler = ModuleHandler(self.dcsInterface)
        self.detectorHandler = DetectorHandler(self.dcsInterface)
        self.logHandler = LogHandler(self.dcsInterface)
        self.databaseHandler = DatabaseHandler(self.dcsInterface)

        self.connect(self.feeCardHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.truCardHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.rcuHandler, QtCore.SIGNAL("fetchLog"), self.logHandler.getLogString)
        self.connect(self.moduleHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.detectorHandler, QtCore.SIGNAL("fetchLog"), self.fetchLog)
        self.connect(self.logHandler, QtCore.SIGNAL("gotLog"), self.updateLogViewer)

        self.connect(self, QtCore.SIGNAL("viewFee"), self.showFeeDialog)
        self.connect(self, QtCore.SIGNAL("viewdTru"), self.showTruDialog)
        self.connect(self, QtCore.SIGNAL("viewRcu"), self.showRcuDialog)
        
        self.connect(self, QtCore.SIGNAL("toggleFee"), self.feeCardHandler.toggleOnOff)
        self.connect(self, QtCore.SIGNAL("toggleTru"), self.truCardHandler.toggleOnOff)
        self.connect(self, QtCore.SIGNAL("rcuUpdateStatus"), self.rcuHandler.updateStatus)
        self.connect(self, QtCore.SIGNAL("rcuToggleOnOff"), self.rcuHandler.toggleOnOff)
        
#        self.connect(self, QtCore.SIGNAL("turnOnModule"), self.moduleHandler.turnOn)
        self.connect(self, QtCore.SIGNAL("turnOnModule"), self.goReady)
        self.connect(self, QtCore.SIGNAL("shutdownModule"), self.moduleHandler.shutdown)

        self.connect(self, QtCore.SIGNAL("showModuleProperties"), self.showModulePropertiesDialog)
        self.connect(self, QtCore.SIGNAL("configureElectronicsModule"), self.showElectronicsConfigDialog)

        self.connect(self, QtCore.SIGNAL("enableTriggerModule"), self.moduleHandler.enableTrigger)
        self.connect(self, QtCore.SIGNAL("disableTriggerModule"), self.moduleHandler.disableTrigger)

        self.connect(self, QtCore.SIGNAL("FeeServerStarted"), self.enableConnectedFeeServers)        

        self.connect(self.detectorHandler, QtCore.SIGNAL("FeeServerStarted"), self.enableConnectedFeeServers)

        for i in range(PHOS_MODS):

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("toggleFee"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewFee"), self.extractSignal)
            
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("toggleTru"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewTru"), self.extractSignal)

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("rcuUpdateStatus"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("rcuToggleOnOff"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("viewRcu"), self.extractSignal)


            self.connect(self.moduleTabs[i], QtCore.SIGNAL("turnOnModule"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("shutdownModule"), self.extractSignal)
            
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("showModuleProperties"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("configureElectronicsModule"), self.extractSignal)

            self.connect(self.moduleTabs[i], QtCore.SIGNAL("enableTriggerModule"), self.extractSignal)
            self.connect(self.moduleTabs[i], QtCore.SIGNAL("disableTriggerModule"), self.extractSignal)

            self.connect(self, QtCore.SIGNAL("cardToggled" + str(i)), self.moduleTabs[i].updateFeeCard)
            self.connect(self, QtCore.SIGNAL("feeStateUpdated" + str(i)), self.moduleTabs[i].updateFeeCard)
            self.connect(self, QtCore.SIGNAL("statusUpdated" + str(i)), self.moduleTabs[i].updateRcu)


        self.connect(self.feeCardHandler, QtCore.SIGNAL("cardToggled"), self.translateFeeSignal)
        self.connect(self.rcuHandler, QtCore.SIGNAL("cardToggled"), self.translateFeeSignal)
        self.connect(self.rcuHandler, QtCore.SIGNAL("feeStateUpdated"), self.translateFeeSignal)

        self.connect(self.rcuHandler, QtCore.SIGNAL("statusUpdated"), self.translateRcuSignal)
Example #14
0
def not_authed(data, parameter, user):
    LogHandler.log_warning("User is not authed")
    return {"error": "not_authed"}
Example #15
0
from PIL import ImageFont

from time import *
import subprocess
import os
import sys
import importlib
import oled_gui_widgets
myfolder = os.path.dirname(os.path.abspath(__file__))

# import pages source path
page_files_path = "pages"
sys.path.append(page_files_path)

import LogHandler
oledlog = LogHandler.LogHandler("oled")

import threading

import ButtonHandler
import prctl

from datetime import datetime

import JoystickHandler

import joystick_elements

try:
    import hapticenginge_interface as hei
    hei.hapt.set_channel_clean(
Example #16
0
from LogHandler import *

g_main_log = LogHandler('main')
Example #17
0
#!/usr/bin/python3
#GPIO USAGE: https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/
#GPIO PINOUT: https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/
try:
    import RPi.GPIO as GPIO
except RuntimeError:
    print(
        "Error importing RPi.GPIO!  This is probably because you need superuser privileges.  You can achieve this by using 'sudo' to run your script"
    )
import LogHandler
fancontroll = LogHandler.LogHandler("fancontroll")
import LocalMachine
import time
import os
import sys
myfolder = os.path.dirname(os.path.abspath(__file__))


def rpienv_source():
    import subprocess
    if not os.path.exists(str(myfolder) + '/.rpienv'):
        print("[ ENV ERROR ] " + str(myfolder) + "/.rpienv path not exits!")
        sys.exit(1)
    command = ['bash', '-c', 'source ' + str(myfolder) + '/.rpienv -s && env']
    proc = subprocess.Popen(command, stdout=subprocess.PIPE)
    for line in proc.stdout:
        if type(line) is bytes:
            line = line.decode("utf-8")
        try:
            name = line.partition("=")[0]
            value = line.partition("=")[2]
Example #18
0
 def log_request(self, code=None, size=None):
     message = "Web Request: " + str(self.client_address[0]) + ":" + str(
         self.client_address[1])
     message += " " + self.command + " " + self.path + " (" + self.request_version + ")"
     message += " " + str(code)
     LogHandler.log_warning(message)
Example #19
0
class WebServer(BaseHTTPServer.BaseHTTPRequestHandler):
    """
    Send HEAD response to client if that is all they have requested
    """
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    """
    Handle GET requests to the server
    """

    def do_GET(self):
        if string.lower(self.path).startswith("/api/"):
            self.handle_api_call()
        else:
            self.handle_web_call()

    """
    Handle POST requests to the server
    """

    def do_POST(self):
        if string.lower(self.path).startswith("/api/"):
            self.handle_api_call()
        else:
            self.handle_web_call()

    """
    Log that a request has been made. Occurs after headers are sent back.
    """

    def log_request(self, code=None, size=None):
        message = "Web Request: " + str(self.client_address[0]) + ":" + str(
            self.client_address[1])
        message += " " + self.command + " " + self.path + " (" + self.request_version + ")"
        message += " " + str(code)
        LogHandler.log_warning(message)

    """
    Handles all calls to the API
    """

    def handle_api_call(self):
        # Map API Calls to functions
        api_mapping = {
            "default": API.bad_call,
            "invalid_data": API.invalid_data,
            "not_authed": API.not_authed,
            "auth/login": API.auth_login,
            "auth/logout": API.auth_logout,
            "ptu/update": API.not_implimented,
            "ptu/urgent": API.not_implimented,
            "admin/add": API.administrator_add,
            "admin/edit": API.administrator_edit,
            "admin/remove": API.not_implimented,
            "psa/add": API.psa_add,
            "psa/edit": API.psa_edit,
            "psa/remove": API.not_implimented,
            "po/add": API.po_add,
            "po/edit": API.po_edit,
            "po/remove": API.not_implimented,
            "ptu/add": API.not_implimented,
            "ptu/edit": API.not_implimented,
            "ptu/remove": API.not_implimented
        }

        # Get the API Call and the parameter
        call = string.lower(self.path)[5:]
        parameter = ""
        if call.count('/') == 2:
            call, parameter = call.rsplit("/", 1)

        # Grab the data
        data_length = self.headers.getheader('content-length')
        if data_length == None:
            data = "{}"
        else:
            data_length = int(data_length)
            data = self.rfile.read(data_length)

        # Check data is valid JSON
        try:
            jsondata = json.loads(data)
        except ValueError, e:
            jsondata = json.loads("{}")
            call = "invalid_data"

        # Auth
        authed = False
        ret = ""
        try:
            ret, user = API.auth_login(jsondata, "", "")
        except KeyError:
            LogHandler.log_error("User failed to auth\r\n" + str(jsondata))
        if ret == {"error": "success"}:
            authed = True

        if not call.startswith("auth") and not authed:
            call = "not_authed"

        # Get the mapping
        try:
            command = api_mapping[call]
            self.send_response(200)
        except KeyError:
            LogHandler.log_warning("Illegal API Call: " + str(call))
            command = api_mapping["default"]
            self.send_response(400)

        # Finish Headers
        self.send_header("Content-type", "application/json")
        self.end_headers()

        # Execute the mapping and respond
        try:
            response = command(jsondata, parameter, user)
        except KeyError, ke:
            LogHandler.log_error("data was malformed or missing when processing\r\n" + \
                    str(jsondata) + "\r\n" + str(ke[0]))
            response = {"error": "failure"}
Example #20
0
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import ConfigParser
import LogHandler

global logger
logger = LogHandler.Start()


def InitSelenium():
    try:

        config = ConfigParser.ConfigParser()
        config.read('config.ini')
        try:
            optionsString = config.get('DEFAULT', 'chromeOptions')
            optionsList = optionsString.split(",")

            chrome_options = Options()

            for option in optionsList:
                chrome_options.add_argument(option)

            driver = webdriver.Chrome(chrome_options=chrome_options)
        except:
            logger.info("Chrome options don't exist")
            driver = webdriver.Chrome()

        return driver
    except Exception as e:
Example #21
0
#!/usr/bin/python3

import os
import sys
myfolder = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(myfolder, "../lib/"))
import LedHandler
import ConfigHandler
import LogHandler
mylogger = LogHandler.LogHandler("rgb_led_controller")
import time


def rgb_config_manager():
    # set config handler
    rgb = ConfigHandler.RGB_config_handler()

    # set pins
    green = LedHandler.LedHandler(channel=12)
    red = LedHandler.LedHandler(channel=32)
    blue = LedHandler.LedHandler(channel=33)

    #ledstate init
    led_state = ""

    # init service status on config
    rgb.put("SERVICE", "ON", secure=False)
    rgb.put("LED", "OFF", secure=False)

    while True:
        try:
Example #22
0
def invalid_data(data, parameter, user):
    LogHandler.log_warning("Malformed Data Received")
    return {"error": "invalid_data"}
Example #23
0
def auth_logout(data, parameter, user):
    username = data["username"]
    LogHandler.log_info(str(username) + " is logging out")
    return {"error": "success"}
Example #24
0
import socket
import sys
from thread import *
import time
import LogHandler
mylogger = LogHandler.LogHandler("clasterCoreSocketServer")


class SocketServer():
    def __init__(self,
                 host='',
                 port=1602,
                 silentmode=False,
                 only_internal_mode=False):
        self.silentmode = silentmode
        self.prompt = "> "
        self.host = host
        self.port = port
        self.connected_clients = 0
        self.only_internal_mode = only_internal_mode
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        mylogger.logger.warn("[INFO] Socket created: HOST: {} PORT: {}".format(
            self.host, self.port))
        self.bind_socket()
        self.server_core()

    def bind_socket(self, retry=20):
        for cnt in range(0, retry):
            #Bind socket to local host and port
            try:
                self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Example #25
0
def not_implimented(data, parameter, user):
    LogHandler.log_warning("API Method not implemented")
    return {"error": "not_implimented"}
Example #26
0
import HTMLFileScraper
import LinkScraper
import DataComparison
import ElevenThirteenManhattan
import TheEugene
import CitySkyline
import Bettina
import R9300
import Solil
import Eberhart
import Metronest
import time
import sys

fileHandler = FileHandler.FileHandler()
logHandler = LogHandler.LogHandler()
excelFileHandler = ExcelFileHandler.ExcelFileHandler()
htmlFileScraper = HTMLFileScraper.HTMLFileScraper()
linkScraper = LinkScraper.LinkScraper()
ETManhattan = ElevenThirteenManhattan.ElevenThirteenManhattan()
theEugene = TheEugene.TheEugene()


class GUI:

    progress_text = StringVar
    links_remaining_text = StringVar
    coding = StringVar
    file_folder_import_switch = StringVar

    owner_name = 'owner_name'
Example #27
0
import requests
import json
import SetWallpaper
import JsonConfig

bingUrl = "https://www.bing.com"
bingJsonUrl = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-cn"

unsplashUrl = "https://source.unsplash.com/random/"

urlHeaders = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}

log = LogHandler.Logger("PyWallpaper")

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def GetUrlText(url):
    try:
        requests.packages.urllib3.disable_warnings()
        response = requests.get(url,
                                headers=urlHeaders,
                                timeout=1000,
                                verify=False)
        '''if response.encoding == "ISO-8859-1":
            response.encoding = response.apparent_encoding'''
        response.raise_for_status()
    except requests.RequestException as e:
Example #28
0
File: Options.py Project: mtr/ttpd
     {'dest': 'high_load_limit',
      'type': 'int',
      'default': 50,
      'metavar': 'THREADS',
      'help': 'maximum number of concurrently running THREADS; ' \
      'the default is %(default)d'}),
    
    (['-L', '--log-level'],
     {'dest': 'log_level',
      'default': 'info',
      'metavar': 'LEVEL',
      'help': "the filter LEVEL used when logging; possible values are " \
      "%(log_levels)s; " \
      "the default is '%(default)s'" % \
      {'log_levels':
       ' < '.join(["'%s'" % x for x in LogHandler.get_log_levels()]),
       'default': '%(default)s'}}),
    
    (['-f', '--log-file'],
     {'dest': 'log_file',
      'default': '%s.log' % BASENAME,
      'metavar': 'FILE',
      'help': 'store the log in FILE; the default is \'%(default)s\''}),

    ]

ttpd_options = [
 
    (['-t', '--without-tad'],
     {'dest': 'run_tad',
      'default': True,
Example #29
0
            LogHandler.log_error("Database: Exception: %s" % e.args[0])

        if data == None or len(data) == 0:
            return None
        else:
            self.objects = []
            for i in range(len(data)):
                new = self.__class__.obj()
                for j in range(len(self.__class__.properties)):
                    p = self.__class__.properties[j]
                    v = data[i][j]
                    try:
                        setattr(new, str(p), v)
                    except ValueError, ve:
                        LogHandler.log_warning(
                            "Database: Select: Attribute Exception: " +
                            str(p) + ": %s" % ve.args[0])
                try:
                    setattr(new, self.__class__.id_property, data[i][-1])
                except ValueError, ve:
                    LogHandler.log_warning(
                        "Database: Select: Attribute Exception: " + str(p) +
                        ": %s" % ve.args[0])
                for key, val in searchterms.iteritems():
                    setattr(new, str(key), val)

                self.objects.append(new)
        return self.objects

    """
    Close the transaction. Doesn't save any changes not committed
Example #30
0
# -*- encoding: utf-8 -*-
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
import json
import time
import os
import sys
myfolder = os.path.dirname(os.path.abspath(__file__))
sys.path.append(myfolder)
import LogHandler
mylogger = LogHandler.LogHandler("confighandler")


def rpienv_source():
    import subprocess
    if not os.path.exists(str(myfolder) + '/.rpienv'):
        print("[ ENV ERROR ] " + str(myfolder) + "/.rpienv path not exits!")
        sys.exit(1)
    command = ['bash', '-c', 'source ' + str(myfolder) + '/.rpienv -s && env']
    proc = subprocess.Popen(command, stdout=subprocess.PIPE)
    for line in proc.stdout:
        if type(line) is bytes:
            line = line.decode("utf-8")
        try:
            name = line.partition("=")[0]
            value = line.partition("=")[2]
            if type(value) is unicode:
                value = value.encode('ascii', 'ignore')
            value = value.rstrip()
            os.environ[name] = value
        except Exception as e:
            if "name 'unicode' is not defined" != str(e):
Example #31
0
Adds a USER to the system
"""
def user_add(data, parameter, au):
    for property in TransactionBean.UserBean.properties:
        try:
            print("Setting UserBean" + str(property) + " To " + data["user"][str(property)])
            setattr(au.user_info, str(property), data["user"][str(property)])
        except ValueError, ve:
            LogHandler.log_warning("Value Error: " + str(ve[0]))
    
    for property in TransactionBean.AuthenticationBean.properties:
        try:
            print("Setting AuthenticationBean" + str(property) + " To " + data["auth"][str(property)])
            setattr(au.auth_info, str(property), data["auth"][str(property)])
        except ValueError, ve:
            LogHandler.log_warning("Value Error: " + str(ve[0]))
    au.create()
    id = au.id
    return {"error": "success", "id": id}

"""
Adds an Administrator to the system
"""
def administrator_add(data, parameter, user):
    return user_add(data, parameter, AuthUser.CreateAdministrator())

"""
Adds a Pool Shop Admin to the system
"""
def psa_add(data, parameter, user):
    return user_add(data, parameter, AuthUser.CreatePoolShopAdmin())
Example #32
0
import socket
import sys
from thread import *
import time
import LogHandler
mylogger = LogHandler.LogHandler("dictSocketHandlerCore")

class SocketServer():

    def __init__(self, host='', port=8888, silentmode=True, only_internal_mode=True):
        self.serverside_printout("=> Initialize SocketServer")
        self.silentmode = silentmode
        self.prompt = "> "
        self.host = host
        self.port = port
        self.connected_clients=0
        self.only_internal_mode = only_internal_mode
        self.start_socket_server()

    def start_socket_server(self):
        self.serverside_printout("=> Start socket server")
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        mylogger.logger.warn("[INFO] Socket created: HOST: {} PORT: {}".format(self.host, self.port))

        self.bind_socket()
        self.server_core()

    def bind_socket(self, retry=20):
        self.serverside_printout("=> Attampt to bind socket: {}:{}".format(self.host, self.port))
        for cnt in range(0, retry):
            #Bind socket to local host and port
Example #33
0
def bad_call(data, parameter, user):
    LogHandler.log_warning("API Method does not exist")
    return {"error": "bad_call"}