def stat(p): 
    n = len(p)
    mean = sum(p) / n
    var = sum((x - mean)**2 for x in p) / n
    std_dev = var ** 0.5
    return mean, std_dev

def do_measure(adc, transform_function, wait_ms=100, count=10):
    import array
    if wait_ms not in range (1, 10000): wait_ms=100
    if count not in range (1, 100): count=10
    p=array.array('f', [] )
    for i in range(count):
        p.append(transform_function(adc.read()))
        time.sleep_ms(wait_ms)
    return stat(p)

def http_senddata(url, username, password, data):
    import socket
    import ussl
    proto, _, host, path = url.split('/', 3)
    print(url)
    print(proto, host, path)
    print(socket.getaddrinfo(host, 443))
    print('------------')
    addr = socket.getaddrinfo(host, 443)[0][-1]

    msg='GET {0} HTTP/1.1\r\nHost: {1}\r\nUsername: {2}\r\nPassword: {3}\r\n{4}\r\n\r\n'.format(path, host, username, password, data)
    s = socket.socket()
    s.connect(addr)
    if proto=='https:':
        s=ussl.wrap_socket(s)
    print("sending: \n----"+msg+"----")
    s.write(bytes(msg, 'utf8'))
    header=s.read(2000)
    body=s.read(4000)
    s.close()
    return header, body

def read_config(conf_file):
    import json, os
    try:
        f=open(conf_file, 'r')
        conf=json.loads(f.read(1024))
        if conf['essid']=='your_essid' and conf['username']=='login_user':
            raise Exception(1, "default config file")
    except:
        print("Can't open or not filled config file {}".format(conf_file))
        x=os.getcwd()
        print("getcwd: {}".format(x))
        print('please create the file with content:\n{"essid": "your_essid", "key": "wifi_password", "consumer_url": "https://mail.example.eu/data/measure", "username": "login_user", "password": "login_password"}')
        time.sleep(10)
    finally:
        f.close()
    return conf

def do_wifi_connect(essid, key, rtc):
    wifi.connect(essid, key)
    while not wifi.status():
        print('Waiting for wifi connection...')
        time.sleep(1)
    wifi.ntp()
    print('network config:', wifi.sta_if.ifconfig())
    time.sleep(1)
    print('rtc time after setup: {0}, tz={1}'.format(time.strftime('%Y-%m-%d %H:%M:%S', rtc.now()), rtc.timezone()))




import time, machine, wifi, system

appName = system.currentApp()
print('{} starting ...'.format(appName))
time.sleep(1)

time.sleep(1)
conf = read_config('/lib/'+appName+'/mconfig.json')
mcp9701 = lambda x: (x-400)/19.5    # mV → °C convert rule for mcp9701
rtc=machine.RTC()
adc=machine.ADC(36)
adc.atten(adc.ATTN_6DB)

do_wifi_connect(conf['essid'], conf['key'], rtc)

url=conf['consumer_url']
user=conf['username']
passwd=conf['password']

while True: 
    celsius, dev = do_measure(adc, mcp9701)
    data="Temp1: {0:5.1f} +/- {1:3.2f} C".format(celsius, dev)
    print("http_senddata('{0}', '{1}', '{2}', '{3}')".format(url, user, passwd, data))
    header, body = http_senddata(url, user, passwd, data)
    print('------------header:')
    print(header)
    print('------------body:')
    print(body)
    print('sleeping...')
    time.sleep(60-1)