Skip to content

Commit

Permalink
adding playlist server and client
Browse files Browse the repository at this point in the history
  • Loading branch information
Christoph Hirtz committed Oct 15, 2014
1 parent 364d8b2 commit dc3b4c9
Show file tree
Hide file tree
Showing 17 changed files with 473 additions and 165 deletions.
33 changes: 9 additions & 24 deletions avrconnector.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class ConnectionType(Enum):
class AVRConnector:
def __init__(self, baud_rate=38400):
self.baud_rate = baud_rate
self.__handlers = []
self.write = None
self.close = None
self.active = False
Expand All @@ -26,8 +25,6 @@ def _connect_linux(self):
try:
logging.info("Trying to connect to %s%s" % (dev, str(x)))
ser = serial.Serial("%s%s" % (dev, str(x)), baudrate=self.baud_rate)
for h in self.__handlers:
h()
return ser.write, ser.close
except serial.serialutil.SerialException:
pass
Expand All @@ -40,17 +37,13 @@ def _connect_bluetooth_linux(self):
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.settimeout(getint("connection_timeout"))
s.connect((server_mac, 1))
for h in self.__handlers:
h()
return s.send, s.close
except:
return False

def _connect_bluetooth_windows(self):
try:
ser = serial.Serial(port=getstring("bluetooth_device_windows"), baudrate=self.baud_rate)
for h in self.__handlers:
h()
return ser.write, ser.close
except:
return False
Expand All @@ -59,17 +52,13 @@ def _connect_macos(self, dev):
try:
logging.info("Trying to connect to %s" % dev)
ser = serial.Serial(dev, baudrate=self.baud_rate)
for h in self.__handlers:
h()
return ser.write, ser.close
except serial.serialutil.SerialException:
return False

def _connect_windows(self):
try:
ser = serial.Serial(port=getstring("serial_device_windows"), baudrate=self.baud_rate)
for h in self.__handlers:
h()
return ser.write, ser.close
except:
return False
Expand All @@ -79,33 +68,31 @@ def _connect_ethernet(self):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((getstring("ethernet_host"), getint("ethernet_port")))
for h in self.__handlers:
h()
return s.send, s.close
except:
return False

def connect(self, type):
def connect(self, connection_type):
"""
:param type: usb, ethernet, bluetooth
:param connection_type: usb, ethernet, bluetooth
:return:
"""
if type == ConnectionType.ethernet:
if connection_type == ConnectionType.ethernet:
ret = self._connect_ethernet()
elif platform == "win32":
if type == ConnectionType.bluetooth:
if connection_type == ConnectionType.bluetooth:
ret = self._connect_bluetooth_windows()
elif type == ConnectionType.usb:
elif connection_type == ConnectionType.usb:
ret = self._connect_windows()
elif platform == "darwin":
if type == ConnectionType.bluetooth:
if connection_type == ConnectionType.bluetooth:
ret = self._connect_macos(getstring("bluetooth_device_macos"))
elif type == ConnectionType.usb:
elif connection_type == ConnectionType.usb:
ret = self._connect_macos(getstring("serial_device_macos"))
else:
if type == ConnectionType.bluetooth:
if connection_type == ConnectionType.bluetooth:
ret = self._connect_bluetooth_linux()
elif type == ConnectionType.usb:
elif connection_type == ConnectionType.usb:
ret = self._connect_linux()
if not ret:
return False
Expand Down Expand Up @@ -138,8 +125,6 @@ def write_single_color(self, color, grid_size):
d = self.pack_mcuf(colors, grid_size, True)
self.write(d)

def add_connection_handler(self, handler):
self.__handlers.append(handler)

def is_active(self):
return self.active
Expand Down
50 changes: 50 additions & 0 deletions blinkclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
from socket_protocol import BlinkClient
from blinkconfig import *
import cmd


class Prompt(cmd.Cmd):
prompt = '> '

def do_add(self, line):
ret = connector.add_to_playlist(line)
print(ret)

def help_add(self):
print("Adds a file to the playlist.")

def do_load_file(self, line):
line = line.split(" ")
ret = connector.load_clip(*line)
print(ret)

def help_load_file(self):
print("Loads a .bml file to the storage")

def do_clear(self, line):
ret = connector.clear_playlist()
print(ret)

def do_remove(self, line):
try:
i = int(line)
ret = connector.remove_from_playlist(i)
print(ret)
except ValueError:
print("ERR")

def do_show(self, line):
ret = connector.get_playlist()
print(ret)

def do_show_clips(self, line):
ret = connector.get_available_clips()
print(ret)

def help_load_file(self):
print("Reads a file and adds it to the list of available clips.")

if __name__ == '__main__':
connector = BlinkClient(getstring("ethernet_host"), getint("ethernet_port"))
Prompt().cmdloop()
13 changes: 5 additions & 8 deletions blinkgui.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,19 +291,17 @@ def _new_document(self):
pass

def _connect_to_device(self, connection_type):
def connect_handler():
self.menuConnect_to_device.setEnabled(False)
self.actionPlayStopDevice.setEnabled(True)
self.actionDisconnect.setEnabled(True)
if not self.__active_connection:
connection = AVRConnector()
connection.add_connection_handler(connect_handler)
ret = connection.connect(connection_type)
if not ret:
self._show_error(tr("Connection could not be established."))
return
self.__active_connection = connection
self.__grid.connection = self.__active_connection
self.menuConnect_to_device.setEnabled(False)
self.actionPlayStopDevice.setEnabled(True)
self.actionDisconnect.setEnabled(True)
else:
self._show_error(tr("A connection already exists."))

Expand Down Expand Up @@ -403,10 +401,9 @@ def _connect_ethernet(self):
dialog = EthernetDialog(self)
if dialog.exec_() == QtGui.QDialog.Accepted:
values = dialog.get_values()
setvalue("ethernet_hostname", values.host_name)
setvalue("ethernet_host", values.host_name)
setvalue("ethernet_port", values.port)
print (getint("ethernet_port"))
self._connect_to_device(connection_type=ConnectionType.ethernet)
self._connect_to_device(ConnectionType.ethernet)

def _show_about(self):
QtGui.QMessageBox.about(self, "Blink", "Version: %s\nAuthor: %s" % (VERSION, AUTHOR))
Expand Down
124 changes: 124 additions & 0 deletions blinkserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#!/usr/bin/env python3

import sys
import os
import time
import json
import socket
from socket_protocol import *
import threading
from blinkconfig import *
from collections import namedtuple
from avrconnector import AVRConnector, ConnectionType
from threading import Thread
from threading import Condition
from bmlparser import BMLReader
Size = namedtuple("size", "width height")
grid_size = Size(3, 3)

playlist_items = []
continue_condition = Condition()


class AVRPlayer():
def __init__(self):
self.connector = AVRConnector()
ret = self.connector.connect(ConnectionType.bluetooth)
if not ret:
print("ERR")
sys.exit(1)
self.clips = {}

def load_clips(self, file_names):
"""
:param files: {}
:return:
"""
reader = BMLReader()
for f in file_names:
fra, info, (width, height) = reader.read_xml(file_names[f])
frames = []
for frame in fra:
packet = self.connector.pack_mcuf(frame.tile_colors, grid_size, False)
frames.append((frame.duration/1000, packet))
self.clips[f] = frames

def play(self, video):
v = self.clips[video]
for frame in v:
self.connector.write(frame[1])
time.sleep(frame[0])


class BlinkDisplayThread(Thread):
def __init__(self):
Thread.__init__(self)

def run(self):
while True:
playlist = list(playlist_items)
if len(playlist) == 0:
with continue_condition:
continue_condition.wait()
for msg in playlist:
item = msg["alias"]
player.play(item)


class EthernetSocket(BlinkServer):
def __init__(self):
BlinkServer.__init__(self, getstring("ethernet_host"), getint("ethernet_port"))

@staticmethod
def add_to_playlist(sock, alias):
if not alias in player.clips:
send_one_message(sock, "ERROR")
return
di = {"alias": alias}
playlist_items.append(di)
with continue_condition:
continue_condition.notifyAll()
send_one_message(sock, str(len(playlist_items)-1))

@staticmethod
def remove_from_playlist(sock, it_id):
item_id = int(it_id)
try:
del playlist_items[item_id]
send_one_message(sock, "OK")
except IndexError:
send_one_message(sock, "ERROR")

@staticmethod
def clear_playlist(sock):
global playlist_items
playlist_items = []
send_one_message(sock, "OK")

@staticmethod
def load_clip(sock, params):
file_name, alias = params.split(",")
player.load_clips({alias: file_name})
send_one_message(sock, "OK")

@staticmethod
def get_available_clips(sock):
send_one_message(sock, str(list(player.clips.keys())))

@staticmethod
def get_playlist(sock):
lis = ["%d -> %s" % (idx, str(item["alias"])) for idx, item in enumerate(playlist_items)]
send_one_message(sock, str(lis))


if __name__ == "__main__":
player = AVRPlayer()
if len(sys.argv) == 2:
files = json.load(open(sys.argv[1], "r"))
player.load_clips(files)
elif os.path.isfile("playlist.cfg"):
files = json.load(open("playlist.cfg", "r"))
player.load_clips(files)
thread = BlinkDisplayThread()
thread.start()
socket = EthernetSocket()
2 changes: 1 addition & 1 deletion color_transition_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Form implementation generated from reading ui file 'color_transition_dialog.ui'
#
# Created: Tue Oct 14 18:46:08 2014
# Created: Wed Oct 15 10:48:03 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion ethernet_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Form implementation generated from reading ui file 'ethernet_dialog.ui'
#
# Created: Tue Oct 14 18:46:09 2014
# Created: Wed Oct 15 10:48:03 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
Expand Down
7 changes: 3 additions & 4 deletions blinkdaemon.py → ethernet_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@
PORT = blinkconfig.getint("ethernet_port")


class BlinkConnector:
class EthernetConnector:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.bind((HOST, PORT))
self.socket.listen(10)
while True:
#wait to accept a connection - blocking call
conn, addr = self.socket.accept()
t = threading.Thread(target=self.client_thread, args=(conn,))
t.start()
Expand All @@ -37,6 +36,6 @@ def client_thread(self, conn):

if __name__ == "__main__":
avr_connector = AVRConnector()
avr_connector.connect(ConnectionType.bluetooth)
connector = BlinkConnector()
avr_connector.connect(ConnectionType.usb)
connector = EthernetConnector()

2 changes: 1 addition & 1 deletion lg_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Form implementation generated from reading ui file 'lg_dialog.ui'
#
# Created: Tue Oct 14 18:46:08 2014
# Created: Wed Oct 15 10:48:03 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
Expand Down
11 changes: 10 additions & 1 deletion mainwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Tue Oct 14 18:46:08 2014
# Created: Wed Oct 15 10:48:03 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
Expand Down Expand Up @@ -565,10 +565,19 @@ def setupUi(self, MainWindow):
self.actionDisconnect.setIcon(icon45)
self.actionDisconnect.setObjectName("actionDisconnect")
self.actionAbout_Qt = QtGui.QAction(MainWindow)
icon46 = QtGui.QIcon()
icon46.addPixmap(QtGui.QPixmap(":/icons/QtProject-qtcreator.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAbout_Qt.setIcon(icon46)
self.actionAbout_Qt.setObjectName("actionAbout_Qt")
self.actionAbout = QtGui.QAction(MainWindow)
icon47 = QtGui.QIcon()
icon47.addPixmap(QtGui.QPixmap(":/icons/dialog-information.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAbout.setIcon(icon47)
self.actionAbout.setObjectName("actionAbout")
self.actionConnectEthernet = QtGui.QAction(MainWindow)
icon48 = QtGui.QIcon()
icon48.addPixmap(QtGui.QPixmap(":/icons/network-wired.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionConnectEthernet.setIcon(icon48)
self.actionConnectEthernet.setObjectName("actionConnectEthernet")
self.toolBar.addSeparator()
self.toolBar.addAction(self.actionGo_to_previous_frame)
Expand Down
Loading

0 comments on commit dc3b4c9

Please sign in to comment.