01studio 1.2.2 01studio 1.2.0镜像版本 socket无法使用

Viewed 74

新版本镜像中无法使用socket功能
1、体现1 wlan.active() 返回错误network(rt_smart) not support set active state
2、体现2 socket.connect()返回错误EHOSTUNREACH ECONNABORTED
具体代码如下 在1.0版本下如下代码可以正常运行 期待尽快解决这个 问题 因为新的镜像 确实非常之快!

import json
import socket
import mynetwork as mynt

def get_config(server_host, server_port, server_path, machine_code, json_path):

    s = None
    try:
        # 解析服务器地址
        ai = socket.getaddrinfo(server_host, server_port)
        print(ai)
        addr = ai[0][-1]  # 获取第一个地址的sockaddr
        # 创建并连接套接字
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(10)
        s.connect(addr)
        data =machine_code.encode()

        # 构建HTTP请求
        boundary = '---------------------------1234567890'

        # 构造请求体
        body_header = (
            f'--{boundary}\r\n'
            'Content-Disposition: form-data; name="request_for_config";\r\n'
            'Content-Type: string\r\n\r\n'
        ).encode()
        body_footer = f'\r\n--{boundary}--\r\n'.encode()
        body_content = body_header + data + body_footer

        # 构造请求头
        headers = (
            'POST {p} HTTP/1.1\r\n'
            'Host: {h}:80\r\n'
            'Content-Type: multipart/form-data; boundary={b}\r\n'
            'Content-Length: {cl}\r\n\r\n'
        ).format(
            p=server_path,
            h=server_host,
            b=boundary,
            cl=len(body_content)
        ).encode()

        # 发送完整请求
        print('send!')
        s.sendall(headers + body_content)

        # 接收响应(简单接收前1024字节)
        response = s.recv(1024)
        response = response.decode()
        
        print(response)

        start_index = response.find('{')
        end_index = response.rfind('}')

        if start_index != -1 and end_index != -1:
            json_str = response[start_index:end_index + 1]
            try:

                json_data = json.loads(json_str)

                if "success" in json_data:
                    return 0,0

                with open(json_path, 'w') as f:
                    json.dump(json_data, f)
                    print('json loaded!')
                return 1, json_data

            except Exception as e:
                print(e)
                return 0, e
        else:
            return 0,0

    except Exception as e:
        print("Upload failed:", e)
        return 0,0
        if s:
            s.close()


# 使用示例
if __name__ == "__main__":

    mynt.WIFI_Connect('szx','12345678')

    # 上传参数
    SERVER_HOST = "****"
    SERVER_PORT = 80
    UPLOAD_PATH = "/send_json.php"

    a = get_config(SERVER_HOST, SERVER_PORT, UPLOAD_PATH, '11f3422f938f32e99ae07fbe9d97ea4f','/sdcard/config.json')


import network
import time
import socket
import os
import json
from machine import Pin, Timer

'''send to server code'''
'''macro defination'''
#MY_WIFI_COUNT = 'B503-WIFI-2G'
#MY_WIFI_PASSWORD = 'jsls-f7-1008'
#MY_server_host = '39.104.53.49'
#MY_server_port = 80
#MY_path = '/upload.php'
'''macro defination/'''


# @brief:       connect to wifi
# @parameters:  WIFI_COUNT str
#               WIFI_PASSWORD str
# @return:      True or False
#               if not connect to the WI-FI toggle the blue light for three times
#               else keep it bright
def WIFI_Connect(WIFI_COUNT, WIFI_PASSWORD):

    WIFI_LED = Pin(52, Pin.OUT)

    wlan = network.WLAN(0) #STA模式
    wlan.active(1)

    if wlan.isconnected():
        wlan.disconnect()

    for i in range(3):
        wlan.connect(WIFI_COUNT, WIFI_PASSWORD)
        if wlan.isconnected():
            break

    if wlan.isconnected():
        WIFI_LED.value(1)
        return True

    else:
        for i in range(3):
            WIFI_LED.value(1)
            time.sleep_ms(300)
            WIFI_LED.value(0)
            time.sleep_ms(300)

        wlan.active(False)

        return False

# @brief:       connect to wifi with wdt
# @parameters:  WIFI_COUNT str
#               WIFI_PASSWORD str
# @return:      True or False
#               if not connect to the WI-FI toggle the blue light for three times
#               else keep it bright
def WIFI_Connect_Wdt(WIFI_COUNT, WIFI_PASSWORD, wdt):

    WIFI_LED = Pin(52, Pin.OUT)

    wdt.feed()
    wlan = network.WLAN(network.STA_IF) #STA模式

    if wlan.isconnected():
        wlan.disconnect()

    for i in range(3):
        wlan.connect(WIFI_COUNT, WIFI_PASSWORD)
        if wlan.isconnected():
            break

    if wlan.isconnected():
        wdt.feed()
        WIFI_LED.value(1)
        return True

    else:
        wdt.feed()
        for i in range(3):
            WIFI_LED.value(1)
            time.sleep_ms(300)
            WIFI_LED.value(0)
            time.sleep_ms(300)

        wlan.active(False)

        return False

# @brief:       send a picture to the server usr HTTP
# @parameters:  img : bytes(image)
#               server_host : host
#               server_port : port
#               path : uoloads.php path
# @return:      server message
def upload_photo(img, server_host, server_port, path, filename):
    if img is None:
        print("No image to upload.")
        return

    s = None

    try:
        ai = socket.getaddrinfo(server_host, server_port)
        addr = ai[0][-1]

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(30)
        s.connect(addr)

        boundary = '---------------------------1234567890'.encode()

        body_header = (
            f'--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="{filename}.jpg"\r\n'
            'Content-Type: image/jpeg\r\n\r\n'
        ).encode()

        body_footer = f'\r\n--{boundary}--\r\n'.encode()
        body_content = body_header + img + body_footer

        headers = (
            'POST {p} HTTP/1.1\r\n'
            'Host: {h}:80\r\n'
            'Content-Type: multipart/form-data; boundary={b}\r\n'
            'Content-Length: {cl}\r\n\r\n'
        ).format(
            p=path,
            h=server_host,
            b=boundary,
            cl=len(body_content)
        ).encode()

        s.sendall(headers + body_content)

        function_char = filename.split('_', 1)[0]

        response = s.recv(4096)

        if response == 0:
            return 0,0
        else:
            http_response = response.decode()
            #print(http_response)
            start_index = http_response.find('{')
            end_index = http_response.rfind('}')
            json_content=""
            if start_index != -1 and end_index != -1:
                json_content = http_response[start_index:end_index + 1]
            else:
                return 0, 0

            json_data = json.loads(json_content)

            if function_char == 'A':
                if json_data.get("success") is True:
                    return 1, 0
                else:
                    return 0, 0

            if function_char == 'OC':
                if json_data.get("success") is True:
                    return 1, 0
                else:
                    return 0, 0

            if function_char == 'D':
                if json_data.get("success") is True:
                    return 1, 0
                else:
                    return 0, 0

            if function_char == 'OD':
                if json_data.get("success") is True:
                    return 1, json_data.get("output")[0]
                else:
                    return 0, 0


    except Exception as e:
        print("Upload failed:", e)
        return 0, 0
    finally:

        if s:
            s.close()

if __name__=='__main__':

    WIFI_Connect('szx', '12345678')

    with open("/sdcard/Origin/143322_10.jpg", "rb") as f:
        img_data = f.read()

    get_flag, result = upload_photo(img_data, '****', 80, '/upload.php', 'OD_11f3422f938f32e99ae07fbe9d97ea4f_10')
    print(result)

1 Answers

你好,请更新到prerelease固件,或者v1.2.2版本。