Advertisement
haddad1

RTI_HA PROXY.py

Aug 19th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.51 KB | None | 0 0
  1. import homeassistant.remote as remote
  2. import socket
  3. api = remote.API('https://ADDRESS.duckdns.org', 'PASSWORD', 443) # ('HA Address', 'HA Password', HA Port)
  4. print(remote.validate_api(api))
  5. HOST = ""
  6. PORT = 4999 # Listening Port
  7.  
  8. # Retrieve input from RTI
  9. # RTI 2-Way driver comand srting syntax examples:
  10. #   ,media_player*select_source*entity_id*media_player.living_room_tv*source*Netflix^
  11. #   ,vacuum*turn_on*entity_id*vacuum.roomba**^
  12. def msg_to_hass(strCommand):
  13.     domain = strCommand.split("*")[0] # HA Domain
  14.     service = strCommand.split("*")[1] # HA Service
  15.     field = strCommand.split("*")[2] # HA Field1
  16.     device = strCommand.split("*")[3] # HA Field1 Value
  17.     field2 = strCommand.split("*")[4] # HA Field2
  18.     device2 = strCommand.split("*")[5] # HA Field2 Value
  19.     data = {}   # initialize dictionary
  20.     data[field] = device # insert field 1 and value into dictionary
  21.     data[field2] = device2 # insert field 2 and value into dictionary
  22.     new_data={k:data[k] for k in data if data[k]} # Remove blank entries from data dictionary and save as new_data
  23.     print(domain, service, new_data) # print domain, service, and data to send to HA
  24.     remote.call_service(api, domain, service, new_data) # send command to HA
  25.     state = remote.get_state(api, device) # request device state from HA
  26.     print(state) # Print state of HA Device
  27.    
  28. def create_listen_socket(host, port):
  29.     """ Setup the sockets our server will receive connection
  30.    requests on """
  31.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  32.     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  33.     sock.bind((host, port))
  34.     sock.listen(100)
  35.     return sock
  36.  
  37. def recv_msg(sock):
  38.     """ Wait for data to arrive on the socket, then parse into
  39.    messages using b'\0' as message delimiter """
  40.     data = bytearray()
  41.     msg = ''
  42.     # Repeatedly read 4096 bytes off the socket, storing the bytes
  43.     # in data until we see a delimiter
  44.     while not msg:
  45.         recvd = sock.recv(4096)
  46.         if not recvd:
  47.             # Socket has been closed prematurely
  48.             raise ConnectionError()
  49.         data = data + recvd
  50.         #if b'\0' in recvd:
  51.         if b'^' in recvd:   # ^ is the last character in the message. Strip the starting comma.
  52.             #msg = data.rstrip(b'\0')
  53.             msg = data
  54.     msg = msg.decode('utf-8')
  55.     msg = msg.split(",")[-1]
  56.     return msg.rstrip("^")
  57.  
  58. def prep_msg(msg):
  59.     """ Prepare a string to be sent as a message """
  60.     msg += '\0'
  61.     return msg.encode('utf-8')
  62.  
  63. def send_msg(sock, msg):
  64.     """ Send a string over a socket, preparing it first """
  65.     data = prep_msg(msg)
  66.     sock.sendall(data)
  67.  
  68.  
  69.  
  70.  
  71. def handle_client(sock, addr):
  72.     """ Receive data from the client via sock and echo it back """
  73.     try:
  74.         msg = recv_msg(sock) # Blocks until received complete message
  75.         print('{}: {}'.format(addr, msg))
  76.         #send_msg(sock, msg) # Blocks until sent
  77.         msg_to_hass(msg)
  78.     except (ConnectionError, BrokenPipeError):
  79.         print('Socket error')
  80.     finally:
  81.         handle_client(client_sock, addr)        # loop back to recv_msg
  82.     #     print('Closed connection to {}'.format(addr))
  83.     #     sock.close()
  84.  
  85.  
  86. if __name__ == '__main__':
  87.     listen_sock = create_listen_socket(HOST, PORT)
  88.     addr = listen_sock.getsockname()
  89.     print('Listening on {}'.format(addr))
  90.  
  91.     while True:
  92.         client_sock, addr = listen_sock.accept()
  93.         print('Connection from {}'.format(addr))
  94.         handle_client(client_sock, addr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement