class SoundController: """Mock-Up Class for controlling the sound.""" def __init__(self): self.logger = Logger() self.logger.log(Logger.INFO, "Started") def play(self, song_title): """Play the song on the path.""" self.logger.log(Logger.INFO, "Loading file " + song_title)
def __create_control_plane(self): control_logger = Logger(os.path.join(path, 'logs'), 'TrafficChart') self.__control_tab['frame'] = ttk.Frame(self.__notebook) self.__control_tab['chart'] = TrafficChart(logger=control_logger, master=self.__control_tab['frame']) self.__control_tab['chart'].pack(side='left', fill='y', expand=True) self.__control_tab['chart'].start_anime() self.__control_tab['control_btn'] = ControlFrame(logger=control_logger, master=self.__control_tab['frame'], text='系統功能') self.__control_tab['control_btn'].pack(side='top', fill='x', expand=True, padx=10) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.CONNECT, self.connect_terminal) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.STARTUP, self.start_terminal) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.STOP, self.stop_terminal) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.SHUTDOWN, self.shutdown_cell) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.L2GUI, self.start_chart) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.UPDATE_L1, lambda: self.__schedule.upload_image('uploadL1')) self.__control_tab['control_btn'].set_callback(ControlFrame.BtnId.UPDATE_L3, lambda: self.__schedule.upload_image('uploadL3')) self.__control_tab['function_btn'] = FunctionFrame(logger=control_logger, config=self.__config, master=self.__control_tab['frame'], text='設定參數') self.__control_tab['function_btn'].pack(side='top', fill='x', expand=True, padx=10) self.__control_tab['ue_list'] = UEListFrame(logger=control_logger, master=self.__control_tab['frame'], text='UE清單') self.__control_tab['ue_list'].pack(side='top', fill='x', expand=True, padx=10) self.__notebook.add(self.__control_tab['frame'], text='Control')
def main(): """ Use some docstring for comments! """ logger = Logger() signal.signal(signal.SIGINT, sig_int_handler) db_connect = None db = 'test.db' with sql.connect(db) as db_connect: # foreign keys are disabled by default for backwards compatibility db_connect.execute("""PRAGMA foreign_keys = ON;""") cursor = db_connect.cursor() cursor.execute("""PRAGMA foreign_keys;""") logger.log(Logger.INFO, "Creating table Sounds...") cursor.execute("""CREATE TABLE IF NOT EXISTS Sounds( sound_ID INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, filepath TEXT UNIQUE );""") logger.log(Logger.INFO, "Creating table Users...") cursor.execute("""CREATE TABLE IF NOT EXISTS Users( mac_address TEXT PRIMARY KEY NOT NULL, username TEXT, light_color TEXT, sound INTEGER REFERENCES Sounds(sound_ID) );""") cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='Sounds' OR name='Users';") created_tables = flatten(cursor.fetchall()) if len(created_tables) == 2: logger.log(Logger.INFO, "Tables successfully created.")
def __create_terminal(self): for screen_id in range(1,self.__config.get_screen_number()+1): screen_conf = self.__config.get_screen_conf(screen_id) screen_logger = Logger(os.path.join(path, 'logs'), screen_conf['name']) frame = TerminalFrame(screen_logger, self.__notebook) frame.grid() self.__notebook.add(frame, text=screen_conf['name']) self.__terminal_tab['frame'][screen_conf['name']] = frame
def __init__(self): """Create an empty handler and connect to the DMX interface.""" self.logger = Logger() self.dmx_devices = list() self.nr_pixels = 0 self.connection = DMXConnection.search_port(DMXHandler.DEVICE_ADDRESS, DMXHandler.NR_USB_PORTS)
def __init__(self, manager_webserver_queue, manager_control_queue): """ Comanager_gueuenstructor of the webserver. :param manager_webserver_queue: The queue which will be used to retrieve messages from the manager. :return: A new webserver. """ multiprocessing.Process.__init__(self) self.manager_webserver_queue = manager_webserver_queue self.manager_control_queue = manager_control_queue self.logger = Logger()
def __init__(self, crawler_queue, webserver_queue): multiprocessing.Process.__init__(self) # Create queue for crawler self.crawler_queue = crawler_queue # Create queue for webserver self.webserver_queue = webserver_queue # Create controller for status LED self.led = LED(LED.MANAGER) # Create logger self.logger = Logger()
class Webserver(multiprocessing.Process): """ Represents the webserver. It starts a RESTful and a websocket service. """ def __init__(self, manager_webserver_queue, manager_control_queue): """ Comanager_gueuenstructor of the webserver. :param manager_webserver_queue: The queue which will be used to retrieve messages from the manager. :return: A new webserver. """ multiprocessing.Process.__init__(self) self.manager_webserver_queue = manager_webserver_queue self.manager_control_queue = manager_control_queue self.logger = Logger() def run(self): """ Starts the webserver in a own thread. """ self.logger.log(Logger.INFO, "Running on http://127.0.0.1:8080") self.logger.log(Logger.INFO, "Webinterface available at http://127.0.0.1:8080/static/drei.html") print("Webserver: Running on http://127.0.0.1:8080") print("Webserver: Webinterface available at http://127.0.0.1:8080/static/drei.html") start_new_thread(self.notify, ()) # Initialize the RESTful and Websocket services. Webservices.manager_control_queue = self.manager_control_queue Webservices.start() def notify(self): """ Blocks until the manager adds new user list to the queue and afterwards notifies all clients. """ while True: # Retrieve user list. user_list = self.manager_webserver_queue.get() # Notify clients. notify_active_users(user_list)
class SoundController: """Controls the sound.""" def __init__(self): self.logger = Logger() self.logger.log(Logger.INFO, "Started") print("Soundcontroller started") def play(self, song_title): """Play the song on the path.""" from thread import start_new_thread self.logger.log(Logger.INFO, "Playing file " + song_title) start_new_thread(self.init_and_play, (song_title,)) def init_and_play(self, song_title): """Initialize the sound controller and plays the sound.""" import pygame pygame.mixer.init() pygame.mixer.music.load(song_title) pygame.mixer.music.play()
def __init__(self, device, dmx_address=0): self.logger = Logger() self.com = 0 self.dmx_frame = list() self.dmx_address = dmx_address # setup channel output list for i in xrange(MAX_CHANNELS + 1): self.dmx_frame.append(MIN_VAL) if platform.machine() == Const.PI_PLATFORM: try: self.com = serial.Serial(device, baudrate=COM_BAUD, timeout=COM_TIMEOUT) except: self.logger.log(Logger.ERROR, "Could not open %s" % device) self.logger.log(Logger.INFO, "Opened %s" % self.com.portstr)
def main(): """ Use some docstring for comments! """ logger = Logger() signal.signal(signal.SIGINT, sig_int_handler) db_connect = None db = 'test.db' with sql.connect(db) as db_connect: # foreign keys are disabled by default for backwards compatibility db_connect.execute("""PRAGMA foreign_keys = ON;""") cursor = db_connect.cursor() cursor.execute("""PRAGMA foreign_keys;""") logger.log(Logger.INFO, "Deleting table Users...") cursor.execute("""DROP TABLE IF EXISTS Users;""") logger.log(Logger.INFO, "Deleting table Sounds...") cursor.execute("""DROP TABLE IF EXISTS Sounds;""") cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='Sounds' OR name='Users';") deleted_tables = flatten(cursor.fetchall()) if len(deleted_tables) == 0: logger.log(Logger.INFO, "Tables successfully deleted.")
def __init__(self): self.logger = Logger() self.logger.log(Logger.INFO, "Started")
class DMXHandler: """Class handles a number of DMX devices.""" DEVICE_ADDRESS = '/dev/ttyUSB%d' NR_USB_PORTS = 4 def __init__(self): """Create an empty handler and connect to the DMX interface.""" self.logger = Logger() self.dmx_devices = list() self.nr_pixels = 0 self.connection = DMXConnection.search_port(DMXHandler.DEVICE_ADDRESS, DMXHandler.NR_USB_PORTS) def is_connected(self): """Checks the connection with the DMX interface.""" return self.connection is not None def get_available_pixels(self): """Return the number of pixels.""" return self.nr_pixels def is_valid(self, check_device): """Test if the device is valid for this DMXHandler, i.e. it doesn't use the same port as another device""" start_address = check_device.get_dmx_address() end_address = start_address + check_device.get_nr_pixels() - 1 for device in self.dmx_devices: start = device.get_dmx_address() end = start + device.get_nr_pixels() if start_address in range(start, end) or end_address in range(start, end): return False return True def get_channel(self, pixel): """Return the channel of that pixel. Return None if the channel does not exist. """ # TODO Works just with a sorted list of devices ascending by there dmx_address for device in self.dmx_devices: if pixel > device.get_nr_pixels(): pixel -= device.get_nr_pixels() else: return device.get_dmx_address() + pixel*DMXDevice.NR_CHANNELS return None def add_device(self, device): """Add the device to the handler. Checks if there is no conflict with other devices. """ if isinstance(device, DMXDevice): if self.is_valid(device): self.nr_pixels += device.get_nr_pixels() self.dmx_devices.append(device) def remove_device(self, device): """Remove the device from the handler.""" if isinstance(device, DMXDevice): if device in self.dmx_devices: self.nr_pixels -= device.get_nr_pixels() self.dmx_devices.remove(device) def set_pixel_color(self, pixel, color=ColorFactory.BLACK): """Set the pixel to the given color.""" if not self.is_connected(): raise DMXConnection.NoConnectionException channel = self.get_channel(pixel) if channel is None: self.logger.log(Logger.WARNING, "Invalid channel %d" % channel) else: self.connection.set_channel(channel + DMXDevice.RED_CHANNEL, color.get_red()) self.connection.set_channel(channel + DMXDevice.GREEN_CHANNEL, color.get_green()) self.connection.set_channel(channel + DMXDevice.BLUE_CHANNEL, color.get_blue(), True) def set_overall_color(self, color): """Set the color of every device.""" for pixel in range(self.get_available_pixels()): self.set_pixel_color(pixel, color) def test(self): """Test if all connected devices works correctly by setting the main colors.""" from time import sleep color_list = [ColorFactory.RED, ColorFactory.GREEN, ColorFactory.BLUE] for color in color_list: for i in range(self.get_available_pixels()): self.set_pixel_color(i, color) sleep(0.06) self.set_pixel_color(i) def clear(self): """Reset the color on all devices.""" self.set_overall_color(ColorFactory.BLACK)
def __init__(self): self.logger = Logger() self.logger.log(Logger.INFO, "Started") print("Soundcontroller started")
from lib.logger.Logger import Logger from lib.event import * logger = Logger() getEventHandler().addToSubscription(logger)
class SQLiteWrapper(Database): """ Provides a connection to the SQLite Database. """ def __init__(self, db="test.db"): Database.__init__(self, db) self.logger = Logger() self.logger.log(Logger.INFO, "DB Wrapper initialized.") def add_user(self, user): """ Adds a user to the database. :param user: The user who will be added. :returns true, if adding was successful, otherwise false. """ was_added_successful = False logger_msg = "nothing happened." with sql.connect(self.db) as db_con: cursor = db_con.cursor() if not self.user_exists(cursor, user.mac): sound_ID = self.get_song_ID(cursor, user.sound) cursor.execute(""" INSERT INTO Users(mac_address, username, sound, light_color) VALUES('%s', '%s', '%s', '%s');""" % ( user.mac, user.name, sound_ID, user.light_color)) was_added_successful = True logger_msg = "User %s with MAC-Address %s created." % (user.name, user.mac) else: logger_msg = "User already exists. Nothing inserted." self.logger.log(Logger.INFO, logger_msg) return was_added_successful def create_sound_title(self, filepath): """ Generates a sound title from a given filepath. :param filepath: :return: Filename as title """ path_chunks = filepath.split('/') title = path_chunks[len(path_chunks) - 1] self.logger.log(Logger.INFO, "title created: %s" % title) return title def user_exists(self, cursor, user_mac): """ Checks if a given user already exists. :return: True, if user exists, otherwise false. """ cursor.execute("""SELECT * FROM Users WHERE mac_address='%s';""" % user_mac) data = cursor.fetchall() if not data: return False else: return True def get_song_ID(self, cursor, filepath): """ Retrieves the sound_ID to a sound's specified filepath. :return: The sound_ID or None, if sound does not exist. """ cursor.execute("SELECT sound_ID from Sounds WHERE filepath='%s';" % filepath) data = cursor.fetchone() if data: return data[0] else: return self.create_sound_ID(cursor, filepath) def create_sound_ID(self, cursor, filepath): title = self.create_sound_title(filepath) cursor.execute(""" INSERT INTO Sounds(title, filepath) VALUES(?, ?);""", (title, filepath)) last_row_id = cursor.lastrowid cursor.execute("""SELECT sound_ID FROM Sounds WHERE rowid='%s';""" % last_row_id) return cursor.fetchone()[0] def get_user(self, user_mac): """ Returns the user with a given MAC address. :return: A user object. """ user = None with sql.connect(self.db) as db_con: cursor = db_con.cursor() cursor.execute("SELECT *, rowid FROM Users WHERE mac_address='%s'" % user_mac) data = cursor.fetchone() if data: mac_add, name, light_color, sound, light_ID = data cursor.execute("SELECT * FROM Sounds WHERE sound_ID='%s'" % sound) sound_ID, title, filepath = cursor.fetchone() user = User(mac_add, name, filepath, light_ID, light_color) else: self.logger.log(Logger.INFO, "User with MAC %s could not be found." % user_mac) return user def retrieve_users(self): """ Returns a list with all users. :return: A list containing all users. """ users = [] with sql.connect(self.db) as db_con: cursor = db_con.cursor() cursor.execute("SELECT mac_address FROM Users") mac_addresses = flatten(cursor.fetchall()) for mac_add in mac_addresses: user = self.get_user(mac_add) users.append(user) return users def update_user(self, user_mac, user): """ Updates the user with specified user_id """ with sql.connect(self.db) as db_con: cursor = db_con.cursor() sound_ID = self.get_song_ID(cursor, user.sound) if not sound_ID: sound_ID = self.create_sound_ID(cursor, user.sound) cursor.execute(""" UPDATE Users SET light_color=?, sound=? WHERE mac_address=? ;""", ( user.light_color, sound_ID, user_mac)) was_update_successful = cursor.rowcount > 0 logger_msg = "Nothing to update." if was_update_successful: logger_msg = "User data updated - new sound: %s new light color: %s." % (user.sound, user.light_color) self.logger.log(Logger.INFO, logger_msg) return was_update_successful def delete_user(self, user_mac): """ Deletes the user with the specified user_mac. :returns True, if user was successfully deleted, otherwise false. """ with sql.connect(self.db) as db_con: cursor = db_con.cursor() cursor.execute("DELETE FROM Users WHERE mac_address='%s';""" % user_mac) deleting_successful = cursor.rowcount > 0 logger_msg = "Deleting user failed." if deleting_successful: logger_msg = "Deleted user %s" % user_mac self.logger.log(Logger.INFO, logger_msg) return deleting_successful def list_sounds(self): """ Provides a list of all sounds. :return: A list, containing the tuples (title, path). """ with sql.connect(self.db) as db_con: cursor = db_con.cursor() cursor.execute("SELECT title FROM Sounds") sound_list = flatten(cursor.fetchall()) return sound_list
class Crawler(multiprocessing.Process): def __init__(self, manager_queue, dummy=True): multiprocessing.Process.__init__(self) self.manager_queue = manager_queue self.dummy = dummy self.led = LED(LED.CRAWLER) self.logger = Logger() def _notify(self, state, mac): # print a pretty message if state == '1': self.logger.log(Logger.INFO, "New peer connected: " + str(mac)) elif state == '0': self.logger.log(Logger.INFO, "New peer disconnected: " + str(mac)) # send new mac to manager self.manager_queue.put([state, mac]) # toggle the status led for 100ms self.led.toggle() time.sleep(0.1) self.led.toggle() def run(self): self.logger.log(Logger.INFO, "Running") print("Logger running") self.led.on() # dummy mode, send addresses in random time slices if self.dummy: while True: time.sleep(2) self._notify('1', '00:80:41:ae:fd:7e') time.sleep(2) self._notify('1', '00:80:41:ae:fd:7d') time.sleep(2) self._notify('0', '00:80:41:ae:fd:7e') time.sleep(2) self._notify('0', '00:80:41:ae:fd:7d') # listen of events from WIFI interface else: # regex pattern for iwevent messages pattern = re.compile('(.*?)\s+(.*?)\s+([\w|\s]+):(.*)$') # spaw new iwevent process and capture output result = subprocess.Popen("/sbin/iwevent", shell=False, stdout=subprocess.PIPE) # each line is a new event while True: line = result.stdout.readline() if line == '': break # parse output matcher = pattern.search(line.decode("utf-8")) if matcher: # new peer connected if "Registered" in matcher.group(3): self.logger.log(Logger.INFO, "New peer connected: " + matcher.group(4)) self.manager_queue.put(['1', matcher.group(4)]) # peer disconnected elif "Expired" in matcher.group(3): self.logger.log(Logger.INFO, "Peer disconnected: " + matcher.group(4)) self.manager_queue.put(['0', matcher.group(4)]) # toggle the status led for 100ms self.led.toggle() time.sleep(0.1) self.led.toggle() self.logger.log("Exited") self.led.off()
#!/usr/bin/env python import multiprocessing import Const import platform from manager.Manager import Manager from lib.database import InitTables from crawler.Crawler import Crawler from webserver.Webserver import Webserver from lib.logger.Logger import Logger __author__ = 's.jahreiss' if __name__ == '__main__': logger = Logger() logger.log(Logger.INFO, "Starting Drei") print("Starting Drei") # Initializing database with tables (if necessary) InitTables.main() # Initialize the message queue for crawler and manager manager_queue = multiprocessing.Queue() # Initialize the message queue for manager and webserver manager_webserver_queue = multiprocessing.Queue() # Start the crawler crawler = Crawler(manager_queue, platform.machine() != Const.PI_PLATFORM) crawler.start()
class DMXConnection(object): """DMXConnection represents the connection to a single DMX device. The DMX address can be set.""" def __init__(self, device, dmx_address=0): self.logger = Logger() self.com = 0 self.dmx_frame = list() self.dmx_address = dmx_address # setup channel output list for i in xrange(MAX_CHANNELS + 1): self.dmx_frame.append(MIN_VAL) if platform.machine() == Const.PI_PLATFORM: try: self.com = serial.Serial(device, baudrate=COM_BAUD, timeout=COM_TIMEOUT) except: self.logger.log(Logger.ERROR, "Could not open %s" % device) self.logger.log(Logger.INFO, "Opened %s" % self.com.portstr) def set_channel(self, channel, val, auto_render=False): """Set the channel to a specified value. You can select if the channel should be rendered directly. The default is False. """ # takes channel and value arguments to set a channel level in the local # dmx frame, to be rendered the next time the render() method is called if (channel > MAX_CHANNELS) or (channel < MIN_CHANNELS): self.logger.log(Logger.WARNING, "Invalid channel %d" % channel) if val > MAX_VAL: val = MAX_VAL if val < MIN_VAL: val = MIN_VAL self.dmx_frame[self.dmx_address + channel] = val if auto_render: self.render() def clear(self, channel=0): """Clear all channels. Set channel to clear only the specified channel.""" if channel == 0: for i in xrange(MIN_CHANNELS, MAX_CHANNELS): self.dmx_frame[i] = MIN_VAL else: self.dmx_frame[channel] = MIN_VAL self.render() def render(self): """Set all the pixel that were set before.""" # updates the dmx output from the USB DMX Pro with the values from self.dmx_frame packet = list() packet.append(chr(START_VAL)) packet.append(chr(LABELS["TX_DMX_PACKET"])) packet.append(chr(len(self.dmx_frame) & 0xFF)) packet.append(chr((len(self.dmx_frame) >> 8) & 0xFF)) for j in xrange(len(self.dmx_frame)): packet.append(chr(self.dmx_frame[j])) packet.append(chr(END_VAL)) if platform.machine() == Const.PI_PLATFORM: self.com.write("".join(packet)) def close(self): """Close the port.""" if platform.machine() == Const.PI_PLATFORM: self.com.close()
self.__control_tab['chart'].attach_L2GUIServ(self.__control_tab['l2guiserv']) except: self._print_error('cannot start chart/L2GUI') return False return True def get_terminal_tab(self): return self.__terminal_tab; def __on_exit(self): self.__root.destroy() sys.exit() def mainloop(self): while True: try: self.__root.mainloop() break except UnicodeDecodeError: pass if __name__ == '__main__': path = os.path.dirname(os.path.realpath(__file__)) logger = Logger(os.path.join(path, 'logs'), 'Main_thread') config = ConfigLoader(os.path.join(path, 'config'), logger=logger) scg = SmallCellGUI(path, config, logger) scg.mainloop()
def __init__(self, manager_queue, dummy=True): multiprocessing.Process.__init__(self) self.manager_queue = manager_queue self.dummy = dummy self.led = LED(LED.CRAWLER) self.logger = Logger()
class Manager(multiprocessing.Process): def __init__(self, crawler_queue, webserver_queue): multiprocessing.Process.__init__(self) # Create queue for crawler self.crawler_queue = crawler_queue # Create queue for webserver self.webserver_queue = webserver_queue # Create controller for status LED self.led = LED(LED.MANAGER) # Create logger self.logger = Logger() def run(self): self.logger.log(Logger.INFO, 'Running') print("Manager running") self.led.on() # Control for sound and light self.per = Periphery() # Create the database connection self.db = SQLiteWrapper() current_users = np.array([]) # Boolean if the list was altered altered = False while True: # Update users users = self.db.retrieve_users() # Receive new changes from crawler changes = np.array(self.crawler_queue.get()) old_users = current_users # Iterate over changes for i in range(0, changes.size - 1): # New user connected if changes[0] == "1": for user in users: if user.mac.lower() == changes[1].lower(): # Signalise changes in user list for webserver altered = True # Add new user to user list old_users = np.append(current_users, changes[1]) # Remove duplicates current_users = np.unique(old_users) # Get light and sound information for user light_id = user.light_id light_color = user.light_color sound = user.sound self.logger.log(Logger.INFO, "user " + changes[1] + " added") # Turn on users light and play users sound self.per.light_on(int(light_id), light_color) self.per.play_sound(sound) break # User disconnected elif changes[0] == "0": for user in users: if user.mac.lower() == changes[1].lower(): # Catch deletion of just added users try: del_index = np.where(current_users == changes[1])[0][0] except IndexError: break # Signalise changes in user list for webserver altered = True # Delete user from user list current_users = np.delete(current_users, del_index) # Get light information for user light_id = user.light_id self.logger.log(Logger.INFO, "user " + changes[1] + " deleted") # Turn off users light self.per.light_off(int(light_id)) # Change in status light elif changes[0] == "2": # Set new colour of status light self.per.set_status_light(changes[1]) # User list was altered if altered: altered = False # Send new user list to webserver self.webserver_queue.put(current_users.tolist()) # Turn off status LED self.led.off()
def __init__(self, db="test.db"): Database.__init__(self, db) self.logger = Logger() self.logger.log(Logger.INFO, "DB Wrapper initialized.")
self.set_pixel_color(i) def clear(self): """Reset the color on all devices.""" self.set_overall_color(ColorFactory.BLACK) if __name__ == '__main__': handler = DMXHandler() tube = PixelTubeDevice(0) bar = LEDBarDevice(48) if handler.is_connected(): logger = Logger() logger.log(Logger.INFO, "Is connected") handler.add_device(tube) handler.add_device(bar) from time import sleep colours = [ColorFactory.RED, ColorFactory.GREEN, ColorFactory.BLUE, ColorFactory.YELLOW, ColorFactory.MAGENTA, ColorFactory.CYAN, ColorFactory.ORANGE, ColorFactory.PURPLE,