added a basic behavior to switch to master mode if we are the only machine in the network

This commit is contained in:
study-faraphel 2025-01-04 00:56:59 +01:00
parent 8038b8e40c
commit 142d0f6db8
3 changed files with 47 additions and 4 deletions

View file

@ -0,0 +1,15 @@
import time
from source.behaviors.roles import base
class MasterRole(base.BaseRole):
"""
Role used when the machine is declared as the master.
It will be the machine responsible for emitting data that the others peers should play together.
"""
def handle(self):
print("I am now the master !")
time.sleep(1)

View file

@ -1,16 +1,42 @@
import time
from datetime import datetime, timedelta
from . import base
from . import base, MasterRole
from source import packets
from ...managers import Manager
from ...utils.crypto.type import CipherType
class UndefinedRole(base.BaseRole):
"""
Role used when the peer have no defined state, for example just after starting.
It looks for the current network peers state and try to integrate itself inside.
"""
def __init__(self, manager: "Manager"):
super().__init__(manager)
self.old_peers: list[packets.PeerPacket] = []
self.previous_discovery: datetime = datetime.now()
def handle(self):
# discover new peers
packet = packets.DiscoveryPacket()
self.manager.communication.broadcast(packet, CipherType.PLAIN)
# wait
time.sleep(1)
# wait for new messages
time.sleep(1)
# check if a new peer have been registered
if self.manager.peers != self.old_peers:
self.old_peers = self.manager.peers.copy()
self.previous_discovery = datetime.now()
# check if no more peers have been found in the previous seconds
if datetime.now() - self.previous_discovery >= timedelta(seconds=5):
# check if no peer have been found except ourselves.
# TODO(Faraphel): need a better check than just that
if len(self.manager.peers) == 1:
# if we are the only machine, become a master
self.manager.role.current = MasterRole(self.manager)

View file

@ -1,2 +1,4 @@
from . import base
from .UndefinedRole import UndefinedRole
from .MasterRole import MasterRole
from .UndefinedRole import UndefinedRole