Beispiel #1
0
def checkAvailability():
    global wasAvailable
    global pooltableChecker
    oldImagePath = ConfigHandler.getOldImagePath()
    currentImagePath = ConfigHandler.getCurrentImagePath()
    isAvailable = True

    currentImage = Path(currentImagePath)
    oldImage = Path(oldImagePath)

    Logger.info("Comparing images")

    if oldImage.is_file():
        try:
            isAvailable = pooltableChecker.isTableFree(currentImagePath,
                                                       oldImagePath)
        except Exception as e:
            isAvailable = None
            Logger.exception(e)

    if isAvailable != wasAvailable:
        Logger.info('Posting availability: ' + str(isAvailable))
        mattermost_client.updateMattermostAvailable(isAvailable)

    wasAvailable = isAvailable
    copyfile(currentImagePath, ConfigHandler.getRawImagePath())
    currentImage.rename(oldImagePath)
Beispiel #2
0
    def ConfirmConfig(self):
        string = ""
        config = self.filesInProject.toPlainText()
        for j in range(config.find("#") + 1, config.find("?") - 1):
            string += config[j]
        f = open("programFile.txt", "w")
        string = string.replace(os.path.basename(string), 'CONFIG.txt')
        f.write(string)
        f.close()
        string = string.replace(os.path.basename(string), 'project.hex')
        f = open(string, "w")
        f.close()
        f = open(string, "w")
        tmp = """CPU =#ENDCPU
FILELOCATIONS =#ENDFILELOCATIONS
CPUTYPE =#ENDCPUTYPE
PROGTYPE =#ENDPROGTYPE
PROGLOCATION =#ENDPROGLOCATION
BAUD =#ENDBAUD
PROJECTLOCATION =#ENDPROJECTLOCATION"""
        f.write(tmp)
        f.close()
        handler.BuildConfigFile(self.CPU.text(),
                                self.filesInProject.toPlainText(),
                                self.CPUTYPE.text(), self.PROGTYPE.text(),
                                self.PROGLOCATION.text(),
                                self.BAUD.currentText())
Beispiel #3
0
 def test_forged_data_has_woken_up(self):
     data_location = reduce(
         os.path.join,
         [ConfigHandler.getPath(),'test','TestInfo','SleepCheckerWokenUp.txt'])
     sleep_checker = SleepChecker.SleepChecker(data_location=data_location)
     self.assertFalse(sleep_checker.isAsleep())
     self.assertTrue(sleep_checker.isAwake())
Beispiel #4
0
 def test_no_data(self):
     data_location = reduce(
         os.path.join,
         [ConfigHandler.getPath(),'test','TestInfo','SleepCheckerNothing.txt'])
     sleep_checker = SleepChecker.SleepChecker(data_location=data_location)
     self.assertFalse(sleep_checker.isAsleep())
     self.assertTrue(sleep_checker.isAwake())
def Compile(projectConfigLocation):
    if not projectConfigLocation:
        return 123
    Lookup = ["CPU =","FILELOCATIONS ="]
    Configdata = handler.GetConfigData(Lookup)

    CPU = Configdata [0]
    FILELOCATIONS = Configdata[1]

    # These are the files needed to store vital information for the parsing of the compile command
    CompileString = ""
    FILENAMES = []
    COMPILEFILES = [];
    PROJECTLOCATION = "";

    for i in range (0,len(FILELOCATIONS)):
        FILENAMES.append((os.path.basename(FILELOCATIONS[i]))) # Stores the names of .c files in this array

    PROJECTLOCATION = os.path.abspath(FILELOCATIONS[0]) # Stores the path to the first .c file
    PROJECTLOCATION = PROJECTLOCATION.replace(FILENAMES[0],'project.elf')   # changes the .c file into project.elf
    # This is done to generate project.elf file in the same location as the first .c file
    # Note that the first .c file is not effected by this action

    for i in range(0,len(FILELOCATIONS)):
        tmp = FILELOCATIONS[i] # Fetches the path to a .c file and stores it into a temporary file
        tmp = tmp[:-1] + 'o' # Changes the files type from .c to .o (ONLY IN A STRING, NOT ON ACTUAL FILE)
        COMPILEFILES.append(tmp) # Appends the previously edited string into an array

    for i in range(0, len(FILELOCATIONS)):
        CompileString = 'avr-gcc -Wall -g -Os -c -mmcu=' + CPU +' ' + FILELOCATIONS[i] +' -o ' + COMPILEFILES[i]  # Generates the compile command for the current file
        print("\n \n "+CompileString+"\n\n")
        proc = subprocess.Popen(shlex.split(CompileString), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = proc.communicate()  # Runs the compile command
        print(out)
        print(err)

    LinkString = "avr-gcc -mmcu=" + CPU +" "# Header of the link command

    for i in range(0,len(FILELOCATIONS)):
        print(COMPILEFILES[len(FILELOCATIONS)- 1 - i] + "\n")
        LinkString += COMPILEFILES[len(FILELOCATIONS)- 1 - i] + " " # Appends the file locations of the compiled files (.o)

    LinkString += " -o " + PROJECTLOCATION # Appends the the file with the location of the project.elf file
    print("\n \n " + LinkString + "\n\n")
    # Converts project.elf into project.hex
    HexString = "avr-objcopy -O ihex -j .text -j .data " + PROJECTLOCATION + " " + PROJECTLOCATION.replace('project.elf','project.hex')
    print("\n \n " + HexString + "\n\n")
    print (LinkString)
    print(HexString)
    # Runs the link command
    proc = subprocess.Popen(shlex.split(LinkString), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    print(out)
    print(err)
    # Runs the convert command
    proc = subprocess.Popen(shlex.split(HexString), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    print(out)
    print(err)
Beispiel #6
0
 def scrape(self):
     config = ConfigHandler.ConfigHandler()
     ebayScraper = Ebay()
     config.setConfig('../data/config.json')
     config.loadConfig() 
     ebayScraper.addKeywords(config.getKeywords())
     ebayScraper.setPagesToScrape(1)
     ebayScraper.scrapeSite()
Beispiel #7
0
 def __init__(self, tkRoot):
     self.root = tk.Toplevel()
     self.Q = Q.Queue()
     self.hNET = None
     self.hPlayerAi = None
     self.cfg = ConfigHandler.ConfigHandler('warpwar.ini')
     print(self.cfg.Server.serverIP)
     print(self.cfg.Server.serverPort)
     print(self.cfg.PlayerAI.name)
 def test_write_to_location(self):
     test_path = reduce(os.path.join,
                        [ConfigHandler.getPath(), 'test', 'TestInfo'])
     self.assertTrue(os.path.exists(test_path))
     junk_location = os.path.join(test_path, 'junk.txt')
     DataWriter.writeDataToFile(data='myjunk', location=junk_location)
     file_opened = open(junk_location, 'r')
     self.assertEquals('myjunk', file_opened.read())
     file_opened.close()
     os.remove(junk_location)
 def test_write_to_directory_that_dne(self):
     test_path = reduce(os.path.join,
                        [ConfigHandler.getPath(), 'test', 'TestInfo'])
     test_path_2 = os.path.join(test_path, 'NewPathThatDNE')
     junk_location_2 = os.path.join(test_path_2, 'junk.txt')
     DataWriter.writeDataToFile(data='myjunk', location=junk_location_2)
     file_opened = open(junk_location_2, 'r')
     self.assertEquals('myjunk', file_opened.read())
     file_opened.close()
     os.remove(junk_location_2)
     os.rmdir(test_path_2)
Beispiel #10
0
    def __init__(self, master, **kwargs):
        TK.LabelFrame.__init__(self, master, text="Server", **kwargs)

        self.cfg = ConfigHandler.ConfigHandler('warpwar.ini')
        print("serv --init")
        print(self.cfg.Server.serverIP)
        print(self.cfg.Server.serverPort)

        self.startstop = None
        self.hNET = None

        self.initGui()
Beispiel #11
0
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:
            rgb_dict = rgb.config_watcher()
            mylogger.logger.info("config watcher dict: {}".format(rgb_dict))
            if rgb_dict is not None:
                red.led_dc_controller(rgb_dict["RED"])
                green.led_dc_controller(rgb_dict["GREEN"])
                blue.led_dc_controller(rgb_dict["BLUE"])
                mylogger.logger.info("RGB dict: R{} G{} B{}".format(
                    rgb_dict["RED"], rgb_dict["GREEN"], rgb_dict["BLUE"]))
                # start led
                if rgb_dict["LED"] != "ON" and led_state != rgb_dict["LED"]:
                    mylogger.logger.info("Turn OFF LED")
                    led_state = rgb_dict["LED"]
                    red.stop()
                    green.stop()
                    blue.stop()
                # stop led
                elif rgb_dict["LED"] == "ON" and led_state != rgb_dict["LED"]:
                    mylogger.logger.info("Turn ON LED")
                    led_state = rgb_dict["LED"]
                    red.start()
                    green.start()
                    blue.start()

                if rgb_dict["SERVICE"] != "ON":
                    mylogger.logger.info("Turn OFF service")
                    red.stop()
                    green.stop()
                    blue.stop()
                    red.__del__()
                    green.__del__()
                    blue.__del__()
                    break
        except KeyboardInterrupt as e:
            mylogger.logger.info("Program is existing: Ctrl-C")
Beispiel #12
0
def getLog():
    try:
        path = ConfigHandler.getLogPath()
        logFile = open(path, "r+")
        logFile.seek(0, os.SEEK_END)
        logFile.seek(logFile.tell() - 500, os.SEEK_SET)
        line = logFile.readline()
        logText = ""
        while line:
            logText += line
            line = logFile.readline()
        return logText
    finally:
        logFile.close()
Beispiel #13
0
def printStartup():
    print("PYthon Grader 2")
    try:
        print(
            f"Version - {re.search(versionFinder, open(PathHandler.relJoin('README.md'), 'r').read()).group()}"
        )
    except:
        print("Couldn't find version in README.md")
    print("By Josh Bedwell")

    if cfg.showWarning():
        print("")
        print(open(PathHandler.relJoin('warning.txt')).read())
        print("")
Beispiel #14
0
    def __init__(self, master, owner, **kwargs):
        TK.LabelFrame.__init__(self, master, text="Not Connected", **kwargs)

        self.cfg = ConfigHandler.ConfigHandler('warpwar.ini')
        print("connpane --init")
        print(self.cfg.Client.serverIP)
        print(self.cfg.Client.serverPort)

        self.owner = owner

        self.conDiscon = None
        self.hCon = None

        self.initGui()
Beispiel #15
0
    def __init__(self, master, **kwargs):
        TK.LabelFrame.__init__(self, master, text="Computer Player", **kwargs)

        print("aipane --init")
        self.hPlayerAi = None
        self.startstop = None

        #  This list must come from the game we connect to
        self.startBaseList = ["Ur Mosul Larsu", "Nineveh Babylon Ugarit"]
        self.startingBases = ['Babylon', 'Nineveh', 'Ugarit']

        self.cfg = ConfigHandler.ConfigHandler('warpwar.ini')
        print(self.cfg.PlayerAI.name)
        print(self.cfg.Server.serverIP)
        print(self.cfg.Server.serverPort)

        self.initGui()
def Upload(projectConfigLocation):
    if not projectConfigLocation:
        return 123
    Lookup = ["CPUTYPE =", "PROGTYPE =","PROGLOCATION =","BAUD =","PROJECTLOCATION ="]
    Configdata = handler.GetConfigData(Lookup)
    CPUTYPE = Configdata[0]
    PROGTYPE = Configdata[1]
    PROGLOCATION = Configdata[2]
    BAUD = Configdata[3]
    PROJECTLOCATION = Configdata[4]

    # Generation of the upload script for avrdude
    # It has to be run with sudo otherwise the command might not be permited to execute
    UploadString = "sudo avrdude -p " + CPUTYPE + " -c " + PROGTYPE + " -P " + PROGLOCATION + " -b " + BAUD + ' -U flash:w:' + PROJECTLOCATION
    # Runs the upload script
    print(UploadString)
    proc = subprocess.Popen(shlex.split(UploadString), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    print(out)
    print(err)
Beispiel #17
0
import SqlHandler
import ConfigHandler
from WebScraper import Ebay

ebay = Ebay()
config = ConfigHandler.ConfigHandler()

items = []
time_interval = 0


def load_config():
    config.load_config("../data/config.json")


def scrape():
    #DELETING CURRENT DATABASE REMOVE THIS LATER
    SqlHandler.drop_table('../data/web_items.db')
    SqlHandler.create_database('../data/web_items.db')

    if config.get_keywords().count is 0:
        print("No keywords set, did you forget to load the config?")

    #Load config
    config.set_config("../data/config.json")
    config.load_config()

    #Scrape sites
    ebay.add_keywords(config.get_keywords())
    ebay.set_pages_to_scrape(config.get_pages_to_scrape())
    ebay.scrape_site()
Beispiel #18
0
    HttpHandler.clearShoppingCart()
    return checkIfContinue(priceTotalOrder, cardsTotalOrder)

def checkIfContinue(priceTotalOrder, cardsTotalOrder):
    print "Ping Info : " + datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') + '\n\tCards Total Purchased : ' + str(cardsTotalOrder) + '/' + str(ConfigHandler.MaxCardsTotalOrder)  + '\n\tPrice Total Purchased : ' + str(priceTotalOrder) + '/' + str(ConfigHandler.MaxPriceTotalOrder)
    if priceTotalOrder >= ConfigHandler.MaxPriceTotalOrder:
        return False
    if cardsTotalOrder >= ConfigHandler.MaxCardsTotalOrder:
        return False
    return True

if __name__ == "__main__":
    configFile = None
    if len(sys.argv) == 2:
        configFile = sys.argv[1]
    ConfigHandler.initConfig(configFile)
    ConfigHandler.displayConfig()
    HttpHandler.login(ConfigHandler.RaiseUser, ConfigHandler.RaisePass, ConfigHandler.VisibleBrowser)
    MailHandler.init(ConfigHandler.GmailUser, ConfigHandler.GmailPass)

    ret = True
    while ret:
        try:
            ret = process()
            time.sleep(5)
        except Exception,e:
            print str(e)
            ret = False

    time.sleep(5)
    HttpHandler.logout()
Beispiel #19
0
            value = value.rstrip()
            os.environ[name] = value
        except Exception as e:
            if "name 'unicode' is not defined" != str(e):
                print(e)
    proc.communicate()


rpienv_source()

try:
    confhandler_path = os.path.join(
        os.path.dirname(os.environ['CONFIGHANDLERPY']))
    sys.path.append(confhandler_path)
    import ConfigHandler
    cfg = ConfigHandler.init()
    default_index_from_cfg = str(
        cfg.get(section="INSTALL_OLED", option="defaultindex")).rstrip()
except Exception as e:
    oledlog.logger.warn("Import config handler failed: " + str(e))
    ConfigHandler = None
    default_index_from_cfg = "-undef-option"

#############################################################################
#                             THREAD TIMING                                 #
#############################################################################
performance_setup_dict = {
    "ULTRALOW": 1.6,
    "LOW": 1.4,
    "OPTIMUM": 1,
    "MEDIUM": 0.5,
Beispiel #20
0
def postRawImage():
    postImage(ConfigHandler.getRawImagePath())
Beispiel #21
0
def postCroppedImage():

    poolFinder = PoolTableFinder()
    poolFinder.saveCroppedImage()

    postImage(ConfigHandler.getCroppedImagePath())
Beispiel #22
0
import requests
import ssl
import ConfigHandler
import socket

from ScoreKeeper import ScoreKeeper
from PoolTableFinder import PoolTableFinder

mattermostConfig = ConfigHandler.getMattermostConfig()

mattermostHookUrl = mattermostConfig['webhook']
user = mattermostConfig['user']
password = mattermostConfig['password']
mattermostApiUrl = mattermostConfig['api']
mattermostCommandChannel = mattermostConfig['commandChannel']
mattermostInfoChannel = mattermostConfig['infoChannel']

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

availableIconUrl = "https://previews.123rf.com/images/floralset/floralset1706/floralset170600119/80446026-billiard-green-pool-ball-with-number-6-snooker-transparent-background-vector-illustration-.jpg"
busyIconUrl = "https://previews.123rf.com/images/floralset/floralset1706/floralset170600120/80446027-billiard-red-pool-ball-with-number-3-snooker-transparent-background-vector-illustration-.jpg"

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

token = None

latestEntry = None

userId = None

def get_confighandler_object():
    global CFG
    if CFG is None:
        CFG = ConfigHandler.init(validate_print=False)
    return CFG
Beispiel #24
0
def get_rpitools_version():
    cfg = ConfigHandler.init(validate_print=False)
    data = cfg.get("GENERAL", "rpitools_version")
    return data
Beispiel #25
0
import logging
import ConfigHandler
import os
import mattermost_client as mattermost

logger = logging.getLogger("pool-ping")
fileLogger = logging.FileHandler(ConfigHandler.getLogPath())
fileLogger.setLevel(logging.DEBUG)
fileLogger.setFormatter(
    logging.Formatter(
        fmt='%(name)s - %(asctime)s # %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'))
logger.addHandler(fileLogger)


def info(msg):
    print(msg)


def error(msg):
    print(msg)
    mattermost.postError(msg)


def exception(e):
    print(e)
    mattermost.postError(str(e))


def getLog():
    try:
Beispiel #26
0
#!/usr/bin/python3

import argparse
import os
import sys
myfolder = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(myfolder, "../lib/"))
import ConfigHandler
import subprocess
import time

rgb = ConfigHandler.RGB_config_handler()

parser = argparse.ArgumentParser()
parser.add_argument("-r", "--red", help="RED component 0-100")
parser.add_argument("-g", "--green", help="GREEN component 0-100")
parser.add_argument("-b", "--blue", help="BLUE component 0-100")
parser.add_argument("-s", "--service", help="led service ON / OFF")
parser.add_argument("-l", "--led", help="led ON / OFF")
parser.add_argument("-sh",
                    "--show",
                    action='store_true',
                    help="show database values")

args = parser.parse_args()
R = args.red
G = args.green
B = args.blue
led_status = args.led
service_status = args.service
show = args.show
import copy
import threading
import FilterTests as ft
import ConfigHandler as ch
import os
import copy
import time

# The general loop of this file is explained here: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html

os.system(
    'sh cameraconfig.sh'
)  # This sets certain parameters for the camera such as disabling autoexposure, setting exposure, etc.

CONFIG = ch.getConfig(
    'vision_processing.cfg'
)  # This allows us to define constants from a configuration file,
# rather than in the code
cap = cv2.VideoCapture(CONFIG['camera'])  # defines our camera
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 426)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
#cap = cv2.VideoCapture('footage.avi')

# Constants
RESOLUTION = (cap.get(cv2.CAP_PROP_FRAME_WIDTH),
              cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
VT_HEIGHT = CONFIG['VT_HEIGHT']
LOWER_THRESH = np.array(CONFIG['LOWER_THRESH'])
UPPER_THRESH = np.array(CONFIG['UPPER_THRESH'])
#LOWER_THRESH = np.array([178, 190, 128])
Beispiel #28
0
 def __init__(self):
     self.imageHandler = ImageHandler()
     self.rawImagePath = ConfigHandler.getRawImagePath()
     self.croppedImagePath = ConfigHandler.getCroppedImagePath()
Beispiel #29
0
            self.rootframe.specialKeyEntry.delete(0, tkinter.END)
            self.rootframe.specialKeyEntry.insert(0,
                                                  self.model.get("specialKey"))
            if self.model.get("defaultKey") == 1:
                self.rootframe.specialKeyEntry.config(state=tkinter.DISABLED)
        if step == StepThree:
            self.rootframe.treeview.delete()
            for slot in self.model.getASlotlist():
                if slot is not None:
                    self.rootframe.treeview.insert(
                        '',
                        'end',
                        text=str(slot.getPosition()),
                        values=(slot.getItem(), slot.getCount(),
                                slot.getPrice()))
        if step == lastStep:
            self.rootframe.entryForFilepath.delete('0', tkinter.END)
            self.rootframe.entryForFilepath.insert(0,
                                                   self.model.get("filepath"))
            self.rootframe.filenameEntry.delete('0', tkinter.END)
            self.rootframe.filenameEntry.insert(0, self.model.get("filename"))


if __name__ == "__main__":

    configuration = ConfigHandler.ConfigHandler()
    configuration.loadFile("configuration.conf")

    root = AfkFinder(configuration)
    root.mainloop()
Beispiel #30
0
    orderInfoList = []
    for orderNumber in orderList:
        orderInfoList.append(HttpHandler.getOrder(orderNumber))
    return orderInfoList


def saveListToFile(fName, orderInfoList):
    with open(fName, 'w') as f:
        f.write("Face Value, Price, SN, PIN\n")
        for orderInfo in orderInfoList:
            line = str(orderInfo["faceValue"]) + "," + str(
                orderInfo["price"]) + "," + str(orderInfo["SN"]) + "," + str(
                    orderInfo["PIN"])
            f.write(line + "\n")


if __name__ == "__main__":
    configFile = None
    if len(sys.argv) == 2:
        configFile = sys.argv[1]
    ConfigHandler.initConfig(configFile)
    ConfigHandler.displayConfig()
    raw = raw_input(
        "Input the start date of your order (mm/dd/yy) or how many orders you want to look up (1 , 2 etc)."
    )
    HttpHandler.login(ConfigHandler.RaiseUser, ConfigHandler.RaisePass,
                      ConfigHandler.VisibleBrowser)
    process(raw)
    time.sleep(5)
    HttpHandler.logout()
 def test_path_exists(self):
     path = ConfigHandler.getPath()
     self.assertTrue(os.path.exists(path))