import socket
import struct
from datetime import datetime  
import random

# Generating data
def generate_dlms_cosem_message(obis_code, int_value):
    header = b'\x10'
    numbers = obis_code.split('.')
    hexo = [hex(int(nus)) for nus in numbers]
    obis = bytes.fromhex(''.join([num[2:].zfill(2) for num in hexo]))

    int_bytes = int_value.to_bytes(4, byteorder='big')  # Convert int_value to 4-byte big-endian bytes

    length = len(obis) + len(int_bytes) + 4
    message = header + bytes([length]) + obis + bytes([len(int_bytes)]) + int_bytes
    return format_bytes_to_hex(message)

# Generating current time
def generate_dlms_cosem_time(obis_code, time_value):
    header = b'\x10'
    numbers = obis_code.split('.')
    hexo = [hex(int(nus)) for nus in numbers]
    obis = bytes.fromhex(''.join([num[2:].zfill(2) for num in hexo]))

    # Convert time to Unix timestamp
    timestamp = int(time_value.timestamp())
    
    # Convert Unix timestamp to byte string
    time_bytes = timestamp.to_bytes(4, byteorder='big')

    length = len(obis) + len(time_bytes) + 4
    message = header + bytes([length]) + obis + bytes([len(time_bytes)]) + time_bytes
    return format_bytes_to_hex(message)

# Formatting output
def format_bytes_to_hex(data):
    return ' '.join([f'\\x{byte:02x}' if byte != 0 else '\\x00' for byte in data])

# Create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Set the IP address and port of Device B
ip_address_B = '127.0.0.1'  
port_B = 65406  

# Connect to Device 
sock.connect((ip_address_B, port_B))
print("Connection to the server")
while True:
    data = sock.recv(1024).decode()
    print(f"RX: {data}")
    prijataData = data
    if (prijataData[15:] == '\\x01 \\x00 \\x1F \\x07 \\x00 \\xFF'):
        print("DATA request")
        obis_code_data = '1.0.31.7.0.255'
        int_value = random.randint(1,20000)
        dlms_cosem_message_data = generate_dlms_cosem_message(obis_code_data, int_value)
        print("TX",dlms_cosem_message_data)
        # Send the message to Device B via socket
        sock.sendall(dlms_cosem_message_data.encode())

    elif(prijataData[15:] == '\\x00 \\x00 \\x01 \\x00 \\x00 \\xFF'):
        print("TIME request")
        obis_code_cas = '0.0.1.0.0.255'
        current_time = datetime.now()
        dlms_cosem_message_cas = generate_dlms_cosem_time(obis_code_cas, current_time)
        print("TX",dlms_cosem_message_cas)
        # Send the message to Device B via socket
        sock.sendall(dlms_cosem_message_cas.encode())
        print("\n")
    else:
        print("Wrong OBIS code")
    
    

# Close the socket
sock.close()







