added a behavior when there are multiple pi that are undefined or master

This commit is contained in:
study-faraphel 2025-02-03 10:45:49 +01:00
parent 29ad1c49f4
commit cad8221887
2 changed files with 30 additions and 6 deletions

View file

@ -28,7 +28,7 @@ class MasterRole(base.BaseActiveRole):
# prepare the audio file that will be streamed
# TODO(Faraphel): use another audio source
self.audio = pydub.AudioSegment.from_file("./assets/Queen - Another One Bites the Dust.mp3")
self.audio = pydub.AudioSegment.from_file("./assets/Roundabout 2008 Remaster.mp3")
self.play_time = datetime.now()
# calculate the number of bytes per milliseconds in the audio
@ -45,9 +45,18 @@ class MasterRole(base.BaseActiveRole):
def handle(self) -> None:
# TODO(Faraphel): communicate with chrony to add peers and enable server mode ?
# TODO(Faraphel): share the secret key generated with the other *allowed* peers ! How to select them ? A file ?
# TODO(Faraphel): check if another server is emitting sound in the network. Return to undefined if yes
# get all the master peers in the network
master_peers = {
address: peer
for (address, peer) in self.manager.peer.peers.items()
if peer.master
}
# if there is more than one master, return to undefined
if len(master_peers) > 1:
# declare ourselves as the master of the network
from source.behaviors.roles import UndefinedRole
self.manager.role.current = UndefinedRole(self.manager)
return
# get the current chunk (loop indefinitely)
chunk = self.chunks[self.chunk_count % len(self.chunks)]

View file

@ -56,5 +56,20 @@ class UndefinedRole(base.BaseRole):
# SCENARIO 3 - network with no master
# TODO(Faraphel): elect the machine with the lowest ping in the network
raise NotImplementedError("Not implemented: elect the machine with the lowest ping as a master.")
# get the peer with the highest public key
master_address, master_peer = max(
self.manager.peer.peers.items(),
key=lambda peer: peer[1].public_key
)
# if we are the master
if self.manager.communication.is_address_local(master_address):
# declare ourselves as the master of the network
from source.behaviors.roles import MasterRole
self.manager.role.current = MasterRole(self.manager)
# else become a slave
else:
# declare ourselves as a slave of the network
from source.behaviors.roles import SlaveRole
self.manager.role.current = SlaveRole(self.manager, master_address)