#
# https://docs.micropython.org/en/latest/wipy/tutorial/wlan.html
# curl --http1.0 192.168.1.206 or what ever.
#
# Serve a web page with values wrapped in:
# <p id=latest ></p>
# <p id=list1minute  ></p>
# <p id=list15minute ></p>
# latest,
#
# wizzy003.py
# loggerNodeDS18_006.py
# 2026-04-06 08:00
#
# Read the AtoD and add value to a list
#
# If a Web Browser connects ouput list as CSV values.
# 
# http://192.168.1.104/red
# http://192.168.1.104/green
# http://192.168.1.104/blue
#
# needs http:// else browser does not send HTML, It only does a TCP/IP connect
# Problems if http://192.168.1.104/red is not used
#
#import gc
#import micropython
#gc.collect()
#micropython.mem_info()
#print('-----------------------------')
#print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc()))

#micropython.mem_info(1)
#
# try using memory to buffer values
#
# log two DS18B20 
buffer      = [] #// used to test ADC
buffer1min  = [] #// DS18B20
buffer15min = [] #// DS18B20

# Import for DS18B20, 
import machine, onewire, ds18x20, time 
from machine import Pin
from machine import ADC
from machine import Pin, I2C
import ssd1306

'''
f = open('log.txt',"a")
ldr = adc.read()
f.write( "\r\n|,"+str( ldr ) + "," )
f.close()
'''

'''
f = open('log.txt')
data = f.read()
print( data )
f.close()
'''

#
# NodeMCU pins
#

adc = ADC(0)            # create ADC object on ADC pin
print( 'ADC:' , adc.read() )  

#LED on ESP12 on pin 2

led = machine.Pin(2, Pin.OUT, value=0)
led.on
time.sleep(0.1)
led.off
time.sleep(0.1)
led.on
time.sleep(0.1)
#
#

print( 'led' )

count =1000

import asyncio

async def blink( period_ms):
    
    led = machine.Pin(2, Pin.OUT, value=0)
    while True:
        global count
        count +=1
        #countUp()
        #led on esp pulled low
        led.off()
        await asyncio.sleep_ms(5)
        led.on()
        await asyncio.sleep_ms(period_ms)

        
# start a polling loop
# have two buffers,
# one for every 1 minute,
# one for every 15 minute,

import ssd1306

i2c     = I2C(sda=Pin(14), scl=Pin(12))
display = ssd1306.SSD1306_I2C(128, 64, i2c)

# append every 15th reading to
async def logDS18B20( period_s ):
    count = 0
    while True:
        global buffer1min
        global buffer15min
        
        print( "==== logDS18B20 " )        
        print( len( buffer1min ) )
        #
        ds_pin = machine.Pin(13)
        ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
        roms = ds_sensor.scan()
        # print('Found DS devices: ', len( roms ), ' ', roms)
        print('Found DS devices: ', len( roms ) )

        c = str( len( roms ) ) + " " + str( count )
        y = 10

        display.fill(0)
        display.rotate( False )  
        display.text( 'DS: '+ c ,  0, y, 1 )
        for rom in roms:
            print(  rom  )
            t= str( ds_sensor.read_temp(rom) )
            print( t )
            y += 12
            display.text( t ,  0, y, 1)
            display.show()

        roms = ds_sensor.scan()
        # print('Found DS devices: ', len( roms ), ' ', roms)
        print('Found DS devices: ', len( roms ) )

        count +=1
        # print( buffer1min )
        if len( buffer1min ) > 10 :
           print( ' del start buffer1min ' )
           del buffer1min[0]
           del buffer1min[0]

        if len( buffer15min ) > 300 :
           print( ' del start buffer1min ' ) 
           del buffer15min[0]
           del buffer15min[0]

        if len( roms ) > 0 :
            ds_sensor.convert_temp()
            await asyncio.sleep_ms(750)
            for rom in roms:
                #print(  rom  )
                t = ds_sensor.read_temp( rom )
                if ( divmod( count, 1 )[1] == 0 ) :
                    buffer1min.append(t)
                    print( '@15sec', t , len( buffer1min ) )
                
            if ( divmod( count, 60 )[1] == 0  ) :
                count = 0                 # 
                # buffer15min.append(0)
                
                for rom in roms:
                    #print(  rom  )
                    t = ds_sensor.read_temp( rom )
                    buffer15min.append(t)
                    print( '@15 ', t )
                    
            await asyncio.sleep(15)
        



print( "loop started " )

# https://bytepawn.com/writing-a-simple-python-async-message-queue-server.html
# https://docs.python.org/3/library/asyncio.html

html10start = """
<!DOCTYPE html>
<html>
<head> <title> ESP8266 DS18B20 </title> </head>
<body> <h1> = ESP8266 DS18B20 = </h1>

"""

html10middle = "<h1> count:= %s , adc:= %s </h1>\r\n"
html10middleDS18B20 = "<h1> T:= %s </h1>\r\n"
html10end = """
    </body>
<style> 
* { font-family: sans-serif, monospace ; padding:10px; }
TH { background:#ccc; }
TD { background:#eee; font-family: monospace ; }
</style> 
</html>

"""

#
# this sort of works!
#
from machine import ADC

adc = ADC(0)            # create ADC object on ADC pin
adc.read()  

async def handle_client(reader, writer):
    global count
    print('New client connected...'+ str( count ) )
    line = str()
    print( line )
    #read until blank line
    while line != '':
        line = str( await reader.readline() )
        print( line )

    # these made it work!
    time.sleep(0.1)
    writer.write('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
    writer.write( html10start )
    global count
    count +=1
    
    adc = ADC(0)            # create ADC object on ADC pin
    adc.read()
    
    ds_pin = machine.Pin(13)
    ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

    roms = ds_sensor.scan()
    print('Found DS devices: ', len( roms ), ' ', roms)

    if len( roms ) > 0 :
        ds_sensor.convert_temp()
        time.sleep_ms(750)
        print( "DB18B20: ")
        for rom in roms:
            #print(  rom  )
            t = ds_sensor.read_temp(rom)
            writer.write( html10middleDS18B20 % ( t )  )
            print( t )

    writer.write( html10middle % ( count , adc.read() )  )
    
    
    # read logged values
    writer.write( "<h2>1min:</h2><p id=buffer1min >,")
    i = 0 
    while i < len( buffer1min ) :
        
      writer.write( " "+str( buffer1min[ i ] ) + "," + str( buffer1min[ i+1 ] ) + ","  )
      i +=2

    writer.write( "</p>\n\r")
    
    writer.write( "<h2>15min:</h2><p id=buffer15min >,")
    
    i = 0 
    while i < len( buffer15min ) :
      #writer.write( str( buffer1min[ i ]) +"," )
      writer.write( " "+str( buffer15min[ i ]) + "," + str( buffer15min[ i+1 ] ) + ","  )
      i +=2

    writer.write( "</p>\n\r")

    writer.write( "<p>")
    # writer.write( buffer)
    # writer.write( len( buffer ) )
    writer.write( "</p>\n\r")
    writer.write( html10end )

    # allow for characters to be sent and received
    time.sleep(1.0)
    #writer.sleep(0.5)
    writer.drain()
    writer.close()
    await writer.wait_closed()
    #reader.close()    

    print('Client disconnected...')

#host = '0.0.0.0'
#port = 8080
async def run_server( host, port ):
    server = await asyncio.start_server( handle_client, host, port )
    print(f'Listening on {host}:{port}...')
    async with server:        
      #await server.serve_forever()
      while True:
        await asyncio.sleep(1)
        
    #   await asyncio.sleep(300)
    


#
# set up WiFi as Station and Access Point
#

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

#deleted - use local credential

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="ESP-node", security=network.AUTH_WPA_WPA2_PSK, key='5678901234')

#
# this is now working, but now sure how.
#

async def main(  ):
    # click off on shot task
    asyncio.create_task( blink( 1000) )    
    asyncio.create_task( logDS18B20( 1)   )       
    #asyncio.create_task( run_server(host='0.0.0.0', port=int( 80 ) ) )
    print( "main loop")
        
    await asyncio.sleep_ms(10000)

#
# this sort of works
asyncio.run( main(  ) )
asyncio.run( run_server(host='0.0.0.0', port=int( 80 ) ) )
