I am trying to send the data measured by my Smart Plug into the Microsoft Azure Cloud so that I can visualize it there later.

I have a python program (the original is from BeardMonkey https://www.beardmonkey.eu/tplink/hs110/2017/11/21/collect-and-store-realtime-data-from-the-tp-link-hs110.html ) that displays the measurements of the smart plug in the terminal of the Raspberry Pi. I don't think this data is being saved, only displayed on the terminal. I want to send this data to the Microsoft Cloud but I don't even know where to start. I know that I need to use the IoT Hub and add the Raspberry Pi as an IoT Edge Device, but nothing else. Any help?

Here is my script:

import sys
import time
import socket
import json
import threading
from struct import *

def int_to_bytes(x):
    return x.to_bytes((x.bit_length() + 7) // 8, 'big')

def int_from_bytes(xbytes):
    return int.from_bytes(xbytes, 'big')

def encrypt(string):
    key = 171
    result = pack('>I', len(string))
    for i in string:
        a = key ^ i
        key = a
        result += int_to_bytes(a)
    return result

def decrypt(string):
    key = 171
    result = b""
    for i in string:
        a = key ^ i
        key = i
        result += int_to_bytes(a)
    return result

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

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

def run():
    threading.Timer(5.0, run).start()

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

    if not data:
        print(time.asctime(time.localtime(time.time()) ), "No data returned on power request.", file=sys.stderr)

    decrypted_data = decrypt(data[4:]).decode()
    #print("DECRYPTED DATA", '\n',decrypted_data,'\n' )

    json_data = json.loads(decrypted_data)
    #print("JSON DATA", '\n',json_data,'\n' )

    emeter = json_data["emeter"]["get_realtime"]
    #print("RAW METER", '\n',emeter,'\n' )

    print("SMART PLUG DATA - ",time.asctime( time.localtime(time.time()) ),'\n', "Current: ", emeter["current_ma"],"mA",'\n'\
          ,"Voltage: ",emeter["voltage_mv"], "mV", '\n',"Power: ", emeter["power_mw"], "mW",'\n', "Total Energy: ",\
          emeter["total_wh"], "Wh", '\n\n')

    if not emeter:
        print("No emeter data returned on power request.", file=sys.stderr)


  • Not an RPi-specific question. MSFT has lots of fora for Azure questions; have you tried asking there first? – JayEye Apr 3 at 2:43

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.