75 lines
2.6 KiB
Python
75 lines
2.6 KiB
Python
from LocalParticipant import LocalParticipant
|
|
from Messages.ParticipantMsg import ParticipantMsg
|
|
from Messages.NetworkIdMsg import NetworkIdMsg
|
|
from Things.TemperatureSensor import TemperatureSensor
|
|
from Thing import Thing
|
|
|
|
import socket
|
|
import threading
|
|
|
|
class SiteServer(LocalParticipant):
|
|
"""! A site server is a participant which provides a shared simulated environment
|
|
"""
|
|
|
|
name = "Site Server"
|
|
|
|
def __init__(self, port=7681, remote=False, udp_socket = None):
|
|
"""! Create a new site server
|
|
@param port The UDP port on which communication is received
|
|
"""
|
|
self.ip_address = "0.0.0.0"
|
|
self.port = port
|
|
self.publishInterval = 0
|
|
self.others = []
|
|
self.network_id = 0
|
|
self.buffer = bytearray(256)
|
|
self.thing_msg_constructors = {}
|
|
|
|
if remote == False:
|
|
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
self.udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
self.udp_socket.bind(("0.0.0.0", port))
|
|
self.AddParticipant(self.ip_address, self.port)
|
|
|
|
self.thread = threading.Thread(target = self.Receiver)
|
|
self.thread.daemon = True
|
|
self.thread.start()
|
|
else:
|
|
self.udp_socket = udp_socket
|
|
|
|
self.Register(TemperatureSensor, Thing.Type.TemperatureSensor)
|
|
|
|
def AddParticipant(self, ip_address, port):
|
|
# print(f'{self.name} Add site participant {ip_address} {port}')
|
|
remote_participant = SiteServer(ip_address, port, remote=True, udp_socket=self.udp_socket)
|
|
remote_participant.network_id = len(self.others)
|
|
self.others.append(remote_participant)
|
|
return remote_participant
|
|
|
|
def ProcessParticipantMsg(self, sender, msg):
|
|
if msg.network_id == 0:
|
|
print(f'{self.name} received New Client -> {sender.network_id}')
|
|
sender.Send(NetworkIdMsg(sender.network_id))
|
|
# else:
|
|
# print(f'{self.name} Client')
|
|
|
|
def ProcessNetworkId(self, msg):
|
|
pass
|
|
|
|
# Register function
|
|
def Register(self, ThingClass, thing_type):
|
|
self.thing_msg_constructors[thing_type] = lambda network_id, thing_id: ThingClass(network_id, thing_id)
|
|
|
|
def Process(self, msg):
|
|
if isinstance(ThingMsg):
|
|
self.ProcessThingMsg(msg)
|
|
else:
|
|
super().Process(msg)
|
|
|
|
def ProcessThingMsg(self, msg):
|
|
if msg.thingType in self.thing_msg_constructors:
|
|
self.thing_msg_constructors[msg.thing_type](msg.network_id, msg.thing_id)
|
|
else:
|
|
Thing(msg.network_id, msg.thing_id, msg.thing_type)
|
|
|