Example #1
0
 def __init__(self, servaddr, servport, device_args="", rx_txrx=False):
     self.pipe = None
     self.conproc = None
     self.logger = None
     self.setup_logger()
     self.radio = Radio(self.logger, device_args, rx_txrx)
     self.connector = ClientConnector(servaddr, servport)
Example #2
0
	def __init__(self):
		super(Main, self).__init__()
		## initialize sensors
		self.sensorThread = False
		self.radioThread = False
		self.cameraThread = False
		try:
			self.sensorThread = Sensors()
		except:
			print("error initing sensor thread")
		try:
			pass
			#self.cameraThread = Camera('Mini')
		except:
			print("error initializing camera thread")
		try:
			self.radioThread = Radio(self)
		except:
			print("error initing radio thread")
		#self.numberGen = RandomThread()
		self.daemon = True
		self.fileLocation = str(os.getcwd()) + '/'
		self.data_file = self.fileLocation + str(datetime.now().replace(microsecond=0))
		print("initialized")
		print(self.data_file)
 async def init_radio(self):
     if not self.neighbourhood[1:]:
         self.srecovery = datetime.now().time()
     self.radio = Radio(RADIO_PORT, self.neighbourhood_watch)
     self.radio_started.set()
     print(
         f"1 Radio Started {self.port}, self id: {self.neighbourhood[0]}, neighbour list: {self.neighbourhood[1:]}"
     )
     await self.radio.start()
 def start_receiving(self, loop_sleep):
     self._receive_loop_sleep = loop_sleep
     if self._radio is None:
         self._radio = Radio(self._is_second_comms)
     self._is_receiving = True
     self._receiving_thread = threading.Thread(target=self.receiving_loop)
     # set to daemon mode so it will be easily killed
     self._receiving_thread.daemon = True
     self._receiving_thread.start()
 def start_sending(self, loop_sleep):
     self._loop_sleep = loop_sleep
     if self._loop_sleep < Radio.MESSAGE_DELAY:
         print("WARNING: Comms loop sending faster than Radio can send")
     if self._radio is None:
         self._radio = Radio(self._is_second_comms)
     self._is_sending = True
     self._sending_thread = threading.Thread(target=self.sending_loop)
     # set to daemon mode so it will be easily killed
     self._sending_thread.daemon = True
     self._sending_thread.start()
 def __init__(self, path, lst, port, id):
     self.path = path
     self.lst = lst
     self.port = port
     self.id = id
     self.radio = Radio(port, print)
     self.pub = Pub(port)
     self.sub = Sub(port)
     self.heartbeat_started = asyncio.Event()
     self.neigh_hood_check_started = asyncio.Event()
     self.sub_started = asyncio.Event()
Example #7
0
def main(radio_idx):
    radio = Radio(int(radio_idx),
                  mic_threshold=MIC_THRESHOLD,
                  input_rate=INPUT_RATE,
                  input_id=INPUT_ID,
                  output_id=OUTPUT_ID)

    radio.connect(server=0)
    radio.start_speaker_stream()

    while True:
        radio.stream_mic_segment_to_server()
Example #8
0
def main():
    stations = [
        Station(
            "https://wdr-1live-live.sslcast.addradio.de/wdr/1live/live/mp3/128/stream.mp3",
            "1Live"),
        Station("http://www.ndr.de/resources/metadaten/audio/m3u/ndr2_hh.m3u",
                "Ndr2"),
        Station(
            "https://swr-dasding-live.sslcast.addradio.de/swr/dasding/live/aac/96/stream.aac",
            "Das Ding")
    ]
    radio_inst = Radio(stations)
    radio_inst.listen_to_station(0)
    menue(radio_inst)
Example #9
0
def user_experiment(set_size=2000):
    if set_size > 0:
        print("+ Extraindo " + str(set_size) + " músicas")
        extractSet(set_size=set_size)
    print('+ Carregando dados no sistema')
    groot = Radio(load_data_songs(), load_data_users())
    print('+ Carregando Dados')
    groot.post_preference_set(
        preference_set=make_set_to_process(
            song_set=groot.get_song_set(),
            dict_set=statisticalOverview(
                songSet=groot.get_song_set(),
                preferenceSet=groot.get_preference_set(),
                DEBUG=False
            ),
            DEBUG=False
        )
    )
    print('+ Treinando a árvore')
    classifier, evaluate_results = plant_the_tree(
        set_to_process=preprocessing_data(
            data_set=groot.get_preference_set(),
            all_features=groot.get_all_features(),
            DEBUG=False
        ),
        features=groot.get_song_features(),
        important_feature=groot.get_important_feature(),
        DEBUG=True,
        ADMIN=False
    )
    groot.post_classifier(
        new_classifier=classifier
    )
    print('+ Obtendo similaridade entre as músicas')
    groot.post_distance_matrix(
        new_distance_matrix=get_song_distance(
            song_set=groot.get_song_set(),
            song_features=groot.get_song_features(),
            classifier_important=groot.get_feature_weight(),
            DEBUG=False
        )
    )
    print('+ Rádio Groot - Iniciando')
    time.sleep(3)
    os.system('clear||cls')
    start_and_end = interface_menu(groot)
    environment(
        groot=groot,
        song_stages=start_and_end
    )
Example #10
0
 def element_wyposazenia(self, typ: str) -> Wyposazenie:
     if typ == 'fotele':
         wyposazenie = Fotele({'typ': 'skorzane'})
     elif typ == 'kierownica':
         wyposazenie = Kierownica({'typ': 'skorzana'})
     elif typ == 'nawigacja':
         wyposazenie = Nawigacja()
     elif typ == 'radio':
         wyposazenie = Radio()
     elif typ == 'tapicerka':
         wyposazenie = Tapicerka({'typ': 'welurowa'})
     else:
         wyposazenie = None
     return wyposazenie
Example #11
0
 def __init__(self):
     self.about_dialog = None
     self.icon = os.path.abspath('./tabletop_radio_.png')
     self.active_icon = None
     self.attention_icon = None
     self.radio = Radio()
     self.notification = Notify.Notification.new('', '', None)
     self.indicator = appindicator.Indicator.new(
         "DoubanRadio-Indicator", self.icon,
         appindicator.IndicatorCategory.APPLICATION_STATUS)
     self.indicator.set_attention_icon(self.icon)
     self.menu = self.get_menu()
     self.indicator.set_menu(self.menu)
     self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
Example #12
0
def admin_experiment(set_size=2000):
    if set_size > 0:
        print("+ Extraindo " + str(set_size) + " músicas")
        extractSet(set_size=set_size)
    print('+ Carregando dados no sistema')
    groot = Radio(load_data_songs(), load_data_users())
    print('+ Processando dados')
    groot.post_preference_set(
        preference_set=make_set_to_process(
            song_set=groot.get_song_set(),
            dict_set=statisticalOverview(
                songSet=groot.get_song_set(),
                preferenceSet=groot.get_preference_set(),
                DEBUG=True
            ),
            DEBUG=True
        )
    )
    print('+ Treinando a árvore')
    classifier, evaluate_results = plant_the_tree(
        set_to_process=preprocessing_data(
            data_set=groot.get_preference_set(),
            all_features=groot.get_all_features(),
            DEBUG=True
        ),
        features=groot.get_song_features(),
        important_feature=groot.get_important_feature(),
        DEBUG=True,
        ADMIN=True
    )
    groot.post_classifier(
        new_classifier=classifier
    )
    print('+ Obtendo similaridade entre as músicas')
    groot.post_distance_matrix(
        new_distance_matrix=get_song_distance(
            song_set=groot.get_song_set(),
            song_features=groot.get_song_features(),
            classifier_important=groot.get_feature_weight(),
            DEBUG=True
        )
    )
    print('+ Iniciando a busca')
    similarity = environment(
        groot=groot,
        song_stages=random_choice(groot=groot),
        DEBUG=True
    )
    print('+ Busca Terminada')
Example #13
0
def main(radio_idx):
    global radio
    radio = Radio(int(radio_idx),
                  mic_threshold=MIC_THRESHOLD,
                  input_rate=INPUT_RATE,
                  input_id=INPUT_ID,
                  output_id=OUTPUT_ID)

    # initialize volume control
    # volume_thread = Thread(target=volume_main)
    # volume_thread.start()
    #
    # channel_selection_thread = Thread(target=channel_selection)
    # channel_selection_thread.start()

    # power button
    powerButton = Button(POWER_PIN, pull_up=False)
    # mute button
    muteButton = Button(MUTE_PIN, pull_up=False)

    powerButton.when_pressed = switchedOn
    powerButton.when_released = switchedOff
    muteButton.when_pressed = unmuteMic
    muteButton.when_released = muteMic
    
    # assign functions for change volume
    volControlB.when_pressed = volcw
    volControlA.when_pressed = volccw

    # assign functions for change channel
    chnlControlB.when_pressed = chnlcw
    chnlControlA.when_pressed = chnlccw

    radio.connect(server=0)
    radio.start_speaker_stream()

    #print("play poweron")
    #radio.play_bilingual_notification(POWERON)

    while True:
        radio.stream_mic_segment_to_server()
        # print("curr", radio.get_current_channel())
        # print("new", channel)
        # print("now", time())
        # print("last", lastUpdateTime)
        if radio.get_current_channel() != channel and time() - lastUpdateTime > 1:
            # print("changing channel...")
            radio.change_channel(channel)
            radio.play_bilingual_notification(CHNLS[channel])
Example #14
0
 def __init__(self):
     """
     Instantiate the AUV object
     """
     self.mc = MotorController()
     # Connection to onboard radio.
     try:
         # Jack Silberman's radio
         #self.radio = Radio('/dev/serial/by-id/usb-FTDI_FT230X_Basic_UART_DN038PQU-if00-port0')
         # Yonder's radio
         self.radio = Radio(
             '/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0')
     except Exception, e:
         print("Radio not found. Exception is: ", e)
         print("Exiting")
         exit(1)
Example #15
0
def main():
    """Runs the gateway"""
    loop = asyncio.get_event_loop()

    router = Router()
    loop.run_until_complete(router.connect_to_message_queue())

    initialize_gpio()
    radio = Radio()

    router.set_send_packet(radio.send_packet)

    poll(loop, radio, router)
    try:
        loop.run_forever()
    finally:
        loop.close()
Example #16
0
    def __init__(self, jid, password, rooms, nick, token, groups):
        # XMPP
        super(Jabbergram, self).__init__(jid, password)
        self.add_event_handler('session_start', self.start)
        self.add_event_handler('groupchat_message', self.muc_message)

        self.muc_rooms = rooms.split()
        self.nick = nick
        self.token = token
        self.xmpp_users = {}
        self.jid = jid
        self.radio = Radio()

        for muc in self.muc_rooms:
            self.add_event_handler("muc::%s::got_online" % muc,
                                   self.muc_online)
            self.add_event_handler("muc::%s::got_offline" % muc,
                                   self.muc_offline)

        # Telegram
        self.groups = groups.split()
        self.bot = telegram.Bot(self.token)
        self.telegram_users = {}

        # put tg connector in a thread
        def start_read_tg_loop():
            t = Thread(target=self.read_tg)
            t.daemon = True
            t.start()

        self.radio.once('http-upload-initialized', start_read_tg_loop)

        # initialize http upload on a thread since its needed to be connected
        # to xmpp
        t = Thread(target=self.init_http)
        t.daemon = True
        t.start()

        log('Please wait a couple of minutes until it\'s correctly '
            'connected.')
Example #17
0
def main():
    pa = Parser()
    naam, url, comm = pa.zendervinden()
    print naam, url, comm
    cursor.hide()
    
    fa = Fabriek()
    co = fa.returnCommunicatorObject(comm)
    
    rd = Radio()
    t = threading.Thread(target=rd.afspelen, args=(naam, url, co))
    t.start()
    
    ## Afspelen stoppen na drukken op één van de EXITKEYS
    kp = Keypress()
    while kp.getexitkeypress() == False:
        time.sleep(0.2)
    
    cursor.show()
    rd.stoppen()
    
    return 0
Example #18
0
    def test_normal(self):
        radio = Radio()
        t1 = SenderTerminal("t1", "00:00:00:00:00:01", "192.168.0.1", radio)
        t1.x = 100
        t1.y = 40
        radio.add_node(t1)

        t2 = ReceiverTerminal("t2", "00:00:00:00:00:02", "192.168.0.2", radio)
        t2.x = 100
        t2.y = -40
        radio.add_node(t2)

        globals.now = 0
        globals.events = sorted(globals.events, key=lambda x: x.time)

        while True:

            if len(globals.events) == 0:
                break

            globals.events = sorted(globals.events, key=lambda x: x.time)
            events_work = copy.copy(globals.events)
            event = globals.events[0]
            globals.now = event.time

            if globals.now > 10:
                break

                break

            for event in events_work:
                if event.time <= globals.now:
                    event.call()
                    globals.events.pop(0)
                else:
                    break

        self.assertEqual(250000, t2.total_received_byte * 8 / globals.now)
Example #19
0
 def generate():
     radio = Radio()
     data = radio.track()
     print(str(data))
     return [str(data) + "\n"]
Example #20
0
import sys
sys.path.append("libs")
import http.server
import urllib.parse, json
from myglobals import MyGlobals
from checkbox import Checkbox
from scatter import Scatter
from radio import Radio
from chart import Chart
from excel import Excel
from table import Table

checkbox = Checkbox()
scatter = Scatter()
radio = Radio()
chart = Chart()
xl = Excel()
table = Table()


class Handler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        jsonResponse = self.rfile.read(int(self.headers['Content-Length']))

        self.send_response(200)
        self.end_headers()

        jsonAsString = jsonResponse.decode("UTF-8")
        results = json.loads(jsonAsString)
    slots = jsonIntent["slots"]

    for i in range(len(slots)):
        if slots[i]['slotName'] == slot_name:
            return slots[i]['value']['value']
    return default_value


def end_session(intent, sentence):
    print('session: ' + intent + ': ' + sentence)
    return EndSession(sentence)


@app.on_intent("PlayInternetRadio")
async def startListening(intent: NluIntent):
    radio_station = get_slot_value_by_slot_name(intent, 'radio_station', None)
    sentence = radio.play_radio_station(radio_station)
    return end_session('Start Listening to Internet Radio', sentence)


@app.on_intent("Stop")
async def stopListening(intent: NluIntent):
    sentence = radio.stop_radio()
    return end_session('Stop Listening to Internet Radio', sentence)


if __name__ == "__main__":
    config = read_configuration_file()
    language = read_language_file(config['setup']['language'])
    radio = Radio({"config": config, "language": language})
    app.run()
Example #22
0
 def __init__(self, blockDevice, baudRate):
     signal.signal(signal.SIGALRM, ncursesSignalHandler)
     self.radio = Radio(blockDevice, baudRate)
Example #23
0
def experiment_cicles(cicles=5, set_size=500):
    weight_df = pd.DataFrame(columns=list([]))
    evaluate_df = pd.DataFrame(columns=list([]))
    similarity_df = pd.DataFrame(columns=list())
    for i in range(cicles):
        print('- * - Iniciando o Ciclo: ', str(i))
        if set_size > 0:
            print("+ Extraindo " + str(set_size) + " músicas")
            extractSet(set_size=set_size)
        print('+ Carregando dados no sistema')
        groot = Radio(load_data_songs(), load_data_users())
        print('+ Processando dados')
        groot.post_preference_set(
            preference_set=make_set_to_process(
                song_set=groot.get_song_set(),
                dict_set=statisticalOverview(
                    songSet=groot.get_song_set(),
                    preferenceSet=groot.get_preference_set(),
                    DEBUG=False
                ),
                DEBUG=False
            )
        )
        print('+ Treinando a árvore')
        classifier, evaluate_results = plant_the_tree(
                set_to_process=preprocessing_data(
                    data_set=groot.get_preference_set(),
                    all_features=groot.get_all_features(),
                    DEBUG=False
                ),
                features=groot.get_song_features(),
                important_feature=groot.get_important_feature(),
                DEBUG=False,
                ADMIN=False
            )
        groot.post_classifier(
            new_classifier=classifier
        )
        print('+ Obtendo similaridade entre as músicas')
        groot.post_distance_matrix(
            new_distance_matrix=get_song_distance(
                song_set=groot.get_song_set(),
                song_features=groot.get_song_features(),
                classifier_important=groot.get_feature_weight(),
                DEBUG=False
            )
        )
        print('+ Iniciando a busca')
        similarity = environment(
            groot=groot,
            song_stages=random_choice(groot=groot),
            DEBUG=False
        )
        print('+ Busca Terminada')
        print('Salvando informações')
        #
        weight_df = pd.concat([weight_df, pd.DataFrame(
            [[i for i in list(groot.get_classifier().feature_importances_)]],
            columns=[i for i in list(groot.get_song_features())],
        )], sort=False)
        #
        evaluate_df = pd.concat([evaluate_df, pd.DataFrame(
            [[i for i in evaluate_results.values()]],
            columns=[x for x in evaluate_results],
        )], sort=False)
        #
        similarity_df = pd.concat([similarity_df,
                  pd.DataFrame(
                      [[i for i in similarity.values()]],
                      columns=[x for x in similarity],
                  )], sort=False)
    plot_feature_importance(weight_df)
    plot_evaluations(evaluate_df)
    plot_similarity(similarity_df['similaridade'].tolist())
    plot_final_state(similarity_df['final_state'].tolist())
    plot_nodes(similarity_df['total_visitas'].tolist())
Example #24
0
    def parse_config_file(self):
        """
            This method parses the configuration file and 
            check that all parameters follow the prerequisites. 
        """
        with open(self._filename) as f:  # Opening configuration file
            tree = json.load(f)  # Parsing json content

            # Closing file
            f.close()

        # First, let's load the list of radios
        for radio in tree['radios']:
            # Load attributes
            long_name = radio['long_name']
            short_name = radio['short_name']
            stream_url = radio['stream_url']
            media_type = radio['type']
            module_name = None
            if 'module_name' in radio:
                module_name = radio['module_name']

            # Check radio attributes type
            if not isinstance(long_name, str):
                raise ConfigurationFileException(
                    "radios.radio.long_name must be a string")

            if not isinstance(short_name, str):
                raise ConfigurationFileException(
                    "radios.radio.short_name must be a string")

            if not isinstance(stream_url, str):
                raise ConfigurationFileException(
                    "radios.radio.stream_url must be a string")

            if not isinstance(media_type, str):
                raise ConfigurationFileException(
                    "radios.radio.type must be a string")

            if module_name is not None and not isinstance(module_name, str):
                raise ConfigurationFileException(
                    "radios.radio.module_name must be a string")

            # Check attribute value and size
            if len(long_name) > 32:
                raise ConfigurationFileException(
                    "radios.radio.long_name must not exceed 32 characters")

            if len(short_name) > 16:
                raise ConfigurationFileException(
                    "radios.radio.short_name must not exceed 16 characters")

            if media_type != "stream" and media_type != "folder":
                raise ConfigurationFileException(
                    "radios.radio.type must be either 'stream' or 'folder'")

            # Register new radio
            r = Radio(long_name, short_name, stream_url, media_type,
                      module_name)
            self._radios.append(r)

        if len(self._radios) <= 0:
            raise ConfigurationFileException("No radio available.")

        # Then, load other mandatory properties
        self._name = tree['general']['name']
        self._halt_message = tree['general']['halt_message']
        self._default_volume = tree['general']['default_volume']
        self._volume_step = tree['general']['volume_step']
        self._volume_timer = tree['display']['volume_timer']
        self._scroll_time_interval = tree['display']['scroll_time_interval']
        self._scroll_time_pause = tree['display']['scroll_time_pause']
        self._serial_device = tree['display']['serial_device']
        self._serial_baud_rate = tree['display']['serial_baud_rate']
        self._radio_info_check_interval = tree['general'][
            'radio_info_check_interval']
        self._full_radio_name_pause = tree['general']['full_radio_name_pause']
        self._save_file_path = tree['general']['save_file_path']

        # Check var type
        if not isinstance(self._name, str):
            raise ConfigurationFileException(
                "general.name parameter must be a string")

        if not isinstance(self._halt_message, str):
            raise ConfigurationFileException(
                "general.halt_message parameter must be a string")

        if not isinstance(self._default_volume, numbers.Number):
            raise ConfigurationFileException(
                "general.default_volume parameter must be a number")

        if not isinstance(self._volume_step, numbers.Number):
            raise ConfigurationFileException(
                "general.volume_step parameter must be a number")

        if not isinstance(self._volume_timer, numbers.Number):
            raise ConfigurationFileException(
                "display.volume_timer parameter must be a number")

        if not isinstance(self._scroll_time_interval, numbers.Number):
            raise ConfigurationFileException(
                "display.scroll_time_interval parameter must be a number")

        if not isinstance(self._scroll_time_pause, numbers.Number):
            raise ConfigurationFileException(
                "display.scroll_time_pause parameter must be a number")

        if not isinstance(self._serial_device, str):
            raise ConfigurationFileException(
                "display.serial_device parameter must be a string")

        if not isinstance(self._serial_baud_rate, numbers.Number):
            raise ConfigurationFileException(
                "display.serial_baud_rate parameter must be a number")

        if not isinstance(self._radio_info_check_interval, numbers.Number):
            raise ConfigurationFileException(
                "general.radio_info_check_interval parameter must be a number")

        if not isinstance(self._full_radio_name_pause, numbers.Number):
            raise ConfigurationFileException(
                "general.full_radio_name_pause parameter must be a number")

        if not isinstance(self._save_file_path, str):
            raise ConfigurationFileException(
                "general.save_file_path parameter must be a string")

        # Check var value and size
        if len(self._name) > 32:
            raise ConfigurationFileException(
                "general.name must not exceed 32 characters")

        if len(self._halt_message) > 32:
            raise ConfigurationFileException(
                "general.halt_message must not exceed 32 characters")

        if self._default_volume > 100 or self._default_volume < 0:
            raise ConfigurationFileException(
                "general.default_volume must be between 0 and 100")

        if self._volume_step > 40 or self._volume_step <= 0:
            raise ConfigurationFileException(
                "general.volume_step must be between 1 and 40")

        if self._volume_timer < 0:
            raise ConfigurationFileException(
                "display.volume_timer must be a positive value (in seconds)")

        if self._scroll_time_interval <= 0:
            raise ConfigurationFileException(
                "display.scroll_time_interval must be a non-null positive value (in seconds)"
            )

        if self._scroll_time_pause < 0:
            raise ConfigurationFileException(
                "display.scroll_time_pause must be a positive value (in seconds)"
            )

        if self._serial_baud_rate <= 0:
            raise ConfigurationFileException(
                "display.serial_baud_rate must be a non-null positive value")

        if self._radio_info_check_interval <= 0:
            raise ConfigurationFileException(
                "general.radio_info_check_interval must be a non-null positive value (in seconds)"
            )

        if self._full_radio_name_pause < 0:
            raise ConfigurationFileException(
                "general.full_radio_name_pause must be a positive value (in seconds)"
            )

        # Now, let's try to load cached settings if exist
        self.load_cached_settings(self._save_file_path)
 def start(self, station_id, station_from):
     log("Yandex.Radio::start")
     self.radio = Radio(client, station_id, station_from)
     self.radio.start_radio(self.__on_start)
Example #26
0
from radio import Channel, Radio

# The FM broadcast band, used for FM broadcast radio by radio stations,
# differs between different parts of the world.
# In Europe, Australia[1] and Africa - from 87.5 to 108 megahertz (MHz)

# A Channel has a frequency (between 87.5 and 108), a name, and a playlist
ch1 = Channel("VGOLOS", 107.2, ["Susy", "Without You", "That's Enough"])
assert(ch1.getFrequency() == 107.2)
assert(str(ch1) == \
"""Channel VGOLOS on 107.2, playlist: ['Susy', 'Without You', "That's Enough"]""")
ch2 = Channel("Oles FM", 91.1, ["911"])
assert(str(ch2) == "Channel Oles FM on 91.1, playlist: ['911']")
assert(ch2.playlist == ['911'])
assert(ch2 == Channel("Oles FM", 91.1, ["911"]))
assert(ch2 != ch1)
assert(ch2 != "Oles FM")
s = set()
assert(ch2 not in s)
s.add(ch2)
assert(Channel("Oles FM", 91.1, ["911"]) in s)
assert(ch1 not in s)
# A Radio (FM Radio) can be tuned to receive channels
# based on some different frequencies
channels = { 107.2 : ch1, 91.1 : ch2 }
radio = Radio(channels, 107.25)
assert(radio.getCurrentFrequency() == 107.25)
# A Radio receives a channel if it’s tuned within 0.05 Hz of that channel’s
# frequency. You’re guaranteed that channel frequencies will always be
# at least 0.05 Hz apart.
assert(radio.getCurrentChannel() == ch1)
Example #27
0
from radio import Radio

objeto_radio = Radio(input("Ingrese una marca: "))

desea_continuar = True

while desea_continuar:

    print("Marca: ", objeto_radio.marca)
    print("Encendido: ", objeto_radio.encendido)
    print("Volumen: ", objeto_radio.volumen)
    print("Fm: ", objeto_radio.en_fm)
    print("Emisora AM: ", objeto_radio.emisora_am)
    print("Emisora FM: ", objeto_radio.emisora_fm)

    if objeto_radio.encendido == False:
        opcion = int(input(("1. Encender: ")))
        if opcion == 1:
            objeto_radio.encender()
    if objeto_radio.encendido == True:
        opcion2 = int(
            input(("""
	1. Apagar 
	2. Subir Volumen
	3. Bajar Volumen
	4. Cambiar Frecuencia
	5. Subir Emisora
	6. Bajar Emisora
""")))
        if opcion2 == 1:
            objeto_radio.apagar()
Example #28
0
#! /usr/bin/env python2

from radio import Radio
from databaseController import DatabaseController
from RaspberryAudioController import RaspberryAudioController

login = '******'
password = '******'
ip = '127.0.0.1'
database = 'radio'

db = DatabaseController(login, password, ip, database)
db.connect()
stations = db.getStationsList()

rd = Radio(stations)
audioController = RaspberryAudioController(30)
paused = True
mapping = db.getGesturesDict()
db.insertDescribedAction('volume_up', str(audioController.getVolume()))

while True:
    print(
        "1. volume up\n2. volume down\n3. station up\n4. station down\n5. play\pause\n"
    )
    action = int(input())
    if action == mapping['volume_up']:
        audioController.volumeUp()
        db.insertDescribedAction('volume_up', str(audioController.getVolume()))
    if action == mapping['volume_down']:
        audioController.volumeDown()
from math import floor
from random import random
from time import sleep

from yandex_music import Client

from radio import Radio

# API instance
client = Client(token="YOUR_TOKEN_HERE")

# Get random station
_stations = client.rotor_stations_list()
_station_random_index = floor(len(_stations) * random())
_station = _stations[_station_random_index].station
_station_id = f'{_station.id.type}:{_station.id.tag}'
_station_from = _station.id_for_from

# Radio instance
radio = Radio(client)

# start radio and get first track
first_track = radio.start_radio(_station_id, _station_from)
print("[Radio] First track is:", first_track)

# get new track every 5 sec
while True:
    sleep(5)
    next_track = radio.play_next()
    print("[Radio] Next track is:", next_track)
Example #30
0
    args = parser.parse_args()

    if args.custom_coords is not None:
        lat, lon = args.custom_coords.strip().split(',')
        utils.REF_LAT, utils.REF_LON = float(lat), float(lon)
    else:
        utils.set_loc_ip()
    print(f'Using reference coordinates of: {utils.REF_LAT}, {utils.REF_LON}')

    msg_que = Queue()
    if args.input is not None:
        print(f"Using MockRadio with {args.input}")
        radio = MockRadio(msg_que, args.input, args.repeat, args.delay,
                          args.delay)
    else:
        print('Setting up radio')
        radio = Radio(msg_que)
        print('Done')

    if args.gui:
        run_gui(radio, args.debug)
    else:
        while True:
            msgs = radio.get_all_queue()
            for m in msgs:
                if m.valid:
                    print(m)
                if args.output is not None and (m.valid
                                                or args.output_invalid):
                    args.output.write(f'{round(time.time())} {m.bin_msg}\n')