Help request to install Two Way RTI Proxy Script

I’m a newbie around here so I apologise if this post is in the wrong place. I posted in uncategorised but alas in spite of many views no responses were forthcoming :cry:
I am trying to install and get working the script below but have been unable to get past the first line error. I am assuming the script is syntactically correct and that I am installing it incorrectly.
Can someone tell me if this script should run in a normal python environment or does it need home assistant appdaemon?

Any pointers will be much appreciated.

import homeassistant.remote as remote
import socket
api = remote.API('https://ADDRESS.duckdns.org', 'PASSWORD', 443) # ('HA Address', 'HA Password', HA Port)
print(remote.validate_api(api))
HOST = ""
PORT = 4999 # Listening Port

# Retrieve input from RTI
# RTI 2-Way driver comand srting syntax examples:
#   ,media_player*select_source*entity_id*media_player.living_room_tv*source*Netflix^
#   ,vacuum*turn_on*entity_id*vacuum.roomba**^
def msg_to_hass(strCommand):
    domain = strCommand.split("*")[0] # HA Domain
    service = strCommand.split("*")[1] # HA Service
    field = strCommand.split("*")[2] # HA Field1
    device = strCommand.split("*")[3] # HA Field1 Value
    field2 = strCommand.split("*")[4] # HA Field2
    device2 = strCommand.split("*")[5] # HA Field2 Value
    data = {}   # initialize dictionary
    data[field] = device # insert field 1 and value into dictionary
    data[field2] = device2 # insert field 2 and value into dictionary
    new_data={k:data[k] for k in data if data[k]} # Remove blank entries from data dictionary and save as new_data
    print(domain, service, new_data) # print domain, service, and data to send to HA
    remote.call_service(api, domain, service, new_data) # send command to HA
    state = remote.get_state(api, device) # request device state from HA
    print(state) # Print state of HA Device
	
def create_listen_socket(host, port):
    """ Setup the sockets our server will receive connection
    requests on """
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(100)
    return sock

def recv_msg(sock):
    """ Wait for data to arrive on the socket, then parse into
    messages using b'\0' as message delimiter """
    data = bytearray()
    msg = ''
    # Repeatedly read 4096 bytes off the socket, storing the bytes
    # in data until we see a delimiter
    while not msg:
        recvd = sock.recv(4096)
        if not recvd:
            # Socket has been closed prematurely
            raise ConnectionError()
        data = data + recvd
        #if b'\0' in recvd:
        if b'^' in recvd:   # ^ is the last character in the message. Strip the starting comma.
            #msg = data.rstrip(b'\0')
            msg = data
    msg = msg.decode('utf-8')
    msg = msg.split(",")[-1]
    return msg.rstrip("^")

def prep_msg(msg):
    """ Prepare a string to be sent as a message """
    msg += '\0'
    return msg.encode('utf-8')

def send_msg(sock, msg):
    """ Send a string over a socket, preparing it first """
    data = prep_msg(msg)
    sock.sendall(data)




def handle_client(sock, addr):
    """ Receive data from the client via sock and echo it back """
    try:
        msg = recv_msg(sock) # Blocks until received complete message
        print('{}: {}'.format(addr, msg))
        #send_msg(sock, msg) # Blocks until sent
        msg_to_hass(msg)
    except (ConnectionError, BrokenPipeError):
        print('Socket error')
    finally:
        handle_client(client_sock, addr)        # loop back to recv_msg
    #     print('Closed connection to {}'.format(addr))
    #     sock.close()


if __name__ == '__main__':
    listen_sock = create_listen_socket(HOST, PORT)
    addr = listen_sock.getsockname()
    print('Listening on {}'.format(addr))

    while True:
        client_sock, addr = listen_sock.accept()
        print('Connection from {}'.format(addr))
        handle_client(client_sock, addr)

It maybe me but I don’t think homeassistant.remote is a valid class.

In order to integrate external scripts into HA, you have 4 options (maybe someone else has another one).

  1. Use pyscript as per these docs
    Reference — hacs-pyscript 1.5.0 documentation

  2. Use the rest api per these docs
    REST API | Home Assistant Developer Docs

  3. Use the websocket api per these docs.
    WebSocket API | Home Assistant Developer Docs

  4. Use MQTT to create and manage sensor per these docs
    MQTT Sensor - Home Assistant

Depending on where and how you need to run this script and what functions you need to be able to call will depend on the best choice.

Pyscript has to be stored in config/pyscript folder in your HA install, so if you are running this on another machine then not suitable.

Rest api is simple to use from anywhere outside HA install and only needs the request library (or any other http library) to call functions. You will need to create a long lived access token in HA to supply in your script but very simple to do. However, functions are a little limited compared to websocket api.

Websocket api is the most functional and what the fronted uses to get info and control HA. However, depending on your python experience, websockets are more complex to manage and maybe overkill if rest api meets your need.

MQTT is a good approach and designed within HA to be able to create and update entities. You cannot directly run services though so depends on your need in HA.

Hope that helps. Post back when you have investigated the above and need any more help.

EDIT: should have added that as it seems your script is just calling a HA service (presume to control something) then rest api is probably the way to go.

It may help to include more info on exactly what you are trying to do with your script on the HA side.

EDIT2: You can also use mqtt to talk to HA to create and update sensors if that is your objective and your script is remote or local to your HA machine but you would have to expose this port on your router as looks like you are accessing remotely. Updated above to include this option.

Hello Mark
Thank you for taking the time to respond to my request for help. Unfortunately I fear that my lack of Linux knowledge is going to force me to abandon this project.

The script was written by another member to enable HASS to receive commands from RTI remote software. The script is intended to operate as a bridge allowing two way text commands to be sent and received by the RTI remote app. Unfortunately the author assumed that anyone wishing to use his script would have the necessary knowledge to install it. My knowledge extends to executing a Hello World script and clearly that is not enough :cry:

I was hoping the script was going to be plug and play!

After a bit of searching looks like homeassistant.remote was removed after version 0.75, so a few years ago. So only way to make this script work is to modify to work with one of list above. Is there not an integration for this by now (this script is 6 years old) or maybe something in nodered that will work with it?

Thanks for putting me out of my misery. I tried every combination I could think of to make it work. Now it all makes sense if a part of the puzzle is missing.
I am not aware any other software that supports two way text based communications. I will checkout Nodered.
Thanks again for your help.