Пример #1
0
class CommandLock(FileLock):
    """Simple process locking.
  """
    log = Logger.getLogger(Logger.myname + '.CommandLock')

    ######################################################################
    # Overridden methods
    ######################################################################
    def __enter__(self):
        try:
            super(CommandLock, self).__enter__()
        except:
            raise CommandLockError("Could not lock file {0}", self.path)
        return self

    ######################################################################
    def __init__(self, filePath, readonly=True):
        super(CommandLock, self).__init__(filePath,
                                          "r" if readonly else "r+",
                                          timeout=20)

    ######################################################################
    def __repr__(self):
        lst = [str(self), "["]
        lst.append(','.join('='.join([key, str(getattr(self, key))])
                            for key in self.__dict__))
        lst.append("]")
        return "".join(lst)

    ######################################################################
    def __str__(self):
        return "{0}({1})".format(type(self).__name__, self.path)

    ######################################################################
    def _createFile(self):
        super(CommandLock, self)._createFile()
        # For now, we default to permitting shared locks from non-root
        # processes. The sysadmin may change this; we won't change the
        # permissions once the file has been created.
        #
        # N.B.: The names may not be sanitized for use with a shell!
        cmd = Command(["chmod", "644", self.path])
        cmd.run()
Пример #2
0
import threading, socket

from utils import Logger, blackboard
from utils.GameControlData import GameControlData

GAME_CONTROLLER_PORT = 3838

# setup logger for network related logs
logger = Logger.getLogger("GameController")


class GameController(threading.Thread):
    """
    The GameController class is used to receive the infos of a game.
    If new data was received, it gets parsed and published on the blackboard.
    """
    def __init__(self, source=None):
        """
        Constructor.
        Inits class variables and establish the udp socket connection to the GameController.
        """
        super().__init__()

        self.__cancel = threading.Event()

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.socket.bind(('', GAME_CONTROLLER_PORT))
        self.socket.settimeout(5)  # in sec
Пример #3
0
	def __init__(self):
		self.logger = Logger.getLogger()
Пример #4
0
import queue
import sqlite3
import threading

import time

from utils import Logger, blackboard

# setup logger for network related logs
logger = Logger.getLogger("GoPro")

class GameLoggerSql(threading.Thread):

    def __init__(self, db, teams=None):
        super().__init__()

        self.__cancel = threading.Event()

        self.db = db
        self.teams = teams if teams is not None else {}
        self.maxTimeGameValid = 60*30

        self.state = { 'v': None }
        self.last_id = 0

        self.init_database()

    def run(self):
        con = sqlite3.connect(self.db)
        cur = con.cursor()
        while not self.__cancel.is_set():
Пример #5
0
                        help="print debug logs")
    parser.add_argument(
        "-i",
        "--info",
        action="store_true",
        help="give infos of latest download version of each manga")
    parser.add_argument(
        "-u",
        "--update",
        action="store_true",
        help="update version of manga (with -u and -n option, fail otherwise)")
    parser.add_argument("-c",
                        "--chapter",
                        nargs='?',
                        const="1",
                        default=0,
                        type=int,
                        help="with -u and -n option, specify the version")
    args = parser.parse_args()

    Logger.getLogger().setMode("DEBUG" if args.verbose else "INFO ")

    if args.info:
        MainClass().showConfigFile(args)
    elif args.update:
        MainClass().updateConfigFile(args)
    else:
        MainClass().download(args)

    Logger.getLogger().close()
Пример #6
0
 def __init__(self):
     self._logger = Logger.getLogger()
Пример #7
0
#!/usr/bin/env python3
import threading, time, json, os
import psutil
os.environ["GST_DEBUG"] = "2"

from utils.GameController import GameController
from utils.GameControlData import GameControlData
from utils.SimpleHttpServer import SimpleHttpServer
from utils import Event, Logger

from PIL import Image, ImageDraw, ImageFont
from operator import itemgetter
import sys, os, traceback
import datetime

logger = Logger.getLogger("LiveStream")

# Required imports
# Gst, GstBase, GObject
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject

# Init Gobject Threads
# Init Gstreamer
GObject.threads_init()
Gst.init(None)

from gst_overlay.gstpipeline import GstPipeline
from gst_overlay.gst_overlay_cairo import GstOverlayCairo, from_pil
Пример #8
0
import os
import subprocess
import threading
from utils import Logger

# setup logger for bluetooth related logs
logger = Logger.getLogger("Bluetooth")


class Bluetooth(threading.Thread):
    def __init__(self, mac, enable_signals: bool = False):
        super().__init__()

        self.mac = mac
        self.msg = ''
        self.process = None
        self.enable_signals = enable_signals

    def run(self):
        with subprocess.Popen([
                'gatttool', '-i', 'hci0', '-t', 'random', '-b', self.mac,
                '--char-write-req', '--handle', '0x002f', '--value', self.msg
        ],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              preexec_fn=self.__preexec_fn) as self.process:
            # retrieve output
            outs, errs = self.process.communicate()
            # log outputs
            if errs:
                logger.warning(' '.join(self.process.args))
Пример #9
0
class Service(YAMLObject):
    """Superclass for services.

  Every subclass of Service controls a service (such as an Albireo
  index or a VDO target) managed by this command. The create/remove/
  have methods are one-time operations that do things like 'albcreate'
  that are persistent, while start/stop/running are used to control
  the availability of the service, either manually or automatically at
  system boot and shutdown. The control commands are idempotent, and
  return values specified as exit codes for /etc/init.d scripts
  specified in the LSB.

  Methods:
    getName  (method on Service) returns a name for the object
    create   creates the service; done once, paired with 'remove'
    remove   removes the service
    have     returns True if the service has been created
    start    starts the service; idempotent; run at system boot
    stop     stops the service; idempotent; run at shutdown
    running  returns True if the service is running
    getKeys  returns a list of the keys to be stored in the
             configuration file
    status   returns the status of the service in YAML format
  """
    log = Logger.getLogger(Logger.myname + '.Service')
    yaml_tag = u"!Service"

    ######################################################################
    # Public methods
    ######################################################################
    @staticmethod
    def getKeys():
        """Returns a list of keys to be stored in the configuration file."""
        return []

    ######################################################################
    def getName(self):
        """Returns the name of a Service, as a string."""
        return self._name

    ######################################################################
    # Overridden methods
    ######################################################################
    @property
    def _yamlAttributeKeys(self):
        keys = ["name"]
        keys.extend(self.getKeys())
        return keys

    ######################################################################
    @property
    def _yamlData(self):
        data = super(Service, self)._yamlData
        data["name"] = self.getName()
        return data

    ######################################################################
    def _yamlSetAttributes(self, attributes):
        super(Service, self)._yamlSetAttributes(attributes)
        self._name = attributes["name"]

    ######################################################################
    @property
    def _yamlSpeciallyHandledAttributes(self):
        specials = super(Service, self)._yamlSpeciallyHandledAttributes
        specials.extend(["name"])
        return specials

    ######################################################################
    def __init__(self, name):
        super(Service, self).__init__()
        self._name = name

    ######################################################################
    def __str__(self):
        return "{0}({1})".format(type(self).__name__, self.getName())

    ######################################################################
    # Protected methods
    ######################################################################
    def _reprAttribute(self, key):
        """Returns a boolean indicating if the entry represented by 'key' from the
       instance's __dict__ should be included in the __repr__ result.

    Arguments:
      key (str):  key from instance's __dict__
    Returns:
      bool: True, if the __dict__ entry with the specified key should be
                  included in the __repr__ result
            False, otherwise
    """
        return not key.startswith('_')
Пример #10
0
	def download(self, args):
		downloader = Downloader()
		if args.name == "All":
			for configFile in os.listdir("config/"):
				res = downloader.download("config/" + configFile)
				self.printResult(res, configFile.split(".")[0])
		else:
			res = downloader.download("config/" + args.name + ".json")
			self.printResult(res, args.name)

if __name__ == '__main__':
	#parser arguments
	parser = argparse.ArgumentParser()
	parser.add_argument("-n", "--name", nargs='?', const="1", default="All",\
		type=str, help="the name of the manga to download: [ OnePiece, FairyTail, All ], default is All")
	parser.add_argument("-v", "--verbose", action="store_true", help="print debug logs")
	parser.add_argument("-i", "--info", action="store_true", help="give infos of latest download version of each manga")
	parser.add_argument("-u", "--update", action="store_true", help="update version of manga (with -u and -n option, fail otherwise)")
	parser.add_argument("-c", "--chapter", nargs='?', const="1", default=0, type=int, help="with -u and -n option, specify the version")
	args = parser.parse_args()

	Logger.getLogger().setMode( "DEBUG" if args.verbose else "INFO ")

	if args.info:
		MainClass().showConfigFile(args)
	elif args.update:
		MainClass().updateConfigFile(args)
	else:
		MainClass().download(args)

	Logger.getLogger().close()
Пример #11
0
import socket
import threading
import time

from utils import Logger, blackboard

# setup logger for network related logs
logger = Logger.getLogger("LED")


class LedStatusMonitor(threading.Thread):
    def __init__(self):
        super().__init__()

        self.__cancel = threading.Event()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.network = None
        self.gopro = None
        self.gc = None

    def run(self):
        while not self.__cancel.is_set():
            self.network = blackboard['network']
            self.gopro = blackboard['gopro']
            self.gc = blackboard['gamecontroller']

            # handle the blue led
            if self.network is None or self.network == 0:
                # (gopro) network not available/visible
                self.sendMessage(
Пример #12
0
import subprocess
import shutil
import re
import threading
import time

from utils import Logger, blackboard
from utils.Bluetooth import Bluetooth

# setup logger for network related logs
logger = Logger.getLogger("Network")


class Network(threading.Thread):
    """ Handles the connection to the GoPro wifi network."""

    def __init__(self, device:str, ssid:str, passwd:str, retries:int, mac:str = None):
        super().__init__()
        # creates a appropriate manager, based on the available network applications
        self.manager = NetworkManagerNmcli() if shutil.which('nmcli') is not None else NetworkManagerIw()

        self.device = self.manager.getWifiDevice(device)
        self.ssid = ssid
        self.passwd = passwd
        self.mac = mac
        self.retries = retries
        self.bt = None

        blackboard['network'] = 0

        self.__cancel = threading.Event()
Пример #13
0
import os
import re
import queue
import threading
import socket
import time
import json

from utils import Logger, blackboard

# setup logger for network related logs
logger = Logger.getLogger("GameLoggerLog")


class GameLoggerLog(threading.Thread):
    def __init__(self, folder, teams=None, log_invisible=False):
        super().__init__()

        self.__cancel = threading.Event()

        self.folder = folder
        self.teams = teams if teams is not None else {}
        self.log_invisible = log_invisible
        self.messages = queue.Queue()

        self.state = {'t1': None, 't2': None, 'h': None, 'v': None}
        self.last_file = None
        self.added_video = False

        self.extension = '.log'
        self.separator = ', '