Пример #1
0
 def run2(self):
     trace('start')
     source = Source()
     translator = Translator(source)
     sink = Sink(translator)
     #exit()
     sink.run()
     trace('end')
def search_sinks():
    while True:
        if IS_WORKING == False:
            print("searching sinks...")
            p = subprocess.Popen(
                "sudo /home/respeaker/snipsAudio/./pulsemixer --get-volume",
                stdout=subprocess.PIPE,
                shell=True)
            (output, err) = p.communicate()
            p_status = p.wait()
            p = subprocess.Popen(
                "sudo /home/respeaker/snipsAudio/./pulsemixer --list",
                stdout=subprocess.PIPE,
                shell=True)
            (output, err) = p.communicate()
            p_status = p.wait()
            lines = output.splitlines()
            for line in lines:
                if line.startswith('Sink input:'):
                    if line.find("snips") == -1:
                        id = find_between(line, "ID: ", ",")
                        SINKS.add(Sink(id, 0))
            for sink in SINKS:
                p = subprocess.Popen(
                    "sudo /home/respeaker/snipsAudio/./pulsemixer --id " +
                    sink.id + " --get-volume",
                    stdout=subprocess.PIPE,
                    shell=True)
                (output, err) = p.communicate()
                p_status = p.wait()
                sink.volume = find_between(output, "", " ")
                print("Sink: " + sink.id + " has volume: " + sink.volume)
Пример #3
0
def _start_sink(number_of_simus, context):
    s = Sink(
        ADD_VENTI_LH_RECEIVE,
        ADD_SINK_RECEIVE,
        ADD_SINK_PUBLISH,
        ADD_LH_LOGGING,
        number_of_simus,
    )
    s.start()
    
    #socket to sinks
    sink = context.socket(zmq.PUSH)
    sink.connect(ADD_SINK_LH_RECEIVE)

    #socket from sink for ready    
    receiver = context.socket(zmq.PULL)
    receiver.bind(ADD_VENTI_RECEIVE)
    
    return sink, receiver
Пример #4
0
 def __load_sinks(self):
     """Load sinks for this ruleset."""
     for root, _, files in os.walk(
             os.sep.join(['modules', self.module, 'sinks'])):
         for file_ in files:
             path = os.path.join(root, file_)
             ext = os.path.splitext(path)[1]
             if ext in ('.yaml', '.yml'):
                 Ruleset.logger.debug('Loading sink from file "%s".', path)
                 with open(path) as stream:
                     self.sinks.append(Sink(yaml.safe_load(stream)))
Пример #5
0
 def connect(self, timeout=20):
     if not self.sink:
         self.sink = Sink(self.host, on_receive=self.track_sink_event)
     start = time.time()
     connected = False
     started = False
     error = None
     while time.time() - start < timeout and not self.is_ready():
         if not connected:
             try:
                 self.sink.connect(self._get_ace_port())
                 self.sink.send("HELLOBG")
                 connected = True
             except Error as error:
                 if not started:
                     self._start()
                     started = True
         self.on_poll(self.POLL_DELAY)
     if not self.is_ready():
         self.sink = None
         raise error
Пример #6
0
    def get_identifier_flow(self, identifier):
        if identifier in self.variable_flows:
            # get existing flow
            flow = self.variable_flows[identifier]
        else:
            # new variable: check if source/sink/sanitizer
            flows = []
            flows.append(Source(identifier, self.is_source(identifier)))
            flows.append(Sink(identifier, self.is_sink(identifier)))
            flows.append(Sanitizer(identifier, self.is_sanitizer(identifier)))
            flow = Flow(flows)

        return flow
Пример #7
0
    def run(self):

        address_used_internally = self.config['address_used_internally']
        range_port_init = self.config['internal_range_port']
        
        number_of_filter_scored = self.config['number_of_filter_scored']
        number_of_sum_up_players = self.config['number_of_sum_up_players']
        number_of_filters_columns = self.config['number_of_filters_columns']

        streamer_input = StreamerSubscriber(self.incoming_address, self.incoming_port, address_used_internally, range_port_init, 1, number_of_filters_columns)

        filters_columns = []        
        for i in range(number_of_filters_columns):
            filters_columns.append(FilterColumns(address_used_internally, range_port_init, address_used_internally, range_port_init + 1))
        streamer_filtered_columns = Streamer(address_used_internally, range_port_init + 1, address_used_internally, range_port_init + 2, number_of_filters_columns, number_of_filter_scored)
        
        filters_scored = []
        for i in range(number_of_filter_scored):
            filters_scored.append(FilterScored(address_used_internally, range_port_init + 2, address_used_internally, range_port_init + 3))
        streamer_scored_goals = StreamerPublisher(address_used_internally, range_port_init + 3, address_used_internally, range_port_init + 4, number_of_filter_scored, number_of_sum_up_players, lambda x: x[1])
        
        # Add subscriber here
        players_summers = []
        for i in range(number_of_sum_up_players):
            players_summers.append(SumUpPlayers(self.config['sum_up_players'], address_used_internally, range_port_init + 4, address_used_internally, range_port_init + 5, self.numerator_address, self.numerator_port))
        
        streamer_players  = Streamer(address_used_internally, range_port_init + 5, address_used_internally, range_port_init + 6, number_of_sum_up_players, 1)
      
        ranking_maker = RankingMaker(address_used_internally, range_port_init + 6, address_used_internally, range_port_init + 7)
        
        sink = Sink(address_used_internally, range_port_init + 7, self.config['output_filename'])
        
        streamer_input.start()
        for filter_columns in filters_columns:
            filter_columns.start()
        streamer_filtered_columns.start()
        for filter_scored in filters_scored:
            filter_scored.start()
        streamer_scored_goals.start()
        for players_summer in players_summers:
            players_summer.start()
        streamer_players.start()
        ranking_maker.start()
        sink.start()


        streamer_input.join()
        for filter_columns in filters_columns:    
            filter_columns.join()
        streamer_filtered_columns.join()
        for filter_scored in filters_scored:
            filter_scored.join()
        streamer_scored_goals.join()
        for player_summer in players_summers:
            players_summer.join()
        streamer_players.join()
        ranking_maker.join()
        sink.join()
Пример #8
0
 def connect(self, timeout=20):
     if not self.sink:
         self.sink = Sink(self.host, on_receive=self.track_sink_event)
     start = time.time()
     connected = False
     started = False
     error = None
     while time.time() - start < timeout and not self.is_ready():
         if not connected:
             try:
                 self.sink.connect(self._get_ace_port())
                 self.sink.send("HELLOBG")
                 connected = True
             except Error as error:
                 if not started:
                     self._start()
                     started = True
         self.on_poll(self.POLL_DELAY)
     if not self.is_ready():
         self.sink = None
         raise error
Пример #9
0
    def add_sink(self, method: Method, sink: dict):
        """Add a new sink to the list.
        New sinks are only relevant if a method's parameters are used in a sink.
        The same sanitizers are used from the original sink.

        Parameters
        ----------
        method : Method
            The method where the sink was added
        sink : dict
            A dictionary definition of the sink as defined in the ruleset
        """
        new_sink = Sink(sink)
        for existing_sink in self.sinks:
            if existing_sink.object_name != new_sink.object_name:
                continue
            if new_sink.methods == existing_sink.methods:
                break
        else:
            # Didn't break above, add new sink
            Ruleset.logger.debug('Added a new sink.  Notifying observers.')
            self.sinks.append(new_sink)
            self.notify_observers(method)
    def run(self):

        address_used_internally = self.config['address_used_internally']
        range_port_init = self.config['internal_range_port']


        number_of_filters_columns = self.config['number_of_filters_columns']
        number_of_filters_by_score = self.config['number_of_filters_by_score']

        streamer_input = StreamerSubscriber(self.incoming_address, self.incoming_port, address_used_internally, range_port_init, 1, number_of_filters_columns)


        filters_columns = []        
        for i in range(number_of_filters_columns):
            filters_columns.append(FilterColumns(address_used_internally, range_port_init, address_used_internally, range_port_init + 1 ))

        streamer_filtered_columns = Streamer(address_used_internally,  range_port_init+ 1, address_used_internally, range_port_init + 2, number_of_filters_columns, number_of_filters_by_score )
        filters_by_score = []
        for i in range(number_of_filters_by_score):
            filters_by_score.append(FilterByScore(self.filter_points, address_used_internally,  range_port_init + 2, address_used_internally, range_port_init + 3))
        streamer_filtered_points = Streamer(address_used_internally,  range_port_init + 3, address_used_internally, range_port_init + 4, number_of_filters_by_score, 1)
        sum_up_points = SumUpPoints(address_used_internally, range_port_init + 4, address_used_internally, range_port_init + 5)
        sink = Sink(address_used_internally, range_port_init + 5, self.config['output_filename'])
        
        streamer_input.start()
        for filter_columns in filters_columns:
            filter_columns.start()
        streamer_filtered_columns.start()
        for filter_by_score in filters_by_score:
            filter_by_score.start()
        streamer_filtered_points.start()
        sum_up_points.start()
        sink.start()


        streamer_input.join()
        for filter_columns in filters_columns:
            filter_columns.join()
        streamer_filtered_columns.join()
        for filter_by_score in filters_by_score:
            filter_by_score.join()
        streamer_filtered_points.join()
        sum_up_points.join()
        sink.join()
Пример #11
0
    def run(self):
        address_used_internally = self.config['address_used_internally']
        range_port_init = self.config['internal_range_port']

        input_streamer = StreamerSubscriber(self.incoming_address,
                                            self.incoming_port,
                                            address_used_internally,
                                            range_port_init, 1, 1)
        games_summarier = GamesSummarier(address_used_internally,
                                         range_port_init,
                                         address_used_internally,
                                         range_port_init + 1)
        sink = Sink(address_used_internally, range_port_init + 1,
                    '%home-wins.txt')

        input_streamer.start()
        games_summarier.start()
        sink.start()

        input_streamer.join()
        games_summarier.join()
        sink.join()
Пример #12
0
# audiocom library: Source and sink functions
import common_srcsink as common
import Image
from graphs import *
import binascii
import random
import os
import itertools
from source import Source
from sink import Sink

# Some tests

src = Source(1000, "testfiles/32pix.png")
payload, databits = src.process()

print "\n\n------------------\n\n"

sink = Sink()
print sink.process(payload)
Пример #13
0
def run(config):
    '''Primary Audiocom functionality.'''

    # Create the preamble to pre-pend to the transmission
    preamble = Preamble(config)

    # Create the sources
    sources = {}
    for i in range(len(config.channels)):
        frequency = config.channels[i]
        source = Source(config, i)
        print "Channel: %d Hz" % frequency
        print "\n".join(["\t%s" % source])
        sources[frequency] = source

    # Create a sender for each source, so we can process the bits to
    # get the modulated samples.  We combine all of the modulated
    # samples into a single array by adding them.
    modulated_samples = []
    for frequency in sources:
        src = sources[frequency]
        sender = Sender(frequency, preamble, config)
        sender.set_source(src)
        modulated_samples = util.add_arrays(sender.modulated_samples(), modulated_samples)

    # Create the channel
    if config.bypass:
        channel = AbstractChannel(config.bypass_noise, config.bypass_h, config.bypass_lag)
    else:
        channel = AudioChannel(config)

    # Transmit and receive data on the channel.  The received samples
    # (samples_rx) have not been processed in any way.
    samples_rx = channel.xmit_and_recv(modulated_samples)
    print 'Received', len(samples_rx), 'samples'

    for frequency in config.channels:
        r = Receiver(frequency, preamble, config)
        try:
            # Call the main receiver function.  The returned array of bits
            # EXCLUDES the preamble.
            bits  = r.process(samples_rx)

            # Push into a Sink so we can convert back to a useful payload
            # (this step will become more useful when we're transmitting
            # files or images instead of just bit arrays)
            src = sources[frequency]
            sink = Sink(src)
            received_payload = sink.process(bits)
            print "Received %d data bits" % len(received_payload)
            if src.type == Source.TEXT:
                print "Received text was:", sink.received_text
 
            if len(received_payload) > 0:
                # Output BER
                hd = util.hamming(received_payload, src.payload)
                ber = float(hd)/len(received_payload)
                print 'BER:', ber
            else:
                print 'Could not recover transmission.'

        except Exception as e:
            # In general, this is a fatal exception.  But we'd still like
            # to look at the graphs, so we'll continue with that output
            print '*** ERROR: Could not detect preamble. ***'
            print repr(e)

        # Plot graphs if necessary
        if config.graphs:
            try:
                len_demod = config.spb * (len(received_payload) + preamble.preamble_data_len())
            except:
                # If we didn't receive the payload, make a reasonable guess for the number of bits
                # (won't work for filetype, where n_bits changes)
                len_demod = config.spb * (config.n_bits + preamble.preamble_data_len())

            if config.demod_type == Receiver.QUADRATURE:
                filtered = r.graph_info.demod_samples
                graphs.plot_sig_spectrum(samples_rx, filtered, "received samples", "filtered samples")
            elif config.src_type == Source.U:
                demod_samples = r.graph_info.demod_samples
                plotrange = preamble.preamble_data_len()*config.spb
                graphs.plot_samples(demod_samples[plotrange:len_demod], 'unit-step response', show=True)
            else:
                graphs.plot_graphs(r.graph_info.demod_samples[:len_demod], r.graph_info.hist_samples[:len_demod], config.spb, preamble)
Пример #14
0
def run(config):
    '''Primary Audiocom functionality.'''

    # Create the preamble to pre-pend to the transmission
    preamble = Preamble(config)

    # Create a source
    source = Source(config)
    frequency = config.channel
    print "Channel: %d Hz" % frequency
    print "\n".join(["\t%s" % source])

    # Create the Sender for this Source.  Process the bits to get
    # modulated samples.
    sender = Sender(frequency, preamble, config)
    sender.set_source(source)
    modulated_samples = sender.modulated_samples()

    # Create the channel
    if config.bypass:
        channel = AbstractChannel(config.bypass_noise, config.bypass_h)
    else:
        channel = AudioChannel(config)

    # Transmit and receive data on the channel.  The received samples
    # (samples_rx) have not been processed in any way.
    samples_rx = channel.xmit_and_recv(modulated_samples)
    print 'Received', len(samples_rx), 'samples'

    r = Receiver(frequency, preamble, config)
    try:
        # Call the main receiver function.  The returned array of bits
        # EXCLUDES the preamble.
        bits  = r.process(samples_rx)

        # Push into a Sink so we can convert back to a useful payload
        # (this step will become more useful when we're transmitting
        # files or images instead of just bit arrays)
        sink = Sink(source)
        received_payload = sink.process(bits)
        print "Received %d data bits" % len(received_payload)
 
        if len(received_payload) > 0:
            # Output BER
            hd = util.hamming(received_payload, source.payload)
            ber = float(hd)/len(received_payload)
            print 'BER:', ber
        else:
            print 'Could not recover transmission.'

    except Exception as e:
        # In general, this is a fatal exception.  But we'd still like
        # to look at the graphs, so we'll continue with that output
        print '*** ERROR: Could not detect preamble. ***'

    # Plot graphs if necessary
    if config.graphs:

        try:
            len_demod = config.spb * (len(received_payload) + preamble.preamble_data_len())
        except:
            # If we didn't receive the payload, make a reasonable guess for the number of bits
            len_demod = config.spb * (config.n_bits + preamble.preamble_data_len())

        if config.src_type == Source.U:
            demod_samples = r.graph_info.demod_samples
            plotrange = preamble.preamble_data_len()*config.spb
            graphs.plot_samples(demod_samples[plotrange:len_demod], 'unit-step response', show=True)

        else:
            graphs.plot_graphs(r.graph_info.demod_samples[:len_demod], r.graph_info.hist_samples[:len_demod], config.spb, preamble)
Пример #15
0
    # use Unicorn HAT when started without parameters
    from RealHat import RealHat
    hat = RealHat()
else:
    # just show the matrix status on the console when started with one parameter
    from FakeHat import FakeHat
    hat = FakeHat()

#################################################################################

app = Flask(__name__)
auth = HTTPBasicAuth()

app.debug = True
led = Matrix(hat)
sink = Sink(led)


# http post http://127.0.0.1:5500/update status:='["NONE","BUILDING","OK","ERROR","NONE","WHAT?"]' --auth giveme:someled
# win: http post http://giveme:[email protected]:5500/update  status:="[\"NONE\",\"BUILDING\",\"OK\",\"ERROR\",\"NONE\",\"WHAT?\"]"
@app.route("/update", methods=['POST'])
@auth.login_required
def update():
    content = request.get_json(silent=True)
    status = content['status']
    return str(sink.put(status))


@auth.verify_password
def verify_password(username, password):
    return username == 'giveme' and password == 'someled'
Пример #16
0
        samples_rx = channel.xmit_and_recv(mod_samples)
    except ZeroDivisionError:
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)

    # push into sink
    sink = Sink()
    #rcd_payload = sink.process(rcdbits)
    rcd_payload = sink.process(databits)

    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(rcd_payload, src_payload)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
                len_mod = len(mod_samples) - opt.spb*opt.silence 
                len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
                plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)
Пример #17
0
class Engine:
    POLL_DELAY = 0.1
    ADDON_KEY = 'bjUxTHZRb1RsSnpOR2FGeHNlUkstdXZudlgtc0Q0Vm01QXh3bWM0VWNvRC1qcnV4bUtzdUphSDBl\nVmdF\n'

    DEFAULT_HOST = "127.0.0.1"
    DEFAULT_PORT = 62062

    def __init__(self,
                 host=DEFAULT_HOST,
                 port=DEFAULT_PORT,
                 save_path=None,
                 save_encrypted=False,
                 log=None,
                 on_playback_resumed=None,
                 on_playback_paused=None,
                 on_poll=None):
        self.log = log or logging.getLogger(__name__)
        self.state = None
        self.host = host
        self.port = port
        self.sink = None
        self.duration = None
        self.link = None
        self.is_ad = False
        self.is_live = False
        self.can_save = []
        self.files = None
        self.key = None
        self.version = None
        self.status = None
        self.progress = 0
        self.down_speed = 0
        self.up_speed = 0
        self.peers = 0
        self.download = 0
        self.upload = 0
        self.save_path = save_path
        self.save_indexes = []
        self.save_encrypted = save_encrypted
        self.saved_files = {}
        self.on_playback_resumed = on_playback_resumed
        self.on_playback_paused = on_playback_paused
        self.error = False
        self.error_msg = None
        self.last_event = None
        self.last_event_params = None
        self.auth_level = None
        self.infohash = None
        self.ready = False
        self.on_poll = on_poll or time.sleep

    def on_start(self, duration):
        self.duration = duration * 1000
        self.sink.send("DUR %s %s" % (self.link, self.duration))
        self.sink.send("PLAYBACK %s 0" % self.link)

    def on_pause(self):
        self.sink.send("EVENT pause")

    def on_resume(self):
        self.sink.send("EVENT play")

    def on_stop(self):
        self.sink.send("EVENT stop")
        self.sink.send("STOP")

    def on_seek(self, _time):
        self.sink.send("EVENT seek position=%s" % int(_time / 1000))

    def on_end(self):
        self.sink.send("PLAYBACK %s 100" % self.link)
        self.sink.send("EVENT stop")
        self.sink.send("STOP")

    def close(self):
        self.log.info("Closing AceStream engine")
        if self.sink:
            if self.state > 0:
                self.on_stop()
            self.sink.send("SHUTDOWN")

    def shutdown(self):
        if self.sink:
            self.sink.end()

    def _start(self):
        if not self._is_local():
            return True
        if self.save_path and not os.path.isdir(self.save_path):
            raise Error("Invalid download path (%s)" % self.save_path,
                        Error.INVALID_DOWNLOAD_PATH)
        if sys.platform.startswith("win"):
            return self._start_windows()
        else:
            try:
                self._start_linux()
            except Error:
                self._start_android()

    def connect(self, timeout=20):
        if not self.sink:
            self.sink = Sink(self.host, on_receive=self.track_sink_event)
        start = time.time()
        connected = False
        started = False
        error = None
        while time.time() - start < timeout and not self.is_ready():
            if not connected:
                try:
                    self.sink.connect(self._get_ace_port())
                    self.sink.send("HELLOBG")
                    connected = True
                except Error as error:
                    if not started:
                        self._start()
                        started = True
            self.on_poll(self.POLL_DELAY)
        if not self.is_ready():
            self.sink = None
            raise error

    @staticmethod
    def _unique_id():
        import random
        return random.randint(0, 0x7fffffff)

    def _files(self, timeout=20):
        start = time.time()
        while time.time(
        ) - start < timeout and self.files is None and not self.error:
            self.on_poll(self.POLL_DELAY)
        if self.error:
            raise Error(self.error_msg, Error.CANT_LOAD_TORRENT)
        elif self.files is not None:
            return self.files
        else:
            raise Error("Timeout while getting files list", Error.TIMEOUT)

    def load_torrent(self,
                     url,
                     developer_id=0,
                     offiliate_id=0,
                     zone_id=0,
                     timeout=20):
        self.sink.send(
            "LOADASYNC %d TORRENT %s %d %d %d" %
            (self._unique_id(), url, developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_infohash(self,
                      infohash,
                      developer_id=0,
                      offiliate_id=0,
                      zone_id=0,
                      timeout=20):
        self.sink.send(
            "LOADASYNC %d INFOHASH %s %d %d %d" %
            (self._unique_id(), infohash, developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_data(self,
                  data,
                  developer_id=0,
                  offiliate_id=0,
                  zone_id=0,
                  timeout=20):
        import base64
        self.sink.send("LOADASYNC %d RAW %s %d %d %d" %
                       (self._unique_id(), base64.b64encode(data),
                        developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_pid(self, content_id, timeout=20):
        self.sink.send("LOADASYNC %d PID %d" % (self._unique_id(), content_id))
        return self._files(timeout)

    def _start_play(self, timeout=20):
        start = time.time()
        while time.time(
        ) - start < timeout and not self.state and not self.error:
            self.on_poll(self.POLL_DELAY)
        if self.error:
            raise Error(self.error_msg, Error.CANT_PLAY_TORRENT)
        elif self.state:
            return
        else:
            raise Error("Timeout while starting playback", Error.TIMEOUT)

    def play_torrent(self,
                     url,
                     indexes=None,
                     developer_id=0,
                     offiliate_id=0,
                     zone_id=0,
                     stream_id=0,
                     timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START TORRENT %s %s %d %d %d %d" %
                       (url, ",".join(str(index) for index in indexes),
                        developer_id, offiliate_id, zone_id, stream_id))
        self._start_play(timeout)

    def play_infohash(self,
                      infohash,
                      indexes=None,
                      developer_id=0,
                      offiliate_id=0,
                      zone_id=0,
                      timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START INFOHASH %s %s %d %d %d" % (infohash, ",".join(
            str(index)
            for index in indexes), developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_pid(self, content_id, indexes=None, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START PID %d %s" %
                       (content_id, ",".join(str(index) for index in indexes)))
        self._start_play(timeout)

    def play_data(self,
                  data,
                  indexes=None,
                  developer_id=0,
                  offiliate_id=0,
                  zone_id=0,
                  timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        import base64
        self.sink.send(
            "START RAW %s %s %d %d %d" % (base64.b64encode(data), ",".join(
                str(index)
                for index in indexes), developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_url(self,
                 url,
                 indexes=None,
                 developer_id=0,
                 offiliate_id=0,
                 zone_id=0,
                 timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START URL %s %s %d %d %d" % (url, ",".join(
            str(index)
            for index in indexes), developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_efile(self, url, timeout=20):
        self.sink.send("START EFILE %s" % url)
        self._start_play(timeout)

    def get_status(self):
        return Status(state=self.state,
                      status=self.status,
                      progress=self.progress,
                      down_speed=self.down_speed,
                      up_speed=self.up_speed,
                      peers=self.peers,
                      url=self.link,
                      error=self.error_msg,
                      download=self.download,
                      upload=self.upload)

    def _start_windows(self):
        import _winreg
        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                  "Software\\AceStream")
            path = _winreg.QueryValueEx(key, "EnginePath")[0]
        except _winreg.error:
            # trying previous version
            try:
                import _winreg
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                      "Software\\TorrentStream")
                path = _winreg.QueryValueEx(key, "EnginePath")[0]
            except _winreg.error:
                raise Error("Can't find AceStream executable",
                            Error.CANT_FIND_EXECUTABLE)
        try:
            self.log.info("Starting AceStream engine for Windows: %s" % path)
            os.startfile(path)
        except:
            raise Error("Can't start AceStream engine",
                        Error.CANT_START_ENGINE)

    def _start_linux(self):
        import subprocess
        try:
            self.log.info("Starting AceStream engine for Linux")
            subprocess.Popen(["acestreamengine", "--client-console"])
        except OSError:
            try:
                subprocess.Popen('acestreamengine-client-console')
            except OSError:
                raise Error("AceStream engine is not installed",
                            Error.CANT_START_ENGINE)

    def _start_android(self):
        try:
            import xbmc
            self.log.info("Starting AceStream engine for Android")
            xbmc.executebuiltin(
                'XBMC.StartAndroidActivity("org.acestream.engine")')
        except:
            raise Error("AceStream engine is not installed",
                        Error.CANT_START_ENGINE)

    def _get_ace_port(self):
        if not self._is_local() or not sys.platform.startswith("win"):
            return self.port
        import _winreg
        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                  "Software\\AceStream")
            engine_exe = _winreg.QueryValueEx(key, "EnginePath")[0]
            path = engine_exe.replace("ace_engine.exe", "")
        except _winreg.error:
            # trying previous version
            try:
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                      "Software\\TorrentStream")
                engine_exe = _winreg.QueryValueEx(key, "EnginePath")[0]
                path = engine_exe.replace("tsengine.exe", "")
            except _winreg.error:
                return self.port
        pfile = os.path.join(path, "acestream.port")
        try:
            hfile = open(pfile, "r")
            return int(hfile.read())
        except IOError:
            return self.port

    def is_ready(self):
        return self.state >= 0

    def track_sink_event(self, event, params):
        self.last_event = event
        self.last_event_params = params

        if event == "STATUS":
            self._update_status(params)

        elif event == "START" or event == "PLAY":
            parts = params.split(" ")
            self.link = parts[0].replace(self.DEFAULT_HOST, self.host)

            if len(parts) > 1:
                if "ad=1" in parts:
                    self.is_ad = True
                    self.sink.send("PLAYBACK %s 100" % self.link)
                    self.link = None
                else:
                    self.is_ad = False

                if "stream=1" in parts:
                    self.is_live = True

        elif event == "AUTH":
            self.auth_level = int(params)
            self.state = State.IDLE

        elif event == "STATE":
            self.state = int(params)

        elif event == "EVENT":
            parts = params.split(" ")
            if len(parts) > 1 and "cansave" in parts:
                if self.save_path:
                    self._save_file(int(parts[1].split("=")[1]),
                                    parts[2].split("=")[1],
                                    parts[3].split("=")[1])

        elif event == "RESUME":
            if self.on_playback_resumed is not None:
                self.on_playback_resumed()

        elif event == "PAUSE":
            if self.on_playback_paused is not None:
                self.on_playback_paused()

        elif event == "HELLOTS":
            parts = params.split(" ")
            for part in parts:
                k, v = part.split("=")
                if k == "key":
                    self.key = v
                elif k == "version":
                    self.version = v
            cmd = "READY"
            if self.key:
                import hashlib
                sha1 = hashlib.sha1()
                addon_key = base64.decodestring(self.ADDON_KEY)
                sha1.update(self.key + addon_key)
                cmd = "READY key=%s-%s" % (addon_key.split("-")[0],
                                           sha1.hexdigest())

            self.sink.send(cmd)

        elif event == "LOADRESP":
            import json
            resp_json = json.loads(params[params.find("{"):len(params)])
            if resp_json["status"] == 100:
                self.error_msg = resp_json["message"]
                self.error = True
            else:
                self.infohash = resp_json["infohash"]
                if resp_json["status"] > 0:
                    self.files = OrderedDict((f[1], urllib.unquote(f[0]))
                                             for f in resp_json["files"])
                else:
                    self.files = OrderedDict()
        elif event == "SHUTDOWN":
            self.shutdown()

    def _save_file(self, index, infohash, _format):
        import urllib

        index = int(index)
        if self.save_path and index in self.save_indexes:
            filename = self.files and self.files[index] or infohash
            if _format == "encrypted":
                if not self.save_encrypted:
                    return
                filename += ".acemedia"
            path = os.path.join(self.save_path, filename)
            if not os.path.exists(path):
                dir_name = os.path.dirname(path)
                if not os.path.exists(dir_name):
                    os.mkdir(dir_name)
                self.sink.send("SAVE infohash=%s index=%s path=%s" %
                               (infohash, index, urllib.quote(path)))
            self.saved_files[index] = path

    def _update_status(self, status_string):
        import re

        ss = re.compile("main:[a-z]+", re.S)
        s1 = re.findall(ss, status_string)[0]
        self.status = s1.split(":")[1]

        if self.status == "starting":
            self.progress = 0
        if self.status == "loading":
            self.progress = 0
        if self.status == "prebuf":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[5])
            self.up_speed = int(parts[7])
            self.peers = int(parts[8])
            self.download = int(parts[10])
            self.upload = int(parts[12])
        if self.status == "buf":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[5])
            self.up_speed = int(parts[7])
            self.peers = int(parts[8])
            self.download = int(parts[10])
            self.upload = int(parts[12])
        if self.status == "dl":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[3])
            self.up_speed = int(parts[5])
            self.peers = int(parts[6])
            self.download = int(parts[8])
            self.upload = int(parts[10])
        if self.status == "check":
            self.progress = int(status_string.split(";")[1])
        if self.status == "idle":
            self.progress = 0
        if self.status == "wait":
            self.progress = 0
        if self.status == "err":
            parts = status_string.split(";")
            self.error = True
            self.error_id = parts[1]
            self.error_msg = parts[2]

    def _is_local(self):
        return self.host == self.DEFAULT_HOST
Пример #18
0
    except ZeroDivisionError:
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)

    # push into sink
    sink = Sink()

    rcd_payload = sink.process(rcdbits)
    
    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(rcd_payload, src_payload)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
                len_mod = len(mod_samples) - opt.spb*opt.silence 
                len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
                plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)

Пример #19
0
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    if opt.cc_len!=0:
        rcdbits = r.decode(rcdbits)

    # push into sink
    sink = Sink(opt.compress)
    sink_bits = sink.process(rcdbits)
    
    if len(sink_bits) > 0:
        hd, err = common_srcsink.hamming(sink_bits, src_bits)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
        len_mod = len(mod_samples) - opt.spb*opt.silence 
        len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
        plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)


Пример #20
0
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)

    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    if opt.cc_len!=0:
        rcdbits = r.decode(rcdbits)

    # push into sink
    sink = Sink(opt.compress, opt.encrypt)
    sink_bits = sink.process(rcdbits, pubkey)
    
    if len(sink_bits) > 0:
        hd, err = common_srcsink.hamming(sink_bits, src_bits)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
        len_mod = len(mod_samples) - opt.spb*opt.silence 
        len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
        plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)
Пример #21
0
 def __init__(self, source):
     self.input_type = kafka.consumer.fetcher.ConsumerRecord
     self.output_type = WireMessage
     Sink.__init__(self, source)
     Source.__init__(self)
Пример #22
0
 def run1(self):
     trace('start')
     source = Source()
     sink = Sink(source)
     sink.run()
     trace('end')
Пример #23
0
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    
    # push into sink
    sink = Sink()
    rcd_payload = sink.process(rcdbits)
    """
    sink = Sink()
    rcd_payload = sink.process(src_payload)
    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(rcd_payload, src_payload)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
                len_mod = len(mod_samples) - opt.spb*opt.silence 
                len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
                plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)


Пример #24
0
def setSink(x,y):
    sinks.append( Sink())
    sinks[len(sinks) -1].set_dimensions(50,50) 
    sinks[len(sinks) -1].y_pos = y
    sinks[len(sinks) -1].x_pos = x
Пример #25
0
def run(config):
    '''Primary Audiocom functionality.'''

    # Create the preamble to pre-pend to the transmission
    preamble = Preamble(config)

    # Create the sources
    sources = {}
    for i in range(len(config.channels)):
        frequency = config.channels[i]
        source = Source(config, i)
        print("Channel: %d Hz" % frequency)
        print("\n".join(["\t%s" % source]))
        sources[frequency] = source

    # Create a sender for each source, so we can process the bits to
    # get the modulated samples.  We combine all of the modulated
    # samples into a single array by adding them.

    baseband_samples = []
    modulated_samples = []

    for frequency in sources:
        src = sources[frequency]
        sender = Sender(frequency, preamble, config)
        sender.set_source(src)

        modulated_samples = util.add_arrays(sender.modulated_samples(),
                                            modulated_samples)
        baseband_samples = util.add_arrays(sender.bits_to_samples(src.payload),
                                           baseband_samples)
        print("sending %d samples" % len(modulated_samples))

    # Create the channel
    if config.bypass:
        channel = AbstractChannel(config.bypass_noise, config.bypass_h)
    else:
        channel = AudioChannel(config)

    # Transmit and receive data on the channel.  The received samples
    # (samples_rx) have not been processed in any way.
    samples_rx = channel.xmit_and_recv(modulated_samples)
    print('Received', len(samples_rx), 'samples')

    for frequency in config.channels:
        r = Receiver(frequency, preamble, config)
        try:
            # Call the main receiver function.  The returned array of bits
            # EXCLUDES the preamble.
            bits = r.process(samples_rx)

            # Push into a Sink so we can convert back to a useful payload
            # (this step will become more useful when we're transmitting
            # files or images instead of just bit arrays)
            src = sources[frequency]
            sink = Sink(src)
            received_payload = sink.process(bits)
            print("Received %d data bits" % len(received_payload))
            if src.type == Source.TEXT:
                print("Received text was:", sink.received_text)

            if len(received_payload) > 0:
                # Output BER
                hd = util.hamming(received_payload, src.payload)
                ber = float(hd) / len(received_payload)
                print('BER:', ber)
            else:
                print('Could not recover transmission.')

        except Exception as e:
            # In general, this is a fatal exception.  But we'd still like
            # to look at the graphs, so we'll continue with that output
            #            print('*** ERROR: Could not detect preamble. ***')
            print(repr(e))

        if config.graphs == "time":
            graphs.plot_samples(baseband_samples,
                                modulated_samples,
                                r.graph_info.received_samples,
                                stems=False)
        elif config.graphs == "freq":
            graphs.plot_sig_spectrum(modulated_samples,
                                     r.graph_info.demod_samples)
        elif config.graphs == "usr":
            graphs.plot_usr(r.graph_info.demod_samples)
Пример #26
0
    except ZeroDivisionError:
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

# process the received samples
# make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)

    # push into sink
    sink = Sink()
    rcd_payload = sink.process(rcdbits)

    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(rcd_payload, src_payload)
        print 'Hamming distance for payload at frequency', fc, 'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
        len_mod = len(mod_samples) - opt.spb * opt.silence
        len_demod = len_mod - opt.spb * (len(src_payload) - len(rcd_payload))
        plot_graphs(mod_samples, samples_rx[barker_start:],
                    demod_samples[barker_start:barker_start + len_demod],
                    opt.spb, src.srctype, opt.silence)
Пример #27
0
        sys.exit(1)
#################################

# process the received samples
# make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)

    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    if opt.cc_len != 0:
        rcdbits = r.decode(rcdbits)

    # push into sink
    sink = Sink(opt.compress, opt.encrypt)
    sink_bits = sink.process(rcdbits, pubkey)

    if len(sink_bits) > 0:
        hd, err = common_srcsink.hamming(sink_bits, src_bits)
        print 'Hamming distance for payload at frequency', fc, 'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
        len_mod = len(mod_samples) - opt.spb * opt.silence
        len_demod = len_mod - opt.spb * (len(src_payload) - len(rcd_payload))
        plot_graphs(mod_samples, samples_rx[barker_start:],
                    demod_samples[barker_start:barker_start + len_demod],
                    opt.spb, src.srctype, opt.silence)
# USAGE: sudo python poll_hd.py <poll_wait_s> <cctray.xml_url_1> <cctray.xml_url_2> ... <cctray.xml_url_n>

if len(sys.argv) < 3:
    print("at least 2 arguments needed")
    exit(1)

from RealHatHD import RealHatHD
hat = RealHatHD()
poll_wait_s = int(sys.argv[1])
urls = sys.argv[2:]

#################################################################################

led = Matrix(hat)
sink = Sink(led)

if __name__ == "__main__":
    try:
        while True:
            status = []
            for url in urls:
                try:
                    cctray = CCTray(url, hat.AREA)
                    status += cctray.fetch()
                except Exception, e:
                    print e

            sink.put(status)
            time.sleep(poll_wait_s)
Пример #29
0
from sink import Sink
from source import Source
import numpy as np
from common_srcsink import hamming

compress = True
sou = Source(1, "testfiles/columns.png", compress)
sink = Sink(compress)

a, b, c = sou.process()
srcbits = sink.process(c)


# #testArr = np.array([1, 1, 1, 0, 0, 0, 0, 0])
# testArr = sou.text2bits("testfiles/Time.txt")

# statistics_bits, encoded_bits  = sou.huffman_encode(testArr)
# print len(encoded_bits)

# print "Encoded bits", encoded_bits
# print

# sink = Sink(1)

# srcbits = sink.huffman_decode(encoded_bits, statistics_bits)

# text = sink.bits2text(srcbits)


# print 
# print
Пример #30
0
class Engine:
    POLL_DELAY = 0.1
    ADDON_KEY = "n51LvQoTlJzNGaFxseRK-uvnvX-sD4Vm5Axwmc4UcoD-jruxmKsuJaH0eVgE"

    DEFAULT_HOST = "127.0.0.1"
    DEFAULT_PORT = 62062

    def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, save_path=None, save_encrypted=False,
                 log=None, on_playback_resumed=None, on_playback_paused=None, on_poll=None):
        self.log = log or logging.getLogger(__name__)
        self.state = None
        self.host = host
        self.port = port
        self.sink = None
        self.duration = None
        self.link = None
        self.is_ad = False
        self.is_live = False
        self.can_save = []
        self.files = None
        self.key = None
        self.version = None
        self.status = None
        self.progress = 0
        self.down_speed = 0
        self.up_speed = 0
        self.peers = 0
        self.download = 0
        self.upload = 0
        self.save_path = save_path
        self.save_indexes = []
        self.save_encrypted = save_encrypted
        self.saved_files = {}
        self.on_playback_resumed = on_playback_resumed
        self.on_playback_paused = on_playback_paused
        self.error = False
        self.error_msg = None
        self.last_event = None
        self.last_event_params = None
        self.auth_level = None
        self.infohash = None
        self.ready = False
        self.on_poll = on_poll or time.sleep

    def on_start(self, duration):
        self.duration = duration * 1000
        self.sink.send("DUR %s %s" % (self.link, self.duration))
        self.sink.send("PLAYBACK %s 0" % self.link)

    def on_pause(self):
        self.sink.send("EVENT pause")

    def on_resume(self):
        self.sink.send("EVENT play")

    def on_stop(self):
        self.sink.send("EVENT stop")
        self.sink.send("STOP")

    def on_seek(self, _time):
        self.sink.send("EVENT seek position=%s" % int(_time / 1000))

    def on_end(self):
        self.sink.send("PLAYBACK %s 100" % self.link)
        self.sink.send("EVENT stop")
        self.sink.send("STOP")

    def close(self):
        self.log.info("Closing AceStream engine")
        if self.sink:
            if self.state > 0:
                self.on_stop()
            self.sink.send("SHUTDOWN")

    def shutdown(self):
        if self.sink:
            self.sink.end()

    def _start(self):
        if not self._is_local():
            return True
        if self.save_path and not os.path.isdir(self.save_path):
            raise Error("Invalid download path (%s)" % self.save_path, Error.INVALID_DOWNLOAD_PATH)
        if sys.platform.startswith("win"):
            return self._start_windows()
        else:
            try:
                self._start_linux()
            except Error:
                self._start_android()

    def connect(self, timeout=20):
        if not self.sink:
            self.sink = Sink(self.host, on_receive=self.track_sink_event)
        start = time.time()
        connected = False
        started = False
        error = None
        while time.time() - start < timeout and not self.is_ready():
            if not connected:
                try:
                    self.sink.connect(self._get_ace_port())
                    self.sink.send("HELLOBG")
                    connected = True
                except Error as error:
                    if not started:
                        self._start()
                        started = True
            self.on_poll(self.POLL_DELAY)
        if not self.is_ready():
            self.sink = None
            raise error

    @staticmethod
    def _unique_id():
        import random
        return random.randint(0, 0x7fffffff)

    def _files(self, timeout=20):
        start = time.time()
        while time.time() - start < timeout and self.files is None and not self.error:
            self.on_poll(self.POLL_DELAY)
        if self.error:
            raise Error(self.error_msg, Error.CANT_LOAD_TORRENT)
        elif self.files is not None:
            return self.files
        else:
            raise Error("Timeout while getting files list", Error.TIMEOUT)

    def load_torrent(self, url, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        self.sink.send("LOADASYNC %d TORRENT %s %d %d %d" % (self._unique_id(), url,
                                                             developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_infohash(self, infohash, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        self.sink.send("LOADASYNC %d INFOHASH %s %d %d %d" % (self._unique_id(), infohash,
                                                              developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_data(self, data, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        import base64
        self.sink.send("LOADASYNC %d RAW %s %d %d %d" % (self._unique_id(), base64.b64encode(data),
                                                         developer_id, offiliate_id, zone_id))
        return self._files(timeout)

    def load_pid(self, content_id, timeout=20):
        self.sink.send("LOADASYNC %d PID %d" % (self._unique_id(), content_id))
        return self._files(timeout)

    def _start_play(self, timeout=20):
        start = time.time()
        while time.time() - start < timeout and not self.state and not self.error:
            self.on_poll(self.POLL_DELAY)
        if self.error:
            raise Error(self.error_msg, Error.CANT_PLAY_TORRENT)
        elif self.state:
            return
        else:
            raise Error("Timeout while starting playback", Error.TIMEOUT)

    def play_torrent(self, url, indexes=None, developer_id=0, offiliate_id=0, zone_id=0, stream_id=0, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START TORRENT %s %s %d %d %d %d" % (url, ",".join(str(index) for index in indexes),
                                                            developer_id, offiliate_id, zone_id, stream_id))
        self._start_play(timeout)

    def play_infohash(self, infohash, indexes=None, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START INFOHASH %s %s %d %d %d" % (infohash, ",".join(str(index) for index in indexes),
                                                          developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_pid(self, content_id, indexes=None, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START PID %d %s" % (content_id, ",".join(str(index) for index in indexes)))
        self._start_play(timeout)

    def play_data(self, data, indexes=None, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        import base64
        self.sink.send("START RAW %s %s %d %d %d" % (base64.b64encode(data), ",".join(str(index) for index in indexes),
                                                     developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_url(self, url, indexes=None, developer_id=0, offiliate_id=0, zone_id=0, timeout=20):
        indexes = indexes or [0]
        self.saved_files = {}
        self.save_indexes = indexes
        self.sink.send("START URL %s %s %d %d %d" % (url, ",".join(str(index) for index in indexes),
                                                     developer_id, offiliate_id, zone_id))
        self._start_play(timeout)

    def play_efile(self, url, timeout=20):
        self.sink.send("START EFILE %s" % url)
        self._start_play(timeout)

    def get_status(self):
        return Status(state=self.state, status=self.status, progress=self.progress, down_speed=self.down_speed,
                      up_speed=self.up_speed, peers=self.peers, url=self.link, error=self.error_msg,
                      download=self.download, upload=self.upload)

    def _start_windows(self):
        import _winreg
        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\AceStream")
            path = _winreg.QueryValueEx(key, "EnginePath")[0]
        except _winreg.error:
            # trying previous version
            try:
                import _winreg
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\TorrentStream")
                path = _winreg.QueryValueEx(key, "EnginePath")[0]
            except _winreg.error:
                raise Error("Can't find AceStream executable", Error.CANT_FIND_EXECUTABLE)
        try:
            self.log.info("Starting AceStream engine for Windows: %s" % path)
            os.startfile(path)
        except:
            raise Error("Can't start AceStream engine", Error.CANT_START_ENGINE)

    def _start_linux(self):
        import subprocess
        try:
            self.log.info("Starting AceStream engine for Linux")
            subprocess.Popen(["acestreamengine", "--client-console"])
        except OSError:
            try:
                subprocess.Popen('acestreamengine-client-console')
            except OSError:
                raise Error("AceStream engine is not installed", Error.CANT_START_ENGINE)

    def _start_android(self):
        try:
            import xbmc
            self.log.info("Starting AceStream engine for Android")
            xbmc.executebuiltin('XBMC.StartAndroidActivity("org.acestream.engine")')
        except:
            raise Error("AceStream engine is not installed", Error.CANT_START_ENGINE)

    def _get_ace_port(self):
        if not self._is_local() or not sys.platform.startswith("win"):
            return self.port
        import _winreg
        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\AceStream")
            engine_exe = _winreg.QueryValueEx(key, "EnginePath")[0]
            path = engine_exe.replace("ace_engine.exe", "")
        except _winreg.error:
            # trying previous version
            try:
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\TorrentStream")
                engine_exe = _winreg.QueryValueEx(key, "EnginePath")[0]
                path = engine_exe.replace("tsengine.exe", "")
            except _winreg.error:
                return self.port
        pfile = os.path.join(path, "acestream.port")
        try:
            hfile = open(pfile, "r")
            return int(hfile.read())
        except IOError:
            return self.port

    def is_ready(self):
        return self.state >= 0

    def track_sink_event(self, event, params):
        self.last_event = event
        self.last_event_params = params

        if event == "STATUS":
            self._update_status(params)

        elif event == "START" or event == "PLAY":
            parts = params.split(" ")
            self.link = parts[0].replace(self.DEFAULT_HOST, self.host)

            if len(parts) > 1:
                if "ad=1" in parts:
                    self.is_ad = True
                    self.sink.send("PLAYBACK %s 100" % self.link)
                    self.link = None
                else:
                    self.is_ad = False

                if "stream=1" in parts:
                    self.is_live = True

        elif event == "AUTH":
            self.auth_level = int(params)
            self.state = State.IDLE

        elif event == "STATE":
            self.state = int(params)

        elif event == "EVENT":
            parts = params.split(" ")
            if len(parts) > 1 and "cansave" in parts:
                if self.save_path:
                    self._save_file(int(parts[1].split("=")[1]), parts[2].split("=")[1], parts[3].split("=")[1])

        elif event == "RESUME":
            if self.on_playback_resumed is not None:
                self.on_playback_resumed()

        elif event == "PAUSE":
            if self.on_playback_paused is not None:
                self.on_playback_paused()

        elif event == "HELLOTS":
            parts = params.split(" ")
            for part in parts:
                k, v = part.split("=")
                if k == "key":
                    self.key = v
                elif k == "version":
                    self.version = v
            cmd = "READY"
            if self.key:
                import hashlib
                sha1 = hashlib.sha1()

                sha1.update(self.key + self.ADDON_KEY)
                cmd = "READY key=%s-%s" % (self.ADDON_KEY.split("-")[0], sha1.hexdigest())

            self.sink.send(cmd)

        elif event == "LOADRESP":
            import json
            resp_json = json.loads(params[params.find("{"):len(params)])
            if resp_json["status"] == 100:
                self.error_msg = resp_json["message"]
                self.error = True
            else:
                self.infohash = resp_json["infohash"]
                if resp_json["status"] > 0:
                    self.files = OrderedDict((f[1], urllib.unquote(f[0])) for f in resp_json["files"])
                else:
                    self.files = OrderedDict()
        elif event == "SHUTDOWN":
            self.shutdown()

    def _save_file(self, index, infohash, _format):
        import urllib

        index = int(index)
        if self.save_path and index in self.save_indexes:
            filename = self.files and self.files[index] or infohash
            if _format == "encrypted":
                if not self.save_encrypted:
                    return
                filename += ".acemedia"
            path = os.path.join(self.save_path, filename)
            if not os.path.exists(path):
                dir_name = os.path.dirname(path)
                if not os.path.exists(dir_name):
                    os.mkdir(dir_name)
                self.sink.send("SAVE infohash=%s index=%s path=%s" % (infohash, index, urllib.quote(path)))
            self.saved_files[index] = path

    def _update_status(self, status_string):
        import re

        ss = re.compile("main:[a-z]+", re.S)
        s1 = re.findall(ss, status_string)[0]
        self.status = s1.split(":")[1]

        if self.status == "starting":
            self.progress = 0
        if self.status == "loading":
            self.progress = 0
        if self.status == "prebuf":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[5])
            self.up_speed = int(parts[7])
            self.peers = int(parts[8])
            self.download = int(parts[10])
            self.upload = int(parts[12])
        if self.status == "buf":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[5])
            self.up_speed = int(parts[7])
            self.peers = int(parts[8])
            self.download = int(parts[10])
            self.upload = int(parts[12])
        if self.status == "dl":
            parts = status_string.split(";")
            self.progress = int(parts[1])
            self.down_speed = int(parts[3])
            self.up_speed = int(parts[5])
            self.peers = int(parts[6])
            self.download = int(parts[8])
            self.upload = int(parts[10])
        if self.status == "check":
            self.progress = int(status_string.split(";")[1])
        if self.status == "idle":
            self.progress = 0
        if self.status == "wait":
            self.progress = 0
        if self.status == "err":
            parts = status_string.split(";")
            self.error = True
            self.error_id = parts[1]
            self.error_msg = parts[2]

    def _is_local(self):
        return self.host == self.DEFAULT_HOST
Пример #31
0
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    decoded_bits = r.decode(rcdbits)

    # push into sink
    sink = Sink()
    rcd_payload = sink.process(databits)#sink.process(decoded_bits)
    
    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(decoded_bits, databits)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
                len_mod = len(mod_samples) - opt.spb*opt.silence 
                len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
                plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)


Пример #32
0
from bolt import Bolt
from sink import Sink
from spout import Spout
from splitBolt import SplitBolt

sp = Spout(paraNext=2)
blt = SplitBolt(parallelism=2, paraNext=[2, 2], grouping='key')
#blt = Bolt(parallelism=2, paraNext=2)
si = Sink(parallelism=2)
si2 = Sink(parallelism=2)

for i in range(0, 10):
    ret = blt.run(sp.run())
    si.run(ret[0])
    si2.run(ret[1])

si.getProcessed()
        # should only happen for audio channel
        print "I didn't get any samples; is your microphone or speaker OFF?"
        sys.exit(1)
#################################

    # process the received samples
    # make receiver
    r = Receiver(fc, opt.samplerate, opt.spb)
    demod_samples = r.demodulate(samples_rx)
    one, zero, thresh = r.detect_threshold(demod_samples)
    barker_start = r.detect_preamble(demod_samples, thresh, one)
    rcdbits = r.demap_and_check(demod_samples, barker_start)
    decoded_bits = r.decode(rcdbits)

    # push into sink
    sink = Sink()
    rcd_payload = sink.process(decoded_bits)

    if len(rcd_payload) > 0:
        hd, err = common_srcsink.hamming(decoded_bits, databits)
        print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err
    else:
        print 'Could not recover transmission.'

    if opt.graph:
                len_mod = len(mod_samples) - opt.spb*opt.silence
                len_demod = len_mod - opt.spb*(len(src_payload) - len(rcd_payload))
                plot_graphs(mod_samples, samples_rx[barker_start:], demod_samples[barker_start:barker_start + len_demod], opt.spb, src.srctype, opt.silence)


url = 'http://localhost:8153/go/cctray.xml'
poll_wait_s = 5

if len(sys.argv) == 1:
    from FakeHat import FakeHat
    hat = FakeHat()

if len(sys.argv) > 1:
    from RealHat import RealHat
    hat = RealHat()
    url = sys.argv[1]

if len(sys.argv) > 2:
    poll_wait_s = int(sys.argv[2])

#################################################################################

led = Matrix(hat)
sink = Sink(led)
cctray = CCTray(url, hat.AREA)

if __name__ == "__main__":
    while True:
        try:
            sink.put(cctray.fetch())
        except Exception, e:
            print e

        time.sleep(poll_wait_s)