#
# Using and ESPO01 and multiple DS18B20 to read the temperatures
# This sort of works
# You need to disconnect from WiFI and connect to SSID 
# and use ipconfig
#
# https://docs.micropython.org/en/latest/wipy/tutorial/wlan.html
#
# curl --http1.0 192.168.1.206
#
# 

#import machine
import machine, onewire, ds18x20, time

# Router specific:-
SSID = 'PLUSNET-Sxxx'
KEY  = '1234567890'

#
# 
#

ds_pin = machine.Pin(2)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()

print('Found DS devices: ', len( roms ), ' ', roms)

#while True:
#while False:
if len( roms ) > 0 :

    ds_sensor.convert_temp()
    time.sleep_ms(750)
    print( "DB18B20: ")
    for rom in roms:
        print(  rom  )
        print(ds_sensor.read_temp(rom))

    st = ''
    st2 = ''

    for rom in roms:
        #st2 +=  str(  rom   ) + ' '
        st2 += " [, "+",".join( hex(b) for b in rom )+", ] , "
        st = st + str( ds_sensor.read_temp(rom) ) + ' , '
        
    st += st2
    print( st )



import network
sta_if = network.WLAN(network.WLAN.IF_STA); sta_if.active(True)
#print( sta_if.scan()  )                           # Scan for available access points
#sta_if.connect("<AP_name>", "<key>") # Connect to an AP
sta_if.connect( SSID , KEY ) # Connect to an AP
print( sta_if.isconnected() )                     # Check for successful connection


# Change name/password of ESP8266's AP:
ap_if = network.WLAN(network.WLAN.IF_AP)
#ap_if.config(ssid="<AP_NAME>", security=network.AUTH_WPA_WPA2_PSK, key="<key>")
ap_if.config(ssid=SSID, security=network.AUTH_WPA_WPA2_PSK, key=KEY)

print( bdev )
    
pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)]

#<table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table>

# %s 
html = """<!DOCTYPE html>
<html>
    <head> <title>ESP8266 DS18B20 </title> </head>
    <body> <h1>ESP8266 DS18B20 </h1>
    <h2> %s , %s </h2>
    </body>
</html>
"""

import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

print('listening on', addr)

while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    
    # this needs to be more robust
    t = 0
    t1 = 0
    t2 = 0
    st = 'No DS18B20 found '
    st2 = ''
    
    if len( roms ) > 0 :
        ds_sensor.convert_temp()
        time.sleep_ms(750)
        # build up CSV list
        st = 'DS18B20 , '
        for rom in roms:
            # st2 +=  str(  rom   ) + ' '
            st2 += " [, "+",".join( hex(b) for b in rom )+", ] , "
            st = st + str( ds_sensor.read_temp(rom) ) + ' , '
        
        st += st2
        print( st )
          
        t1 = ds_sensor.read_temp(rom)
        t2 = ds_sensor.read_temp(rom)

    cl_file = cl.makefile('rwb', 0)
    
    # read values from POST    
    while True:
        line = cl_file.readline()
        if not line or line == b'\r\n':
            break
        
    # rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
    # response = html % '\n'.join(rows)  
    #
    # temps = ['%s ' % (str(p), p.value()) for p in roms]
    response = html % ( str( len( roms ) ) , st )
    
    cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
    cl.send(response)
    cl.close()
    
