게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
라즈베리파이 파이썬코드에 while문 썼는데 동작을 안해요
게시물ID : programmer_23407짧은주소 복사하기
작성자 : 싱그러운햇살
추천 : 1
조회수 : 2367회
댓글수 : 3개
등록시간 : 2023/06/17 17:18:10
frompythonosc.osc_serverimportAsyncIOOSCUDPServer
frompythonosc.udp_clientimportSimpleUDPClient
frompythonosc.dispatcherimportDispatcher
importRPi.GPIOasGPIO
importdatetime
importasyncio
# import orjson
importtime


SWITCHES= [13, 19, 29, 33, 40]
RELAY= [11, 12, 15, 16]
STATUS= {'s0': 0, 's1': 0, 's2': 0, 's3': 0, 's4': 0, 'r0': 0, 'r1': 0, 'r2': 0, 'r3': 0}
# STATUS_LIST = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # s0-4, r0-3
SERVER_IP='192.168.1.136'
SERVER_PORT=1234
client=SimpleUDPClient(SERVER_IP, SERVER_PORT)
PRINT=''
VAR=0

defrelay_handler(addr, args):
    print(f"{addr}, {args}")
    relay(args)
    print(STATUS)
    # client.send_message('/switch', list(STATUS.values()))
    return

defdefault_handler(addr, *args):
    print(f"{addr}, {args}")
    return

deftoggle(channel):
    ifGPIO.input(channel) ==GPIO.HIGH:
        STATUS[f's{SWITCHES.index(channel)}'] =0
        # STATUS_LIST[SWITCHES.index(channel)] = 0
    elifGPIO.input(channel) ==GPIO.LOW:
        STATUS[f's{SWITCHES.index(channel)}'] =1
        # STATUS_LIST[SWITCHES.index(channel)] = 1
    else:
        STATUS[f's{SWITCHES.index(channel)}'] =2

    PRINT=str(SWITCHES.index(channel))
    VAR=str(STATUS[f's{SWITCHES.index(channel)}'])

    print(STATUS)
    # client.send_message('/switch', STATUS)
    # client.send_message('/switch', list(STATUS.values()))
    # client.send_message('/switch', 's'+ str(SWITCHES.index(channel))+str(STATUS[f's{SWITCHES.index(channel)}']))
    # client.send_message('/switch', 's'+ str(SWITCHES.index(channel)))
    client.send_message('/switch', 's'+PRINT+VAR)

    # time.sleep(1)


    return


definitialize():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(SWITCHES, GPIO.IN, pull_up_down=GPIO.PUD_UP)
   

    GPIO.setup(RELAY, GPIO.OUT)
    GPIO.output(RELAY, GPIO.HIGH) # turn it off
    forSWITCHinSWITCHES:
        GPIO.add_event_detect(SWITCH, GPIO.RISING, callback=toggle, bouncetime=200)


    return



defrelay(args):
    try:
        index, action=args.split('_')
    except:
        print('WRONG MESSAGE')
        return
    index=int(index[-1])
    iff'r{index}'inSTATUS:
        ifaction=='0':
            STATUS[f'r{index}'] =0
            # STATUS_LIST[SWITCHES.index(f'r{index}')] = 0
            GPIO.output(RELAY[index], GPIO.HIGH)
        elifaction=='1':
            STATUS[f'r{index}'] =1
            # STATUS_LIST[SWITCHES.index(f'r{index}')] = 1
            GPIO.output(RELAY[index], GPIO.LOW)
        else:
            pass
    return


asyncdefloop():
    """Example main loop that only runs for 10 iterations before finishing"""
    whileTrue:
        client.send_message('/allswitch', list(STATUS.values()))
        awaitasyncio.sleep(0)
       



asyncdefinit_main():
    try:
        print('Start Switch')
        initialize()
        dispatcher=Dispatcher()
        dispatcher.map('/relay', relay_handler)
        dispatcher.set_default_handler(default_handler)
        server=AsyncIOOSCUDPServer(('0.0.0.0', 1337), dispatcher, asyncio.get_event_loop())

        transport, protocol=awaitserver.create_serve_endpoint()  # Create datagram endpoint and start serving
        awaitloop()  # Enter main loop of program

    finally:
        GPIO.cleanup()
        print('Finishing')
        transport.close()  # Clean up serve endpoint



asyncio.run(init_main())


whileTrue:
    client.send_message('/allswitch', list(STATUS.values()))
 
 
여기 끝에 반복문 달았는데요
그럼 컴퓨터 서버로 스위치의 상태가 리스트형태로 계속 와야하는데
오질 않아서요..
 
while True:
client.send_message~~
 
이부분을 어디에 넣어야 반복문이 돌아갈까요?

 
전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호