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)

Laurent

Web développeur freelance et surtout autodidacte, je navigue sur le web à la recherche de technologies plutôt bien fichue et performante pour mes développement web, app (mobile et desktop) et IOT (micropython, python). Après 9 ans de développement web, j'ai enfin créé un blog 😃. Je ne poste pas beaucoup mais j'espère que çà vous sera utile.

https://monkeytime.be/fr

Écrire un commentaire

L'email renseigné ne sera pas publié sur le site.

Quelle est le dernier caractère du mot ydcbv ? :