added a basic behavior to switch to master mode if we are the only machine in the network
This commit is contained in:
parent
8038b8e40c
commit
142d0f6db8
3 changed files with 47 additions and 4 deletions
15
source/behaviors/roles/MasterRole.py
Normal file
15
source/behaviors/roles/MasterRole.py
Normal 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)
|
|
@ -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)
|
||||
|
|
|
@ -1,2 +1,4 @@
|
|||
from . import base
|
||||
from .UndefinedRole import UndefinedRole
|
||||
|
||||
from .MasterRole import MasterRole
|
||||
from .UndefinedRole import UndefinedRole
|
Loading…
Reference in a new issue