DesignSpark Electrical Logolinkedin
菜单 搜寻
提问问题

更为简单的方案 - Cypress WiFi-BT Pioneer 套件嵌入式网络

随着对“智能化”普及营销的关注,说一句并非每个“联网”应用程序都需要云,似乎有悖于时代发展。

有时,嵌入式设备只需从已知位置检索数据或通过局域网与其他设备通信足矣。例如,您可能只需要让别人使用网络浏览器通过本地网络查询您的设备。

借助一些功能强大的库,这些类型的交互可使用 Python 创建,只需短短几行代码,就能轻松尝试不同的方法并找到最适合的一种。在相同的时间内,通常只能完成其中一种交互编码。

Zerynth 工具链提供大量实用的代码示例,您可以在这些示例的基础上创建自己的定制应用程序,使过程更加简单。在今天的文章中,我们将通过使用 Cypress WiFi-BT Pioneer 套件 (175-4669) 探讨其中部分内容,该套件也是 Zerynth“家族”板套件的最新成员。

入门

假设您已经安装了 Zerynth,并按照 Pioneer 套件设置说明进行操作,包括连接、注册和虚拟化设备。

完成后,我们可以自由地将任何示例程序加载到电路板上。如上所述,示例程序有很多,通过单击 IDE 项目窗口左侧的“灯泡”图标即可找到。现在让我们来进行这项操作,并从“网络”部分选择一个示例:

小型网络服务器

我从小型网络服务器示例开始,因为它展示了如何使用 HTML,以用户可读取的格式向用户远程显示信息的基本要素。使用示例时,需要单击“Clone(复制)”按钮并将它保存到自己的项目目录中。我们可以重命名项目,还可以将它移动至硬盘上的任何位置。

现在我们有了自己的副本,可以对它进行修改以适应电路板。我们只需要做两件事:

  1. 为板上的 WiFi 设备导入正确的驱动程序。这只需要一行代码。
  2. 在程序中输入网络凭据,使它连接至网络。我对代码的修改有点超过必要程度,因为我希望该信息位于程序文件的顶部,以便可在不同位置查找和更改代码。

现在我们尝试一下。

###############################################################################
# Mini Web Server
#
# Created by Zerynth Team 2015 CC
# Authors: G. Baldi, D. Mazzei
###############################################################################

# import streams & socket
import streams
import socket

# import the wifi interface
# the wifi module needs a networking driver to be loaded
# in order to control the board hardware.
from wireless import wifi
from murata.lbee5kl1dx import lbee5kl1dx as wifi_driver

NetName = "Network_Name"
NetPassword = "Network_Password"


streams.serial()

# init the wifi driver!
# The driver automatically registers itself to the wifi interface
# with the correct configuration for the selected board
wifi_driver.auto_init()
# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link(NetName,wifi.WIFI_WPA2,NetPassword)
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)

# Yes! we are connected
print("Linked!")

# Let's print our ip, it will be needed soon
info = wifi.link_info()
print("My IP is:",info[0])

# Now let's create a socket and listen for incoming connections on port 80
sock = socket.socket()
sock.bind(80)
sock.listen()


while True:
    try:
        # Type in your browser the board ip!
        print("Waiting for connection...")
        # here we wait for a connection
        clientsock,addr = sock.accept()
        print("Incoming connection from",addr)

        # yes! a connection is ready to use
        # first let's create a SocketStream
        # it's like a serial stream, but with a socket underneath.
        # This way we can read and print to the socket
        client = streams.SocketStream(clientsock)

        # let's read all the HTTP headers from the browser
        # stop when a blank line is received
        line = client.readline()
        while line!="\n" and line!="\r\n":
            line = client.readline()
        print("HTTP request received!")

        # let's now send our headers (very minimal)
        # hint: \n is added by print
        print("HTTP/1.1 200 OK\r",stream=client)
        print("Content-Type: text/html\r",stream=client)
        print("Connection: close\r\n\r",stream=client)
        # see? as easy as print!
        print("<html><body>Hello Zerynth!",random(0,100),"</body></html>",stream=client)
        # close connection and go waiting for another one
        client.close()
    except Exception as e:
        print("ooops, something wrong:",e)

附注:如果您手头没有电路板,仍然可以编译(或“验证”)代码,以确保语法正确无误。您可以单击主窗口上方的“Device:(设备:)”框来执行此操作。单击选择虚拟设备并(本例中)选择 PSoC6 WiFi-Bt Pioneer 套件,然后点击列表底部的“Set(设置)”按钮。然后就可以开始了。单击“Verify(验证)”按钮(设备框左侧 3 个按钮中最左边的一个),开始编译代码 - 希望没有错误。

要将代码导入到板上,我们需要单击上传按钮 -“Device(设备)”框左侧 3 个按钮中间的一个。这样将开始代码编译和上载。在此过程中,在加载新程序之前,将擦除电路板存储器。

自动擦除可能需要一段时间,因此如果在约 30 秒内没有任何反应,无需担心。

加载后的程序将开始运行,您可以通过单击“Device(设备)”框右侧按钮组最右边的一个来打开控制台窗口查看反馈。

如果在与 PSoC6 位于同一网络的 PC 上打开网络浏览器,并将控制台窗口中的 IP 地址输入到浏览器的地址栏中,我们将收到一条消息:

太棒了!我们收到了预期的消息和随机数。现在,我们可以简单尝试其他示例。

HTTP 时间

这次,我们从远程源获取一些数据。时间怎么样?我们可以像之前一样打开示例:

然后,我们复制示例并做出与之前相同的修改:

程序加载后将与服务器联系,然后从服务器中提取时间数据并显示在控制台窗口中:

工作时间

当然,我们可以将这些代码示例作为任何工作的基础,从而快速构建自己的示例。如果我们希望设备从服务器获取一些数据,并在网络浏览器中向用户显示,该怎么做?我们可以合并示例,如下所示:

###############################################################################
# Mini Time Web Server
###############################################################################

# import streams & socket
import streams
import socket
import json
import requests

# import the wifi interface
from wireless import wifi
from murata.lbee5kl1dx import lbee5kl1dx as wifi_driver
#from espressif.esp32net import esp32wifi as wifi_driver

NetName = "Network_Name"
NetPassword = "Network_Password"

def getTime():
    for i in range(3):
        try:
            print("Trying to connect to time server...")
            # go get that time!
            # url resolution and http protocol handling are hidden inside the requests module
            response = requests.get('http://now.zerynth.com/')
            
            # let's check the http response status: if different than 200, something went wrong
            print("Http Status:",response.status)
            # if we get here, there has been no exception, exit the loop
            
            js = json.loads(response.content)
            StrDate = ("Date:",js['now']['rfc2822'][:16])
            StrTime = ("Time:",js['now']['rfc2822'][17:])
            return StrDate,StrTime
        except Exception as e:
            print("Error while getting date and time")
            print(e)

            
streams.serial()

# init the wifi driver!
# The driver automatically registers itself to the wifi interface
# with the correct configuration for the selected board
wifi_driver.auto_init()
# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link(NetName, wifi.WIFI_WPA2, NetPassword)
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)

# Yes! we are connected
print("Linked!")

# Let's print our ip, it will be needed soon
info = wifi.link_info()
print("My IP is:",info[0])

# Now let's create a socket and listen for incoming connections on port 80
sock = socket.socket()
sock.bind(80)
sock.listen()


while True:
    try:
        # Type in your browser the board ip!
        print("Waiting for connection...")
        # here we wait for a connection
        clientsock,addr = sock.accept()
        print("Incoming connection from",addr)

        # yes! a connection is ready to use
        # first let's create a SocketStream
        # it's like a serial stream, but with a socket underneath.
        # This way we can read and print to the socket
        client = streams.SocketStream(clientsock)

        # let's read all the HTTP headers from the browser
        # stop when a blank line is received
        line = client.readline()
        while line!="\n" and line!="\r\n":
            line = client.readline()
        print("HTTP request received!")


        # let's now send our headers (very minimal)
        # hint: \n is added by print
        print("HTTP/1.1 200 OK\r",stream=client)
        print("Content-Type: text/html\r",stream=client)
        print("Connection: close\r\n\r",stream=client)
        StrD, StrT = getTime()

        # see? as easy as print!
        print(StrD,"",stream=client)
        print(StrT,"",stream=client)
        
        print("\r\n\r",stream=client)
        # close connection and go waiting for another one
        client.close()
    except Exception as e:
        print("ooops, something wrong:",e)

在自己的平台上尝试运行此示例。恭喜第一位在评论中添加链接,展示输出成果的用户!

在此基础上,我们可以加以扩展,以获得实际需要的数据(例如,最新的可用固件版本),以及将浏览器外观设置成终端应用中显示的样子,例如将当前的固件与最新版本进行比较。

结语

无论使用哪种硬件平台,我都喜欢在 Zerynth 上运行简短的 Python 程序,不仅速度快、乐趣十足,而且很快就能看到结果。

Mark completed his Electronic Engineering degree in 1991 and went on to work in real-time digital signal processing applications engineering, later moving into technical marketing.

3 Sep 2019, 6:55