1

I have a Python script which retrieves the measured data from a smart plug so that I can visualize it on my Rasbperry Pi.

This command gets the data

send_hs_command("192.168.1.26", 9999, b'{"emeter":{"get_realtime":{}}}')

and this is the define

def send_hs_command(address, port, cmd):
    data = b""

    tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        tcp_sock.connect((address, port))
        tcp_sock.send(encrypt(cmd))
        data = tcp_sock.recv(2048)
    except socket.error:        
        print(time.asctime( time.localtime(time.time()) ), "Socket closed.", file=sys.stderr)
    finally:
        tcp_sock.close()
    return data

My problem is that if I take the Smart Plug somewhere else, it will have a new IP-Address, which means I have to keep rewriting it on my Python script. This is not an option for me. What would be the simplest solution? I have heard that I can add this (let's say the hostname of my device is "mydevice"):

hostname = "mydevice"
ip = socket.gethostbyname(hostname)

This works right now cause I found out the hostname of my device using an IP Scanner App on my phone. The problem is that I need to be able to take the smart plug to different places and I don't know if the hostname changes when the wifi network changes. Does it? I cannot keep rewriting the ip address on my script manually.

Thanks

  • Using hostname = "localhost" is a universal-platform solution. – user96931 May 6 at 18:19
  • Hi and thanks. To be honest I don't understand your comment. Can you explain a bit – xoani May 7 at 8:44
  • "localhost" as the hostname should return the IP address of the device your script is running on using ip = socket.gethostbyname(hostname). – user96931 May 7 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.