Python, Azure IoT 및 Power 애플리케이션을 사용하여 명절 조명 제어

본문은 #PythonFunBites의 일부분이다.
북반구의 밤이 가까워지면서 많은 겨울 축제가 진행되고 있다. 그것들의 공통점은 불빛이다.
과거에 나는 단지 가장 가까운 소매상으로부터 등불을 한 줄 한 줄 사서 나무나 집 주위에 걸고 리모컨이나 버튼으로 내가 원하는 색깔을 얻었다.
올해 나는 사물인터넷으로 전기를 공급하는 명절등을 건설하고 코드가 없는 전력 응용 프로그램이 제어하는 더 좋은 일을 하기로 결정했다.

하드웨어는 WS2812B programmable LED strips(Neopixels)를 기반으로 Raspberry Pi Zero W에 의해 제어될 것이다.소프트웨어 측면에서 Pi는 일부 Python 코드와 Azure IoT Central 대화를 실행할 것이다. IoT 소프트웨어 즉 서비스 플랫폼으로 Pi에 명령을 보내서 불을 켜거나 끌 수 있다.하나Power App는 모바일 응용 프로그램을 통해 사물인터넷 센터를 제어하는 데 사용될 것이다. 코드가 없다!이 모든 클라우드 서비스는 무료로 사용할 수 있으니 더욱 좋다!

You can find a full hands-on guide to building this your self with detailed instructions and all the code in my Neopixel Holiday Lights GitHub Repo


필요한 하드웨어


이 기능을 만들려면 다음 하드웨어가 필요합니다.
  • 인터넷에 연결할 수 있는 복분자 원주율, 예를 들어 원주율 0의 원주율 또는 원주율 3/4의 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율 원주율
  • WS212B 프로그래밍 가능 LED 1개
  • 5v 전원 공급 장치 - USB - 커넥터 카트리지 컨덕터 또는 5v DC 변환기
  • 크로스 컨덕터
  • 하드웨어를 연결하려면 LED의 양극 지시선이나 핀셋을 5v 전원의 양극 단자에 연결하고, 음극 지시선이나 핀셋을 전원의 음극 단자와 Raspberry Pi의 GND GPIO 핀셋에 연결하십시오.이 때문에 일부 LED에는 음극 지시선이 두 개 있습니다. 그렇지 않으면 용접이나 추가 지시선이 필요합니다.마지막으로 제어 탭을 복분자 Pi에 연결하는 GPIO 탭 18입니다.Raspberry Pi GPIO documentation에서pin코드에 대한 상세한 정보를 찾을 수 있습니다.

    Azure IoT Central


    Azure IoT Central는 소프트웨어 즉 서비스 플랫폼으로 귀하가 사물인터넷 응용을 위해 클라우드 인프라와 안전을 구축할 수 있고 코드가 필요하지 않습니다.이것은 장치 템플릿 - 장치가 클라우드로 전송할 수 있는 데이터 설명과 클라우드가 장치에 전송할 수 있는 명령을 기반으로 일부 조작을 지시합니다.
    apps.azureiotcentral.com부터 새 프로그램을 만듭니다.IoT Central 은 유료 서비스이지만 무료로 사용할 수 있습니다.무료 층이 하나 있지만 이 층을 사용해서 만든 응용 프로그램은 7일 후에 삭제되기 때문에 표준 층을 선택합니다.두 표준 계층 모두 2대의 장치를 무료로 제공하므로 비용을 지불하지 않고도 Pi를 제어할 수 있습니다.
    Azure 구독이 있어야만 가입할 수 있기 때문에 없으면 무료로 가입할 수 있습니다.학생은 azure.microsoft.com/free/students에 1년 등록하고 100달러의 학점을 얻으며 매년 재계약을 하지 않으면 azure.microsoft.com/free에 1년 등록하고 200달러의 학점을 받아 30일 동안 지속한다.
    응용 프로그램을 만든 후 두 개의 명령과 한 개의 속성을 사용하여 장치 템플릿을 만듭니다.이러한 명령은 조명을 켜고 끕니다. 속성은 색상을 변경하지 않도록 하기 때문에 Pi를 다시 시작하면 조명이 마지막 색상 세트를 사용하여 다시 켜집니다.
    명령 중 하나 On 를 명명하고 Color 라는 요청 파라미터를 받아들이도록 합니다.요청한 파라미터가 없는 상태에서 다른 명령을 명명합니다. OffColor라는 속성을 string로 만듭니다.이 템플릿을 게시하고 새 장치를 만듭니다.디바이스를 생성한 후 연결 세부 정보를 얻습니다.

    프로그래밍 Pi


    다음 단계는 Pi를 프로그래밍하여 사물인터넷 센터에 연결하고 명령을 받고 불을 켜는 것이다.이것은 파이톤에서 완성할 수 있습니다.Pi가 최신 Raspberry Pi 운영체제와 모든 최신 업데이트를 사용하고 인터넷에 연결되어 있는지 확인하십시오.Lite나 데스크톱 버전을 사용할 수 있습니다. 이 Pi가 헤더가 없는 프로젝트에 대해서는 더 작은 SD 카드를 사용해서 Pi를 더 빨리 시작할 수 있도록 Lite 버전을 사용합니다.

    To program the Pi, you can use your favourite Python tool. I personally recommend using Visual Studio Code, a free, open source developer text editor that has extensions for a variety of languages, including the PyLance extension for Python. If you are using the full desktop version of Raspberry Pi OS, you can , otherwise use the Remote SSH extension to code remotely on a Pi 3 or 4, or the SSH File system extension to code remotely on a Pi Zero.


    먼저 Pip 패키지를 설치해야 합니다.슈퍼 사용자의 실행 코드로 필요한 Neopix를 제어하기 위해 sudo 설치가 필요합니다.다음 구성 요소를 설치합니다.
    rpi_ws281x 
    adafruit-circuitpython-neopixel
    azure-iot-device
    python-dotenv
    
    
    앞의 두 패키지는 LED에 대한 제어를 제공하고azure-iot-device 패키지는 IoT Central에 연결된 장치에 대한 파이톤 코드와 python-dotenv 파일에서 기밀을 불러와서 API 키 등의 내용이 원본 코드로 업로드되지 않도록 한다.
    장치를 설치한 후 Pi의 폴더에 .env라는 파일을 생성하여 IoT 중앙 장치의 연결 세부 정보를 저장하고 다음을 추가합니다.
    ID_SCOPE=<ID scope>
    DEVICE_ID=<device id>
    PRIMARY_KEY=<primary key>
    
    
    IoT 중앙 장치 연결 대화 상자의 ID 범위 값으로 바꿉니다.env.장치 ID로 바꾸기<ID scope>, 키로 바꾸기<device id>.
    다음에 <primary key>라는 파일을 만들고 다음 코드를 추가합니다.the GitHub repo tha accompanies this post에서도 이 코드를 찾을 수 있습니다.
    import asyncio
    import board
    import neopixel
    import os
    from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient
    from azure.iot.device import MethodResponse
    from dotenv import load_dotenv
    
    # Define the NeoPixel strip setting:
    # The pin the control wire is connected to (18 in this code)
    # The length of the strip (150 LEDs in this code)
    # The brightness (0.2 on a scale of 0-1)
    # If the colors are written as soon as the values are updated, or if they need to be
    # updated all at once as soon as the values are set
    pixels = neopixel.NeoPixel(board.D18, 150, brightness=0.2, auto_write=False)
    
    # Load the IoT Central connection details from a .env file
    load_dotenv()
    id_scope = os.getenv('ID_SCOPE')
    device_id = os.getenv('DEVICE_ID')
    primary_key = os.getenv('PRIMARY_KEY')
    
    # Declare the device client so it can be used from all the function
    device_client = None
    
    # Provisions the device with the Azure device provisioning service or returns
    # the connection details if the device is already provisioned
    async def register_device():
        provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
            provisioning_host='global.azure-devices-provisioning.net',
            registration_id=device_id,
            id_scope=id_scope,
            symmetric_key=primary_key,
        )
    
        return await provisioning_device_client.register()
    
    # Sets the color of the Neopixels based on a color string coming in.
    # This color string is a 6 character code, 2 characters for red, 2 for green
    # and 2 for blue. These 2 characters are a HEX value from 00 to FF.
    # For example FF0000 is full red, no green or blue. FFFFFF is white, 000000 is off.
    # Once the color is set, write it back to the IoT Central property via a device twin
    async def set_color(color):
        # split in the color string into the red, green and blue components, and convert these
        # to valid hex strings
        r = '0x' + color[0:2]
        g = '0x' + color[2:4]
        b = '0x' + color[4:6]
    
        # Convert hext to numerical values
        r_value = int(r, 0)
        g_value = int(g, 0)
        b_value = int(b, 0)
    
        print('Updating color: r =', r_value, ', g =', g_value, ', b =', b_value)
    
        # Set all the pixels to the new color
        pixels.fill((r_value, g_value, b_value))
    
        # Show the color on all the pixels
        pixels.show()
    
        # Write the color back as a property
        # Properties are written to the device twin, so patch the reported properties
        # with the color
        patch = {'Color':color}
        print("Sending patch:", patch)
        await device_client.patch_twin_reported_properties(patch)
    
    # IoT Central command handler
    # IoT Central commands are implemented as IoT Hub direct methods
    async def command_handler(method_request):
        print("Message received:", method_request.name)
        print("Message payload:", method_request.payload)
    
        # Determine how to respond to the command based on the IoT Hub direct method method name
        # which is the same as the IoT Central command name
        if method_request.name == "On":
            # For an On request, set the color based on the payload
            await set_color(method_request.payload)
            print("executed on")
        elif method_request.name == "Off":
            # For an Off request, set the color to 000000, which turns the pixels off
            await set_color("000000")
            print("executed off")
        else:
            print("Received unknown method: " + method_request.name)
    
        # Method calls have to return a response so IoT Central knows it was handled correctly,
        # So send a 200 response to show we handled this
        payload = {"result": True}
        status = 200
    
        # Send the response
        method_response = MethodResponse.create_from_method_request(method_request, status, payload)
        await device_client.send_method_response(method_response)
    
    async def property_handler(patch):
        print("Patch received:", patch)
        if 'Color' in patch:
            await set_color(patch['Color'])
    
    # The main async function that runs the app
    async def main():
        global device_client
    
        # Regsiter the Pi as an IoT device in IoT Central
        registration_result = await register_device()
    
        # Build the IoT Hub connection string from the registration details
        # IoT Central sits on top of IoT Hub, and the Python SDK only supports IoT Hub,
        # So to talk to IoT central the IoT Hub connection string needs to be built from details
        # from registering the device with the provisioning service
        conn_str='HostName=' + registration_result.registration_state.assigned_hub + \
                    ';DeviceId=' + device_id + \
                    ';SharedAccessKey=' + primary_key
    
        # The client object is used to interact with your Azure IoT Central app via IoT Hub, so create this 
        # from the connection string
        device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
    
        # Connect the client to IoT Hub
        print('Connecting')
        await device_client.connect()
        print('Connected')
    
        # IoT Central stores properties in the device twin, so read this to see if we have a color
        # stored from the last run for the lights. This way when the device starts up it can set the color
        # to the last setting
        twin = await device_client.get_twin()
        print('Got twin: ', twin)
    
        # Load the color from the reported properties of the twin if it exists
        if 'reported' in twin and 'Color' in twin['reported']:
            await set_color(twin['reported']['Color'])
    
        # Set the method request handler on the client to handle IoT Central commands
        device_client.on_method_request_received = command_handler
    
        # Handle updates to the color property from IoT Central
        device_client.on_twin_desired_properties_patch_received = property_handler
    
        # Define a message loop that keeps the app alive whilst listening for commands
        async def main_loop():
            while True:
                await asyncio.sleep(1)
    
        # Wait for user to indicate they are done listening for method calls
        await main_loop()
    
        # Finally, disconnect
        await device_client.disconnect()
    
    # Start the async app running
    if __name__ == " __main__":
        asyncio.run(main())
    
    
    코드와 주석을 읽고 무엇을 할 수 있는지 봅시다.
    이 코드는 Azure 디바이스 구성 서비스에 연결되며 app.py 파일의 설정을 사용하여 디바이스를 인증하고 연결합니다.색상이 설정되었는지 확인하기 위해 속성을 로드하고 설정된 경우 새 픽셀을 해당 색상으로 설정합니다.그리고 새 픽셀의 색을 바꾸거나 닫기 위해 명령을 정탐합니다.
    다음 명령을 사용하여 코드를 sudo로 실행합니다.
    sudo python3 app.py
    
    
    프로그램이 시작되고 연결됩니다.그런 다음 IoT Central에서 명령을 실행하여 조명을 제어할 수 있습니다.
    On 명령의 색상은 16진수 문자열을 나타내는 문자열 값으로 지정되어야 합니다.R, G, B 값은 각각 0-255(.env-00-FF)로 6자 길이가 됩니다.예를 들어 빨간색FF0000, 녹색00FF00, 파란색0000FF, 노란색FFFF00, 흰색FFFFFF이다.

    Power 애플리케이션 설정


    Power Apps는 로직과 서비스를 연결하는 흐름을 만들고 캔버스에 디자인된 UI에 연결하여 코드가 낮거나 코드가 없는 어플리케이션을 만들 수 있습니다.
    Power Apps 계정을 만들어야 합니다. 없으면 등록할 수 있습니다. community plan이것은 당신에게 자신의 응용 프로그램을 배우고 구축할 수 있는 자유로운 환경을 제공할 것이다.
    Power 응용 프로그램에서 프로세스를 만드는 것부터 시작합니다.템플릿에서 만들기 옵션을 사용하여 Power Apps 버튼을 선택해야 합니다.스트림 이름Turn lights on을 지정하고 V2 커넥터 대신 Azure IoT Central V3 커넥터를 추가합니다.IoT Central 애플리케이션을 선택하고 디바이스 id를 추가하고 디바이스 템플릿을 설정하고 기능을 선택한 다음 On 명령을 선택합니다.새 상자가 나타나고 색상이 명령으로 전달되므로 이 상자를 선택한 다음 나타나는 상자에서 전원 응용 프로그램에서 문의를 선택합니다.그런 다음 스트림을 저장합니다.

    Off 명령에 대한 다른 흐름Turn lights off을 만듭니다.
    절차가 생기면, 프로그램을 만들고, 텍스트 입력과 두 개의 단추를 캔버스에 끌어다 놓고, 열에 정렬합니다.
    텍스트 이름ColorInput을 입력하고 기본값을 삭제하고 프롬프트를 색상으로 변경합니다.
    버튼On의 이름을 지정하고 리본에서 작업 탭을 선택한 다음 전원 자동화 를 선택합니다.팝업 창에서 유동 전조등을 선택합니다.흐름을 추가하는 데 몇 초가 걸립니다.이것이 완성되면 기능 표시줄에 반완전한 기능이 표시됩니다.Text 컨트롤의 ColorInput 속성을 다음으로 전달합니다.
    PowerAppsbutton.Run(ColorInput.Text)
    
    
    다른 버튼의 이름Off을 지정하고 불끄기 프로세스를 추가합니다.이 함수는 매개 변수가 필요하지 않기 때문에 괄호만 닫으면 됩니다.

    Pi에서 응용 프로그램이 실행되는지 확인한 다음 도구 모음의 [응용 프로그램 미리 보기] 버튼을 사용하여 Power 응용 프로그램을 저장하고 테스트합니다.

    완성!


    당신의 응용 프로그램이 지금 완성되었습니다!전등을 어디에 설치하고 Power App을 통해 제어할 수 있습니다.너는 휴대전화에서 그것을 운행할 수 있다.Apple App Store 또는 Google Play Store에서 Power Apps 애플리케이션을 설치하고 로그인하여 애플리케이션을 선택하고 조명을 제어합니다.

    자세히 보기


    Microsoft learn을 통해 Azure IoT Central 및 Microsoft Power 플랫폼에 대한 자세한 내용을 확인할 수 있습니다.Microsoft learn은 Microsoft에서 제공하는 모범 사례 및 자가 지도 학습 플랫폼입니다.
  • Develop IoT Central applications with IoT Central
  • Microsoft Power Platform Fundamentals
  • 11월 16일부터 20일까지 마이크로소프트에서 all things Python의 콘텐츠를 시청한다.dev.to를 계속 시청하여 사물인터넷부터 기계학습까지 다양한 내용을 이해하세요!🐍

    좋은 웹페이지 즐겨찾기