Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4843

MicroPython • Re: How to draw simple chart on client side from server data

$
0
0
jsChart is a valid option.
Sample code, check network definitions, had to change it for local use.

Code:

"""05.01.2024 dodana meritev temperature na PICOGarage Door Controller codeWritten by Michael Ruppe @ Core Electronics    - Version 1.0 July 2022Hosts a static webpage with three garage door control buttons (Up, Stop, Down)Outputs: Open Drain channels to pull-down garage door controller channels.Adapted from examples in: https://datasheets.raspberrypi.com/picow/connecting-to-the-internet-with-pico-w.pdfhttps://core-electronics.com.au/projects/wifi-garage-door-controller-with-raspberry-pi-pico-w-smart-home-project/"""import timeimport networkimport uasyncio as asynciofrom machine import Pin, WDT, RTCimport secretsrtc=machine.RTC()#wdt = WDT(timeout = 8000)adcpin = 4pico_temp = machine.ADC(adcpin)temperature_pico = 25# Hardware definitionsled = Pin("LED", Pin.OUT, value=1)pin_up = Pin(5, Pin.OUT, value=0)#pin_up = Pin(17, Pin.OUT, value=0)#pin_up = Pin(18, Pin.OUT, value=0)# Configure your WiFi SSID and passwordssid = secrets.WiFi.ssid #Your network namepassword = secrets.WiFi.password  #Your WiFi passwordcheck_interval_sec = 0.25wlan = network.WLAN(network.STA_IF)OUT_Buffer_temperature = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]read_flag = True# The following HTML defines the webpage that is servedhtml = """<!DOCTYPE html><html></body> <body style="background-color:powderblue;"></body><head><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,"><style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}.button { background-color: #4CAF50; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }.buttonRed { background-color: #d11d53; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head><body><center><h1>Garazna vrata</h1></center><br><br><form><center><center> <button class="button" name="DOOR" value="UP" type="submit">Odpri</button><br><br><center> <button class="buttonRed" name="DOOR" value="STOP" type="submit">Get Temp.</button><br><br><center> <button class="button" name="DOOR" value="DOWN" type="submit">Zapri</button></center></center></form><br><br><br><br><div>  <canvas id="myChart"></canvas></div><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><script>  var input = %s;  // build the labels on the fly. Could be provided  // from the application here as code uses RTC  const labels = [];  for(var i = 0; i < input.length; i ++ ){      labels.push(i);  }    const data = {      labels: labels,      datasets: [{        label: 'Temperatures',        data: input,        fill: false,        borderColor: 'rgb(75, 192, 192)',        tension: 0.1      }]    };  const ctx = document.getElementById('myChart');  new Chart(ctx, {    type: 'line',    data: data ,        options: {      scales: {        y: {          beginAtZero: true        }      }    }  });</script></body></html>"""#-------------------------------------------------------------------------------def Buffer_temperature(IN_FiFo, OUT_Buffer_temperature):    OUT_Buffer_temperature.pop(0)    OUT_Buffer_temperature.append(IN_FiFo)#'-------------------------------------------------------------------------------        def get_time():    timestamp=rtc.datetime()    leto = timestamp[0]    mesec = timestamp[1]    dan = timestamp[2]    ura = timestamp[4]    minuta = timestamp[5]    sekunda = timestamp[6]    return leto, mesec, dan, ura, minuta, sekunda#-------------------------------------------------------------------------------        def ReadTemperature():    adc_value = pico_temp.read_u16()    volt = (3.3/65535) * adc_value    temperature = 27 - (volt - 0.706)/0.001721    #a = round(temperature, 1)    #print('temperature = ', temperature, 'a', a)    return round(temperature, 1)#-------------------------------------------------------------------------------def blink_led(frequency = 0.5, num_blinks = 3):    for _ in range(num_blinks):        led.on()        time.sleep(frequency)        led.off()        time.sleep(frequency)#-------------------------------------------------------------------------------def control_door(cmd):    if cmd == 'stop':        #pin_up.on()        blink_led(0.1, 1)        #pin_up.off()            if cmd == 'up':        pin_up.on()        blink_led(0.1, 1)        pin_up.off()        if cmd == 'down':        pin_up.on()        blink_led(0.1, 1)        pin_up.off()#-------------------------------------------------------------------------------        async def connect_to_wifi():    wlan.active(True)    #wlan.config(pm = 0xa11140)  # Diable powersave mode    wlan.ifconfig(('192.168.4.219', '255.255.255.0', '192.168.4.1', '8.8.8.8'))    wlan.connect(ssid, password)    # Wait for connect or fail    max_wait = 10    while max_wait > 0:        if wlan.status() < 0 or wlan.status() >= 3:            break        max_wait -= 1        #print('waiting for connection...')        time.sleep(1)    # Handle connection error    if wlan.status() != 3:        blink_led(0.1, 10)        raise RuntimeError('WiFi connection failed')    else:        blink_led(0.5, 2)        #print('connected')        status = wlan.ifconfig()        print('ip = ' + status[0])#-------------------------------------------------------------------------------async def serve_client(reader, writer):    global OUT_Buffer_temperature        #print("Client connected")    request_line = await reader.readline()    #print("Request:", request_line)    # We are not interested in HTTP request headers, skip them    while await reader.readline() != b"\r\n":        pass        # find() valid garage-door commands within the request    request = str(request_line)    cmd_up = request.find('DOOR=UP')    cmd_down = request.find('DOOR=DOWN')    cmd_stop = request.find('DOOR=STOP')    #print ('DOOR=UP => ' + str(cmd_up)) # show where the commands were found (-1 means not found)    #print ('DOOR=DOWN => ' + str(cmd_down))    #print ('DOOR=STOP => ' + str(cmd_stop))    stateis = "" # Keeps track of the last command issued        # Carry out a command if it is found (found at index: 8)    if cmd_stop == 8:        #stateis = ": STOP"        #b = ReadTemperature()        c = OUT_Buffer_temperature #[b, 21.1, 22.1, 23.3, 24.4]        stateis = (str(c))         print(stateis)        control_door('stop')            elif cmd_up == 8:        stateis = "ODPRI"        #print(stateis)        control_door('up')            elif cmd_down == 8:        stateis = "ZAPRI"        #print(stateis)        control_door('down')        response = html % stateis    writer.write('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')    writer.write(response)    await writer.drain()    await writer.wait_closed()#-------------------------------------------------------------------------------async def main():    global read_flag    #print('Connecting to WiFi...')    asyncio.create_task(connect_to_wifi())    #print('Setting up webserver...')    asyncio.create_task(asyncio.start_server(serve_client, "0.0.0.0", 80))    while True:        await asyncio.sleep(check_interval_sec)        #wdt.feed()        a = get_time()        if ((a[5] == 0) and (read_flag == True)):            b = ReadTemperature()            Buffer_temperature(b, OUT_Buffer_temperature)            print(a[3], a[4], a[5], ' ', OUT_Buffer_temperature)            read_flag = False                    if a[5] == 10:            read_flag = True#-------------------------------------------------------------------------------try:    print('-------------------------------asyncio.run(main())')    asyncio.run(main())    finally:    asyncio.new_event_loop()    #print('.....................................asyncio.new_event_loop()')

Statistics: Posted by ghp — Sat Jan 20, 2024 10:51 am



Viewing all articles
Browse latest Browse all 4843

Trending Articles