Ejemplo n.º 1
0
 def __init__(self, home, away):
     Broadcaster.__init__(self)
     self.match_teams = (home, away)
     self.finished = False
     self.watch = Watch()
     self.ball = Ball(self)
     self.reposition()
Ejemplo n.º 2
0
 def select_picture(self):
     filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '~/Pictures')
     device_name = '{}'.format(self.combo.currentText())
     print(device_name)
     if device_name == 'All':
         device_ips = self.devices.values()
         bc = Broadcaster(device_ips)
     else:
         device_ip = self.devices[device_name]
         bc = Broadcaster([device_ip])
     bc.send_picture(filename)
     self.statusBar().showMessage('Picture sent')
     self.broadcaster = bc
Ejemplo n.º 3
0
def start_aircast(hostname, port):
    sample_queue = Queue()
    io_loop = tornado.ioloop.IOLoop.current()

    stream_url = "http://{}:{}{}".format(hostname, port, STREAM_ROUTE)
    caster = Caster(stream_url)

    config = Config(sample_rate=44100, channels=2, bits_per_sample=16)
    broadcaster = Broadcaster(config, sample_queue, io_loop)
    shairport = Shairport(caster.device_name, config, sample_queue)
    app = make_app(broadcaster)

    def shairport_status_cb(event, _):
        if event == 'playing':
            caster.start_stream()

    shairport.add_callback(shairport_status_cb)

    broadcaster.start()
    shairport.start()
    app.listen(port)

    logger.info("AirCast ready. Advertising as '%s'", caster.device_name)
    try:
        io_loop.start()
    except KeyboardInterrupt:
        pass
    finally:
        io_loop.stop()
        shairport.stop()
        broadcaster.stop()

        shairport.join(5)
        broadcaster.join(5)
Ejemplo n.º 4
0
def init_bot(config, lang, token):
    global db
    global handler
    global bc

    # Initilizing
    db = Database(config)
    handler = Handler(lang)
    updater = Updater(token['botToken'])
    dp = updater.dispatcher
    bc = Broadcaster(db, updater.bot)

    print('Dating Bot started.')

    # Add message handlers
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(CommandHandler('help', help))
    dp.add_handler(MessageHandler(Filters.all, process))
    dp.add_handler(CallbackQueryHandler(callback))
    dp.add_error_handler(error)

    # Start broadcasting thread
    #bc.start()

    # Start bot
    updater.start_polling()
    updater.idle()
Ejemplo n.º 5
0
 def loadLevel(self):
     if self.networkingEnabled:
         self.broadcaster = Broadcaster()
         self.listener = Listener()
         self.listener.start()
         self.broadcaster.start()
     if self.server or not self.networkingEnabled:
         self.remainingIDs.append([1,""])
         self.remainingIDs.append([2,""])
Ejemplo n.º 6
0
Archivo: inbus.py Proyecto: mlos/inbus
 def __init__(self, address=("127.0.0.1", 7222), buffer_size=65536):
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     registry = Registry()
     self._message_receiver = MessageReceiver(
         IncomingMessageTranslator(
             [registry,
              Broadcaster(registry,
                          MessageSender(OutgoingMessageTranslator(), sock))
              ]), address, buffer_size)
Ejemplo n.º 7
0
    def __init__(self, width, height, num_mines):
        """
        Positional arguments:
        width: the width of the game field.
        height: the height of the game field.
        num_mines: the number of mines in the game field.
        """

        assert num_mines <= width * height
        Broadcaster.__init__(self)
        self.width, self.height = width, height
        self.num_mines = num_mines
        self.mines = Matrix(width, height)
        candidate_positions = [Point(x, y) for x in range(width) for y in range(height)]
        for location in random.sample(candidate_positions, num_mines):
            self.mines[location] = True
        self.cell_states = Matrix(width, height, State.covered)
        self.cell_state_counts = {State.covered: width * height, State.uncovered: 0, State.flagged: 0, State.unsure: 0}
        self.game_state = State.not_started
Ejemplo n.º 8
0
    def __init__(self, **kargs):
        Broadcaster.__init__(self)
        self.queue = PieceQueue(kargs.get("generator", gen_bags))
        # self.queue = PieceQueue(kargs.get("generator", gen_line_pieces))
        self.queue.peek()

        self.cols = kargs.get("cols", 10)
        self.rows = kargs.get("rows", 22)  # typically 16 to 24. 22 is recommended.
        self.obstructed_rows = 2
        self.blocks = set()

        self.score = 0
        self.lines_cleared = 0
        self.level = 0

        self.frames_since_last_drop = 0
        self.frames_between_drops = self.get_frames_between_drops()

        self.held_piece = None
        self.may_hold = True
        self.active_piece = None

        self.lost = False
Ejemplo n.º 9
0
    def from_dict(cls, dct):  # type: (dict) -> Station
        """

        :param dct:
        :return:
        """
        station = cls()

        station.station_id = dct.pop("stationID")

        if "callsign" in dct:
            station.callsign = dct.pop("callsign")

        if "name" in dct:
            station.name = dct.pop("name")

        if "affiliate" in dct:
            station.affiliate = dct.pop("affiliate")

        if "broadcastLanguage" in dct:
            station.broadcast_languages = dct.pop("broadcastLanguage")

        if "descriptionLanguage" in dct:
            station.description_languages = dct.pop("descriptionLanguage")

        if "broadcaster" in dct:
            station.broadcaster = Broadcaster.from_dict(dct.pop("broadcaster"))

        if "logo" in dct:
            station.logo = StationLogo.from_dict(dct.pop("logo"))

        if "isCommercialFree" in dct:
            station.is_commercial_free = dct.pop("isCommercialFree")

        if "affiliate" in dct:
            station.affiliate = dct.pop("affiliate")

        if "isRadioStation" in dct:
            station.is_radio_station = dct.pop("isRadioStation")

        if len(dct) != 0:
            logging.warn("Key(s) not processed for Station: %s",
                         ", ".join(dct.keys()))

        return station
Ejemplo n.º 10
0
    def from_dict(cls, dct):  # type: (dict) -> Station
        """

        :param dct:
        :return:
        """
        station = cls()

        station.station_id = dct.pop("stationID")

        if "callsign" in dct:
            station.callsign = dct.pop("callsign")

        if "name" in dct:
            station.name = dct.pop("name")

        if "affiliate" in dct:
            station.affiliate = dct.pop("affiliate")

        if "broadcastLanguage" in dct:
            station.broadcast_languages = dct.pop("broadcastLanguage")

        if "descriptionLanguage" in dct:
            station.description_languages = dct.pop("descriptionLanguage")

        if "broadcaster" in dct:
            station.broadcaster = Broadcaster.from_dict(dct.pop("broadcaster"))

        if "logo" in dct:
            station.logo = StationLogo.from_dict(dct.pop("logo"))

        if "isCommercialFree" in dct:
            station.is_commercial_free = dct.pop("isCommercialFree")

        if "affiliate" in dct:
            station.affiliate = dct.pop("affiliate")

        if "isRadioStation" in dct:
            station.is_radio_station = dct.pop("isRadioStation")

        if len(dct) != 0:
            logging.warn("Key(s) not processed for Station: %s", ", ".join(dct.keys()))

        return station
Ejemplo n.º 11
0
def main():
    esp.osdebug(None)
    config = load_config()
    broadcaster = Broadcaster(100)
    one_wire = onewire.OneWire(machine.Pin(22, machine.Pin.PULL_UP))
    temp_sensor = DS18B20(one_wire)

    sensor_ids = temp_sensor.scan()
    if not sensor_ids:
        machine.reset()
        return
    sensor_id = sensor_ids[0]

    try:
        temperature = temp_sensor.convert_read_temp(sensor_id)
        broadcaster.broadcast(temperature)
    except Exception:
        broadcaster.broadcast(Broadcaster.ERROR_TEMPERATURE)

    measure("end")
    machine.reset()
Ejemplo n.º 12
0
class NetMgr(Mgr):
    def __init__(self, engine,localOptions):
        Mgr.__init__(self, engine)
        self.engine = engine
        self.networkingEnabled = localOptions.enableNetworking
        if self.networkingEnabled:
            self.server = localOptions.server
        else:
            self.server = False
        self.ip = localOptions.ip
        self.remainingIDs = []
        self.timeToWaitForPlayers = 10

    def initialize(self):
        pass   
    def loadLevel(self):
        if self.networkingEnabled:
            self.broadcaster = Broadcaster()
            self.listener = Listener()
            self.listener.start()
            self.broadcaster.start()
        if self.server or not self.networkingEnabled:
            self.remainingIDs.append([1,""])
            self.remainingIDs.append([2,""])
    
    def releaseLevel(self):
        if self.networkingEnabled:
            self.listener.stop()
            self.broadcaster.stop()
            self.listener.join()
            self.broadcaster.join()

    def tick(self, dtime):
        if self.networkingEnabled:
            if dtime < 1 and self.timeToWaitForPlayers > 0:
                self.timeToWaitForPlayers -= dtime
            # check to see if all players are ready to start the race
            if self.timeToWaitForPlayers > 0 and self.engine.gameMgr.allPlayersReady == False:
                allReady = True
                for ent in self.engine.entMgr.entities:
                    if not ent.isReady:
                        allReady = False
                if len(self.engine.entMgr.entities) > 1:
                    self.engine.gameMgr.allPlayersReady = allReady
            elif self.timeToWaitForPlayers <= 0:
                self.engine.gameMgr.allPlayersReady = True

            # get messages
            incoming = self.listener.getMessages()
            outgoingMsgs = []
            for msgs in incoming:
                msgType, msg = messages.unpack(msgs)
                if msgType == const.STATUS:
                    found = False
                    # check to see if the status message is regarding a ship that is already created
                    for ent in self.engine.entMgr.entities:
                        if ent.shipId == msg.shipId:
                            found = True
                    # if it is, send updates to entity
                    if found and msg.shipId != self.engine.entMgr.playerIndex:
                        self.engine.entMgr.entities[msg.shipId].updateQueue.append(msg)
                    # if it isn't, create that entity
                    elif not found:
                        ent = Spaceship("Ship" + str(msg.shipId),msg.shipId, self.engine,const.MESHES[msg.shipId])
                        ent.pos = self.engine.entMgr.nextPos
                        self.engine.entMgr.nextPos.x += 40
                        self.engine.entMgr.entities.append(ent)
                # only process requests before game has started
                elif msgType == const.REQUEST and self.timeToWaitForPlayers > 0:
                    for ID in self.remainingIDs:
                        # if the id has not been issued already, or if the ID corresponds to a user who has been given an ID (but did not recieve their ID), send the ID
                        if ID[1] == "" or ID[1] ==  msg.userName:
                            outgoingMsgs.append(messages.pack(messages.InfoMessage(msg.userName,ID[0]),const.INFO))
                            ID[1] = msg.userName
                # only process info messages when this player has not been handed a playerIndex
                elif msgType == const.INFO and not self.server and self.engine.entMgr.playerIndex == -1:
                    self.engine.entMgr.playerIndex = msg.shipId
                    found = False
                    for ent in self.engine.entMgr.entities:
                        if ent.shipId == msg.shipId:
                            found = True
                    if not found:
                        ent = Spaceship("Ship" + str(msg.shipId),msg.shipId, self.engine,const.MESHES[msg.shipId])
                        ent.pos = self.engine.entMgr.nextPos
                        self.engine.entMgr.nextPos.x += 40
                        self.engine.entMgr.entities.append(ent)

            # if this player has not been handed a playerIndex, request one.
            if self.engine.entMgr.playerIndex == -1:
                outgoingMsgs.append(messages.pack(messages.RequestMessage(str(socket.gethostname())),const.REQUEST))
            # if the player has been handed a playerIndex, send the status of your ship
            else:
                myId = self.engine.entMgr.playerIndex
                myEnt = self.engine.entMgr.entities[myId]
                outgoingMsgs.append(messages.pack(messages.StatusMessage(myId,myEnt.pos,myEnt.dir,myEnt.colVel,myEnt.speed,myEnt.pitch, myEnt.roll,myEnt.isReady),const.STATUS))
            # send outgoing messages
            for msg in outgoingMsgs:
                self.broadcaster.addMessage(msg)
Ejemplo n.º 13
0

lamp = Lamp()

# RPI HOSTNAME ---------------------------------------------------
this_lamp = subprocess.check_output('hostname')
this_lamp = this_lamp.decode("utf-8")
this_lamp = this_lamp.replace('lamp', '', 1)
print("THIS LAMP IS LAMP NUMBER: " + this_lamp)
lamp.id = int(this_lamp)

mixer = alsaaudio.Mixer()
mixer.setvolume(0)

listener = Listener()
broadcaster = Broadcaster()


def fadeIn():
    print("FADE IN")
    volume = mixer.getvolume()
    volume = int(volume[0])
    while volume < 100:
        volume += 2
        mixer.setvolume(volume)
        sleep(0.01)
    print("VOLUME IS 100")


def fadeOut():
    print("FADE OUT")
Ejemplo n.º 14
0
def main():
        if len(sys.argv) != 2:
                print("Usage: {} [username]".format(sys.argv[0]));
                sys.exit(1);        
                
        
        try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
        except:
                print('Could not create socket');
                exit(1);
        
        port = PORT_MIN;
        while True:
                try:
                        s.bind(('', port));
                        break;
                except:
                        port += 1;
                        if(port > PORT_MAX):
                                print("Could not bind socket");
                                exit(1);

        # get user info
        addrinfo = socket.getaddrinfo(socket.gethostname(), port);
        addressFam = addrinfo[2];
        addr = addressFam[4];

        # make local peer
        localPeer = Peer(sys.argv[1], addr[0], addr[1]);
        while(not localPeer.isValidUsername()):
                newUsername = input("Please enter a username with at least one upper letter, one lower letter, one digit, and one of .-_: ");
                localPeer = Peer(newUsername, addr[0], addr[1]);
        
        hQueue = Queue();
        crQueue = Queue();
        csQueue = Queue();
        peerList = [];
        peerList.append(localPeer);
        bc = Broadcaster(s, peerList);
        mr = MasterReceiver(s, hQueue, crQueue);
        pd = PeerDiscover(peerList, hQueue);
        mgr = Messenger(s, peerList, crQueue, csQueue);

        bc.daemon = True;
        mr.daemon = True;
        pd.daemon = True;
        mgr.daemon = True;
    
        bc.start();
        mr.start();
        pd.start();
        mgr.start();
	
        #print("Loading peers...");
	
        msg = "";
        while True:
                msg = input(localPeer.username + ": ");
                if len(msg) == 1 and msg[0] == 'q':
                        break;
                elif(msg == "list"):
                        print(" Users online: ");
                        for i in range(1, len(peerList)):
                                print(peerList[i].username);
                        continue;
                elif len(msg) == 1 and msg[0] == 'p':
                        peerList[0].printInfo();
                        continue;

                csQueue.put(msg);
	
        print("Logged off");
Ejemplo n.º 15
0
from weather_station import WeatherStation
from broadcaster import Broadcaster
import time
import os
import sys
import logging
from config_loader import ConfigLoader
logging.basicConfig(level=logging.DEBUG)

if len(sys.argv) == 2:
    conf = ConfigLoader(sys.argv[1])
else:
    conf = ConfigLoader("config.json")

if (conf.AP_mode):
    com = Broadcaster(host="localhost", port=conf.websocket_port)
else:
    com = Broadcaster(host=conf.webserver, port=conf.websocket_port)


def speedUpdate(value):
    global sound
    #print "Wind speed: %s" % value
    com.emit("windSpeedUpdate", {'value': value, 'id': id})


def directionUpdate(value):
    global sound
    #print "Wind direction: %s" % value
    com.emit("windDirectionUpdate", {'value': value, 'id': id})
Ejemplo n.º 16
0
from html import escape
from aiogram import Dispatcher
from telethon.tl.types import Channel
from telethon.errors import ChannelPrivateError, RPCError

from database import Database
from broadcaster import Broadcaster
from globals import client, bot, DIR_PATH
from filters import *
from utils import get_entity, answer, provide_client_connection, \
    inline_feed_ls, inline_channel_ls, clean_query, get_title

dp = Dispatcher(bot)
db = Database(DIR_PATH + '/database.json')
bc = Broadcaster(db)
db.subscribe(bc)

# region Message handlers


@dp.message_handler(from_me, commands=['start'])
async def start(message: types.Message):
    await answer('Hello ' + message.from_user.first_name + '\n'
                 + 'Use /addfeed <link_to_channel> to add channel which will '
                 + 'serve as your feed.\nThen send me a link to '
                 + 'channel you want to add to your feed or use /add '
                 + '<link_to_channel>.\n You can add as many feeds and '
                 + 'channels as you wish. Use /help for additional commands',
                 parse_mode=None)

Ejemplo n.º 17
0
            ac.go_to_seconds("sample4.wav", 0)
            ac.play_sound("sample4.wav")
        elif val == "W":
            ac.go_to_seconds("sample5.wav", 0)
            ac.play_sound("sample5.wav")
    last_dir = val

ac = AudioController()

print "Loading sounds..."
ac.add_sound("bg01.wav")
ac.add_sound("bg02.wav")
ac.add_sound("sample2.wav")
ac.add_sound("sample3.wav")
ac.add_sound("sample4.wav")
ac.add_sound("sample5.wav")
ac.play_sound("bg01.wav", loops=-1)
ac.play_sound("bg02.wav", loops=-1)
ac.set_volume("bg02.wav",0.0)
print("finished loading sounds.")

print "Starting communications..."
com = Broadcaster(port=port, host=host)
com.on("windSpeedUpdate", updateSpeed)
com.on("windDirectionUpdate", updateDirection)
print "communications established."
print "Enjoy..."

com.wait_forever()

print "Finished"
 def test_broadcaster_created_without_receivers(self):
     broadcaster = Broadcaster()
     self.assertFalse(broadcaster.has_receivers())
 def test_broadcaster_created_with_a_receiver_registered(self):
     broadcaster = Broadcaster()
     receiver = ReceiverMock()
     broadcaster.register(receiver)
     self.assertTrue(broadcaster.has_receivers())
Ejemplo n.º 20
0
from weather_station import WeatherStation
from broadcaster import Broadcaster
import time
import os
import sys
import logging
logging.basicConfig(level=logging.DEBUG)

host = sys.argv[1]
port = sys.argv[2]
id = sys.argv[3]

com = Broadcaster(host=host, port=port)


def speedUpdate(value):
    global sound
    #print "Wind speed: %s" % value
    com.emit("windSpeedUpdate", {'value': value, 'id': id})

def directionUpdate(value):
    global sound
    #print "Wind direction: %s" % value
    com.emit("windDirectionUpdate", {'value': value, 'id': id})


ws = WeatherStation(windSpeedCallback=speedUpdate, windDirectionCallback=directionUpdate)
print "starting weather station thread."
ws.start()

com.wait_forever()
 def test_receiver_receives_broadcast(self):
     broadcaster = Broadcaster()
     receiver = ReceiverMock()
     broadcaster.register(receiver)
     broadcaster.broadcast()
     receiver.notify.assert_called_with()
 def test_using_zope_interface(self):
     broadcaster = Broadcaster()        
     receiver = ReceiverMock()
     broadcaster.register(receiver)
     broadcaster.broadcast()
     receiver.notify.assert_called_with()
Ejemplo n.º 23
0

def updateSpeed(data):
    val = data["value"]
    sendWindSpeed(val)


def updateDirection(data):
    global last_dir
    global ac
    val = data["value"]
    #print "windDirection: %s" % val
    if val != last_dir:
        sendWindDirection(val)
    last_dir = val


print "Starting communications..."
com = Broadcaster(port=8080, host="192.168.42.1")
com.on("windSpeedUpdate", updateSpeed)
com.on("windDirectionUpdate", updateDirection)
print "communications established."
print "Enjoy..."

sendWindDirection("N")
sendWindSpeed(200)

com.wait_forever()

print "Finished"