simplify listener

This commit is contained in:
Maxime Bloch 2020-01-22 19:35:00 +01:00
parent f823f9c3ed
commit 65c71b8ed0
No known key found for this signature in database
GPG key ID: CE32A7D95B7D6418

View file

@ -1,43 +1,9 @@
import datetime import datetime
import socket import socket
import sys import sys
from typing import Optional
from utils import mac_address, broadcast_address from utils import mac_address, broadcast_address
class Frame:
def __init__(self,
destination: bytes,
protocol: bytes,
message: str,
source: bytes = mac_address):
self.destination: bytes = destination
self.source: bytes = source
self.protocol: bytes = protocol
self.message: str = message
def decode_packet(packet_bytes: bytes) -> Optional[Frame]:
protocol: bytes = packet_bytes[12:14]
if protocol != b"\x60\x00":
return None
try:
destination = packet_bytes[0:6]
source = packet_bytes[6:12]
message = packet_bytes[14:].decode("utf-8").rstrip("\x00")
return Frame(destination=destination,
source=source,
protocol=protocol,
message=message)
except:
# print("[Error] Could not decode message.")
return None
if __name__ == "__main__": if __name__ == "__main__":
print("Starting listener...") print("Starting listener...")
@ -48,15 +14,17 @@ if __name__ == "__main__":
while True: while True:
byte_string, addr = connection.recvfrom(65536) byte_string, addr = connection.recvfrom(65536)
frame = decode_packet(byte_string) destination = byte_string[0:6]
if byte_string[12:14] == b"\x60\x00" \
and (destination == mac_address or destination == broadcast_address):
if frame is not None \ source = byte_string[6:12]
and (frame.destination == mac_address or frame.destination == broadcast_address): message = byte_string[14:].decode("utf-8").rstrip("\x00")
dt_string = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S") dt_string = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
print("----") print("----")
print("Revcd from {} to {} @{}".format(frame.source, frame.destination, dt_string)) print("Revcd from {} to {} @{}".format(source, destination, dt_string))
if frame.message == "ZeusWPI is de max!": if message == "ZeusWPI is de max!":
print("Congratulations, packet received correctly!") print("Congratulations, packet received correctly!")
else: else:
print("Wrong message, please check that you are sending \"ZeusWPI is de max!\"") print("Wrong message, please check that you are sending \"ZeusWPI is de max!\"")