ChatGPT et correction de la programmation

le code injecté dans chatGPT


import uos

try:
  import usocket as socket
except:
  import socket

import network
import time

import esp
esp.osdebug(None)

import ujson

import gc
gc.collect()

ap = network.WLAN(network.AP_IF)

def verify_user_WiFi():
    if uos.stat("wifi.json")[6] == 0:
        return False
    with open('wifi.json', 'w') as json_file:
        data = ujson.load(json_file)
        if data["ssid"] is None or data["key"] is None:
            return False
        sta_if = network.WLAN(network.STA_IF)
        if not sta_if.isconnected():
            print('Testing connection to your wifi network...')
            sta_if.active(True)
            sta_if.connect(data["ssid"], data["key"])
            if not sta_if.isconnected():
                return False
    

def start_AP():
    ssid = 'BULB-AP'
    password = '123456789'

    ap.active(True)
    ap.config(essid=ssid, password=password)

    while ap.active() == False:
      pass

    print('Starting AP successful')
    print(ap.ifconfig())

def stop_AP():
    ap.active(False)
    print('Stopping AP successful')
    
def do_connect_to_user_WiFi(ssid, key):
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(ssid, key)
        if not sta_if.isconnected():
            return False
    print('network config:', sta_if.ifconfig())
    
def listen():
    start_AP()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    s.listen(5)

    while True:
      conn, addr = s.accept()
      print('Got a connection from %s' % str(addr))
      request = conn.recv(4096).decode('utf-8')
      print('Content = %s' % str(request))
      data = request.json()
      if data["ssid"] is not None and data["key"] is not None:
          if do_connect_to_user_WiFi(data["ssid"], data["key"]) == False:
              conn.send("invalid")
              conn.close()
          conn.send("connected")
          with open('wifi.json', 'w') as json_file:
              dictionary = {"ssid": data["ssid"], "key": data["key"]}
              ujson.dump(dictionnary, json_file)
          conn.close()
          stop_AP()
      conn.close()
      
if verify_user_WiFi() == False:
    listen()

Le texte "commentaire" sorti par chatGPT

This program sets up an access point (AP) on the ESP8266 with the name "BULB-AP" and password "123456789". It then opens a socket on port 80 and listens for incoming connections. When a client connects, it reads the request and checks if it contains valid wifi credentials in the form of a json object with "ssid" and "key" fields. If the wifi credentials are valid, the ESP8266 connects to the specified wifi network and saves the credentials to a file named "wifi.json" and sends "connected" to the client. If the wifi credentials are not valid, it sends "invalid" to the client and continues to listen for connections. It also has a function named verify_user_WiFi() which check if the wifi.json file exist and contain valid ssid and key, if not, it starts the AP. It is important to note that this code does not include error handling for edge cases and invalid input, such as a file not being found or improperly formatted JSON data. In a real-world implementation, you would want to include additional error handling and testing to ensure that the program is robust and can handle a wide range of inputs.

La correction en injectant le texte

Create a program that sets up an access point (AP) on the ESP8266 with the name "BULB-AP" and password "123456789". It then opens a socket on port 80 and listens for incoming connections. When a client connects, it reads the request and checks if it contains valid wifi credentials in the form of a json object with "ssid" and "key" fields. If the wifi credentials are valid, the ESP8266 connects to the specified wifi network and saves the credentials to a file named "wifi.json" and sends "connected" to the client. If the wifi credentials are not valid, it sends "invalid" to the client and continues to listen for connections. It also has a function named verify_user_WiFi() which check if the wifi.json file exist and contain valid ssid and key, if not, it starts the AP.


import network
import socket
import ujson

def verify_user_WiFi():
    try:
        with open('wifi.json', 'r') as json_file:
            data = ujson.load(json_file)
            if "ssid" not in data or "key" not in data:
                raise ValueError("Invalid wifi json file")
            sta_if = network.WLAN(network.STA_IF)
            if not sta_if.isconnected():
                print('Testing connection to user wifi network...')
                sta_if.active(True)
                sta_if.connect(data["ssid"], data["key"])
                if sta_if.isconnected():
                    print("Connected to wifi network")
                    return True
                else:
                    raise ValueError("Cannot connect to wifi network")
    except (OSError, ValueError):
        print("WiFi credentials not found, starting AP")
        return False

def start_AP():
    ssid = 'BULB-AP'
    password = '123456789'

    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid=ssid, password=password)

    while ap.active() == False:
      pass

    print('Access Point started successfully')
    print(ap.ifconfig())

def stop_AP():
    ap = network.WLAN(network.AP_IF)
    ap.active(False)
    print('Access Point stopped successfully')

def do_connect_to_user_WiFi(ssid, key):
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('Connecting to network...')
        sta_if.active(True)
        sta_if.connect(ssid, key)
        if not sta_if.isconnected():
            return False
    print('Connected to wifi network:', sta_if.ifconfig())
    return True

def listen():
    start_AP()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    s.listen(5)

    while True:
        conn, addr = s.accept()
        print('Got a connection from %s' % str(addr))
        request = conn.recv(4096).decode('utf-8')
        print('Content = %s' % str(request))
        try:
            data = ujson.loads(request)
            if "ssid" not in data or "key" not in data:
                raise ValueError("Invalid wifi json")
            if do_connect_to_user_WiFi(data["ssid"], data["key"]) == False:
                conn.send("invalid".encode())
                conn.close()
                continue
            with open('wifi.json', 'w') as json_file:
                ujson.dump(data, json_file)
            conn.send("connected".encode())
            stop_AP()
        except (ValueError,OSError) as e:
            print(e)

PWA (Progressive Web App) init, un exemple fonctionnel

Si vous voulez démarrer avec un site web qui peut s'installer comme application sur un smartphone (c'est une option du navigateur qui s'affiche et qui proposera l'installation), voici un petit dossier d'exemple, un petit "Hello World", pour démarrer votre projet


<!-- le code du fichier index.html -->
<!DOCTYPE html>
<html lang="fr" dir="ltr">

    <head>

    <meta name="theme-color" content="#ffffff">

    <script src="/js/https.js" type="text/javascript" async></script>

    <meta charset="utf-8">
    <link rel="manifest" crossorigin="use-credentials" href="/manifest.json">

    <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->
    <meta name="viewport" content="initial-scale=1.0">

    <title>Your site title</title>

    <meta content="follow,index" name="robots">
    <meta name="description" content="Your site description">
    <meta name="keywords" content="some, thing">

    <meta name="author" content="First Name Last Name">
    <meta name="copyright" content="All rights reserved">

    <link rel="icon" type="image/png" href="/favicon.png" />
    <link rel="icon" type="image/vnd.microsoft.icon" href="/favicon.ico">
    <!--[if IE]><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /><![endif]-->

    <meta property="og:type" content="website">
    <meta property="og:locale" content="en">
    <meta property="og:site_name" content="Site Name">
    <meta property="og:title" content="Page Title">
    <meta property="og:description" content="Page description">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <link rel="apple-touch-icon" title="Site title" sizes="57x57" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="114x114" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="72x72" href="/touch-retina.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="144x144" href="/touch-retina.webp">

    <link rel="apple-touch-icon" title="Site title" sizes="57x57" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="60x60" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="72x72" href="/touch-retina.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="76x76" href="/touch-retina.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="114x114" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="120x120" href="/touch-icon.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="144x144" href="/touch-retina.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="152x152" href="/touch-retina.webp">
    <link rel="apple-touch-icon" title="Site title" sizes="180x180" href="/touch-retina.webp">
    <link rel="icon" type="image/png" title="Site title" href="/favicon.webp" sizes="32x32">
    <link rel="icon" type="image/png" title="Site title" href="/touch-retina.webp" sizes="192x192">
    <link rel="icon" type="image/png" title="Site title" href="/touch-retina.webp" sizes="96x96">
    <link rel="icon" type="image/png" title="Site title" href="/favicon.webp" sizes="16x16">
    <link rel="icon" type="image/png" title="Site title" href="/favicon.webp" />

    <meta name="msapplication-TileColor" content="transparent">
    <meta name="msapplication-TileImage" content="/touch-retina.webp">

    <!--[if lt IE 9]><script src="/js/html5shiv.js" type="text/javascript"></script><script src="/js/respond.js" type="text/javascript"></script><![endif]-->

    </head>

     <body>

        <h1>Hello World !</h1>

    </body>

</html>


<link rel="stylesheet" type="text/css" href="/css/main.css" media="all">

<script type="text/javascript" async>
window.onload = () => {
	'use strict';
  
	if ('serviceWorker' in navigator) {
	  navigator.serviceWorker
			   .register('./sw.js');
	}
}
</script>

https://github.com/MonkeyTime/PWA-init

Les éditeurs ou IDE indispensables

1 Atom https://atom.io + package Pymakr

est exempt de bug pour le développement micropython ou sous Pycom

 

2 Thonny https://thonny.org

idéal si vous débutez le développement ESP32 ou ESP8266

 

3 Studio Code https://code.visualstudio.com

pour tous autres langages de programmation (pour ma part surtout javascript) ou

pour tous frameworks type electronjs, Cordova, nodejs, Meteorjs (mais l'extension Pymakr pour Visual Studio Code a un bug)

 

4 Eclipse PHP IDE https://www.eclipse.org/pdt

j'aime bien pour gérer et développer mes projets PHP "from scratch" et sans auto-complétion.

TTGO oled ESP32 et SSD1306

Une librairie SSD1306 pour TTGO oled ESP32 qui fonctionne.


from machine import SoftI2C, Pin
import ssd1306

# ESP32 Pin assignment
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))

# ESP8266 Pin assignment
#i2c = I2C(-1, scl=Pin(5), sda=Pin(4))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.fill(0)
oled.text('Hello, World 1!', 0, 0)
oled.text('Hello, World 2!', 0, 10)
oled.text('Hello, World 3!', 0, 20)
oled.show()

# # If you need to disable oled in production environment
# from machine import SoftI2C, Pin
# import ssd1306
# 
# # ESP32 Pin assignment
# i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
# 
# # ESP8266 Pin assignment
# #i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
# 
# oled_width = 128
# oled_height = 64
# oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# oled.fill(0)
# oled.poweroff()

https://github.com/MonkeyTime/TTGO-Oled-ESP32-SSD1306-library