webOS Article/4. webOS 활용하기

webOS와 websocket을 이용하여 LED 제어하기 4 : websocket server

Nahye0n 2021. 8. 5. 23:16

WebSocket server


  • 전체 시스템 소개
  • ESP+LED+websocket
  • Enact webapplication
  • websocket server
  • 시스템 연동

1. 개요

코드를 보면, 크게 SimpleEcho와 SimpleIoT 로 나눌 수 있습니다. 

class SimpleEcho(WebSocket):

SimpleEcho는 반사, 반환을 하는 것입니다.

socket server ESP 간의 신호를 전송할 때, ESP에서 신호가 server로 간 뒤, 바로 ESP에 반사되어 전송되는 것입니다.

class SimpleIoT(WebSocket):

SimpleIoT는 socket server와 ESP, Enact-app간의 신호를 교환힙니다.

 'msgType' : 'status'

msgType이 'status'인 경우, 신호는 ESP 자기자신을 제외하고 server와 Enact-app에 전송됩니다.

  'msgType' : 'command'

msgType 'Command'인 경우는 Enact-app 제외하고 server와 ESP에 전송됩니다.

 

 

 

2. 코드 설명

  • SimpleEcho 코드
class SimpleEcho(WebSocket):
    def connected(self):
        print(self.address, 'connected')
        self.send_message('Hi')

 

server ESP가 최초로 연결되어있을 때, 'Hi'라는 메세지를 출력합니다.

 

    def handle(self):
        print(self.address, 'Recieve', self.data)
        if(self.data == 'On'):
            msg = {
                'msgType' : 'status',
                'deviceID' : 'CML0001',
                'ledStatus' : 'On'
            }
        else:
            msg = {
                'msgType' : 'status',
                'deviceID' : 'CML0001',
                'ledStatus' : 'Off'
            }
        self.send_message(json.dumps(msg, indent=4))
        print('Response', msg)

'handle'의 경우, led가 “On”이라면 server와 Enact-app에게 'ledStatus'가 'on' 상태를 전송합니다.

나머지 경우에는  'ledStatus'가 'off' 상태 전송합니다.

 

 

  • SimpleIoT 코드
class SimpleIoT(WebSocket):
    def connected(self):
        print(self.address, 'connected')
        msg = {
            'msgType' : 'command',
            'deviceID' : 'CML001',
            'ledStatus' : 'Off'
        }
        self.send_message(json.dumps(msg, indent=4))
        clients.append(self)

'connected' 경우에는 msgtype 'command'로 server와 ESP에게 'ledStatus'가 'off' 상태를 전송합니다.

 

 

    def handle(self):
        print(self.address, 'Receive', self.data)
        
        for client in clients:
            if client != self:        

                print('Send', self.data)
                client.send_message(self.data)

    def handle_close(self):
        clients.remove(self)

'handle'인 경우, for문을 돌면서 client가 자기 자신을 제외한 모든 클라이언트에게 자신의 정보를 전송합니다.