import socket   
from datetime import datetime
import time as sleep

#Generating read request
def generate_dlms_cosem_read_request(obis_code):
    header = b'\x10'  
    read_request_code = b'\xC0'  
    numbers = obis_code.split('.')
    hexo = [hex(int(nus)) for nus in numbers]
    obis = bytes.fromhex(''.join([num[2:].zfill(2) for num in hexo]))
    length = len(obis) + 3  

    # Construct the read request message
    read_request_message = header + bytes([length]) + read_request_code + obis
    formatted_message = ' '.join(['\\x{:02X}'.format(byte) for byte in read_request_message])
    return formatted_message

# OBIS codes for data and time)
obis_code = '1.0.31.7.0.255'  
obis_code_time = '0.0.1.0.0.255'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Set IP address and port for Device 
ip_address_A = '127.0.0.1'  
port_A = 65404  

# Bind and listen for incoming connections
sock.bind((ip_address_A, port_A))
sock.listen(1)
print("Listening...")
conn, addr = sock.accept()
print("Connected to ", addr)

# Send the read request data
read_data = generate_dlms_cosem_read_request(obis_code)
conn.sendall(read_data.encode())
print("DATA REQUEST..")
print("TX", read_data)
while True:
    data = conn.recv(1024).decode()
    print("RX: ",data)
    prijataData = data
    if ('\\x01 \\x00 \\x1f \\x07 \\x00 \\xff' in prijataData):
        namerenaData = prijataData[45:] 
        cleaned_data = namerenaData.replace("\\x","").replace(" ","")
        data_from_device = int(cleaned_data, 16)
        print("Received data: ", data_from_device)

         # Request for the device's current time
        read_time = generate_dlms_cosem_read_request(obis_code_time)
        conn.sendall(read_time.encode())
        print("TIME REQUEST..")
        print("TX", read_time)
    elif('\\x00 \\x00 \\x01 \\x00 \\x00 \\xff' in prijataData):
        namerenaCas = prijataData[45:]
        cleaned_time = namerenaCas.replace("\\x","").replace(" ","")
        timestamp = int(cleaned_time, 16)
        time = datetime.fromtimestamp(timestamp)
        print("Current time: ", time)
        print("\n")
        sleep.sleep(15)

        # Request for data again after a delay
        read_data = generate_dlms_cosem_read_request(obis_code)
        conn.sendall(read_data.encode())
        print("DATA REQUEST..")
        print("TX", read_data)
    else:
        print("Wrong OBIS code")


# Uzavření socketu
conn.close()
sock.close()