radio_engine.py

import asyncio

import serial

import subprocess

import websockets

import os

import time

import subprocess

subprocess.run([

"mpg123",

"-q",

"/home/fi/kb405a/startup.mp3"

])

time.sleep(1)

REMOTE_FILE = "/home/fi/kb405a/remote_station.txt"

SERIAL_PORT = "/dev/ttyACM0"

BAUD_RATE = 115200

C_MIN = 10.0

C_MAX = 329.0

stations = [

("Apfelsaft","https://stream.laut.fm/apfelsaft"),

("Barok","https://streams.greenhost.nl:8006/barok"),

("BE ONE Hits Oostende","https://live.radiostudio.be/beone" ),

("Blues Drenthe FM","https://d3vbm02trh7zmp.cloudfront.net/icecast/rtvdrenthe/BluesradioDrenthe" ),

("Classic Gold","https://cast1.torontocast.com:3365/stream" ),

("Citysound Radio","https://auds1.intacs.com/citysoundfm" ),

("Deltamusic","https://stream.laut.fm/deltamusic" ),

("De tijdloze","https://icecast.vrtcdn.be/stubru_tijdloze-high.mp3"),

("Discoweek","https://stream.laut.fm/discoweek"),

("Filmmuziek", "https://streams.greenhost.nl:8006/film" ),

("FM Goud Limburg","https://stream.fmgoud.be/fm-goud-noord-limburg"),

("Flash FM","https://flashfm2.ice.infomaniak.ch/flashfm2-128.mp3"),

("Freez FM","https://stream.freezfm.nl/freezfm"),

("Funky Channel Brugge","https://cast3.asurahosting.com/proxy/breakou1/stream"),

("Galaxy Greece","https://galaxy.live24.gr/galaxy9292"),

("Halloween Radio Movies", "https://node-17.zeno.fm/mash62rv1bruv"),

("Jazz One","https://streaming.broadcast.radio/onejazz" ),

("Joe Gold","https://audio-streaming.joe.be/joe-gold.aac"),

("JOE FM","https://streams.radio.dpgmedia.cloud/redirect/joe_fm/mp3"),

("Jukebox","https://jukebox.stream.laut.fm/jukebox"),

("Kiev","https://listen6.myradio24.com:9000/4171"),

("Klara","https://icecast.vrtcdn.be/klara-high.mp3"),

("Klara Continuo","https://icecast.vrtcdn.be/klaracontinuo-high.mp3" ),

("Komilfoo FM","https://eu1.reliastream.com/proxy/marc?mp=/stream"),

("Kustradio","https://www.clubfmserver.be:8000/kustradio.mp3"),

("Kortrijk","https://s19.myradiostream.com/18068/listen.mp3"),

("Megamix","https://web.radio.antennevorarlberg.at/mm-80er90ermegamix"),

("M-FM Zottegem","https://2424.cloudrad.io:8248/live"),

("MNM","https://icecast.vrtcdn.be/mnm-high.mp3"),

("MNM Hits","https://icecast.vrtcdn.be/mnm_hits-high.mp3"),

("Moonlight","https://server-67.stream-server.nl:8780/stream"),

("MooyZo Pajotteland","https://play.mooyzo.be/mooyzo.mp3"),

("Night Lounge","https://stream.laut.fm/radiomusicnetwork" ),

("NPO 1","https://icecast.omroep.nl/radio1-bb-mp3"),

("NPO 2","https://icecast.omroep.nl/radio2-bb-mp3"),

("NPO 3FM","https://icecast.omroep.nl/3fm-bb-mp3"),

("NRJ Belgie","https://playerservices.streamtheworld.com/api/livestream-redirect/NRJBELGIE.mp3"),

("Ocean FM","https://playerservices.streamtheworld.com/api/livestream-redirect/OCEAN_FM_SLIGO.mp3"),

("Oslo InterFM","https://stream.interfm.no/interfm_hq"),

("Oudepiratenhits","https://server-67.stream-server.nl:8910/stream"),

("Radio 1 BE", "https://icecast.vrtcdn.be/radio1-high.mp3"),

("Radio 2 BE", "https://icecast.vrtcdn.be/ra2wvl-high.mp3"),

("Radio 5","https://icecast.omroep.nl/radio5-bb-mp3"),

("Radio 538","https://playerservices.streamtheworld.com/api/livestream-redirect/RADIO538.mp3"),

("Radio Contact","https://radiocontact.ice.infomaniak.ch/radiocontact-mp3-192.mp3"),

("Radio Kompas Diksmuide","https://mediaserv33.live-streams.nl:8052"),

("Radio Melodie Schlagers","https://radiomelodie.schlagerparadies.de/radiomelodie"),

("Radio Meteor","https://streams.movemedia.be/meteor"),

("Radio Mi Amigo","https://stan319.radioca.st/;"),

("Radio Ninove","https://radioninove.streamer.radioninove.be/"),

("Radio Nostalgie","https://playerservices.streamtheworld.com/api/livestream-redirect/NOSTALGIEWHATAFEELING.mp3"),

("Radio Nostalgie Plus","https://playerservices.streamtheworld.com/api/livestream-redirect/NOSTALGIEPLUS.mp3"),

("Radio Oostende","https://stream.laut.fm/ostende"),

("Radio Pros Aalst","https://live2.radiostudio.be/pros"),

("Retro Hits","https://stream.zeno.fm/v8b6uyvf9s8uv"),

("Silver Radio","https://stream.silverstar-radio.de/listen/silverstart_radio/radio.mp3"),

("Stadsradio Vlaanderen","https://randstad.wirelessbelgie.be:8330/;stream.mp3"),

("Starradio Oud-Turnhout","https://streams.movemedia.eu:8000/stereofm"),

("Stockholm","https://81.225.54.184:8000/live"),

("Studio Brussel","https://icecast.vrtcdn.be/stubru-high.mp3"),

("Sunshine FM","https://stream.sunshine-live.de/live/mp3-192/"),

("The Beat","https://live-nors.sharp-stream.com/nors19.mp3"),

("Topbam","https://playerservices.streamtheworld.com/api/livestream-redirect/TOPBAM.mp3"),

("Top Radio","https://str.topradio.be/topradio.mp3"),

("Top Zen","https://playerservices.streamtheworld.com/api/livestream-redirect/TOPZEN.mp3"),

("VBRO","https://stream.vbro.be:9100/vbro"),

("WRadio Roeselare","https://stream.wradio.es:9000/;stream/1"),

("Q Foute Radio", "https://icecast-qmusicbe-cdp.triple-it.nl/q-foute-radio.mp3" ),

("Qmusic","https://icecast-qmusicbe-cdp.triple-it.nl/qmusic.mp3"),

("QMusic Allstars","https://icecast-qmusicbe-cdp.triple-it.nl/q-allstars.mp3"),

("Radio Melinda","https://stream.decibelhuis.be/1"),

("Radio Noordzee", "https://stream.noordzee105.be/noordzee-192"),

("Noordzee Gold","https://stream.noordzee105.be/gold"),

];

volume = 85

remote_override = False

remote_cap = None

LOCAL_THRESHOLD = 8.0

clients = set()

current_station = -1

player = None

async def stuur_remote_station(index):

bericht = f"REMOTE:{index}"

print("VERZEND:", bericht)

if clients:

await asyncio.gather(

*[client.send(bericht) for client in clients]

)

remote_override = False

remote_until = 0

def check_remote_station():

print("BESTAAT:",

os.path.exists(REMOTE_FILE))

if not os.path.exists(REMOTE_FILE):

return

global current_station, remote_override

remote_override = True

try:

with open(REMOTE_FILE, "r") as f:

waarde = f.read().strip()

print("WAARDE =", waarde)

try:

station = int(waarde)

except:

station = -1

for i, (naam, url) in enumerate(stations):

if naam.lower() == waarde.lower():

station = i

break

print("REMOTE =", station)

if station >= 0 and station != current_station:

current_station = station

print("START=", station)

for client in clients:

asyncio.get_running_loop().create_task(

client.send(f"REMOTE:{station}")

)

print("VERSTUURD REMOTE:", station)

os.remove(REMOTE_FILE)

except Exception as e:

print("REMOTE fout:", e)

def pf_to_station(cap):

verhouding = (cap - C_MIN) / (C_MAX - C_MIN)

verhouding = max(0.0, min(1.0, verhouding))

return round(verhouding * (len(stations)-1))

async def websocket_handler(ws):

global current_station

global remote_override

global remote_cap

print("NIEUWE CONNECTIE")

clients.add(ws)

try:

async for message in ws:

print("ONTVANGEN:", message)

if message.startswith("SET:"):

station = int(message.split(":")[1])

current_station = station

remote_override = True

remote_cap = None

for client in clients:

await client.send(f"REMOTE:{station}")

print("REMOTE STATION =", station)

elif message.startswith("VOL:"):

volume = int(message.split(":")[1])

subprocess.run([

"amixer",

"-D",

"hw:3",

"sset",

"Speaker",

f"{volume}%"

])

print("VOLUME =", volume)

finally:

clients.remove(ws)

print("CLIENT WEG:", len(clients))

async def serial_task():

global current_station, remote_override, remote_cap

remote_override = False

ser = serial.Serial(SERIAL_PORT, BAUD_RATE)

while True:

try:

check_remote_station()

line = ser.readline().decode().strip()

cap = float(line)

station = pf_to_station(cap)

if remote_override:

if remote_cap is None:

remote_cap = cap

print("REMOTE START CAP =", remote_cap)

verschil = abs(cap - remote_cap)

if verschil < LOCAL_THRESHOLD:

print(

f"REMOTE OVERRIDE ACTIEF "

f"(?={verschil:.2f} pF)"

)

await asyncio.sleep(0.03)

continue

print(

f"TERUG NAAR LOCAL "

f"(?={verschil:.2f} pF)"

)

remote_override = False

remote_cap = None

print("CAP =", cap)

print("STATION =", station)

print("CLIENTS =", len(clients))

if station != current_station:

current_station = station

for client in clients:

asyncio.get_running_loop().create_task(

client.send(f"REMOTE:{station}")

)

await stuur_remote_station(station)

except Exception as e:

print(e)

await asyncio.sleep(0.03)

async def main():

await websockets.serve(

websocket_handler,

"0.0.0.0",

8765

)

await serial_task()

if __name__ == "__main__":

asyncio.run(main())