'Python websocket server, understanding difficulties in OOP
I am trying to improvise a simple WebAPI control using pymodbus, I would like to implement this using websocket. From an example I found on the net, this was tried with the SimpleWebSocketServer module.
Now I have difficulties with the implementation, because I don't know exactly how to work with the class "class Echo(WebSocket):" correctly.
I think I should differentiate the variable "self.data" outside the class "Echo" which is passed from my websocket client using If comparisons?
The problem seems to be that the library pymodbus is not included in the "class echo". Anyway, the program terminates as soon as one of the four variables [relays1, relays1off, relays2, relays2off] is passed by the client. Or rather it does not abort but the socket connection is closed.
Unfortunately I am still relatively inexperienced in OOP, please could someone help me further.
The source of my websocket example is: https://iosoft.blog/2019/07/17/websocket-programming/
Kind regards!
# Websocket
import time
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
UNIT = 0x1
HOST = '192.168.0.50'
PORT = 502
COILBASE = 512 # Coil Output Base Address
import signal, sys
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
PORTNUM = 8001
#state = 0
def main():
client = ModbusClient(host=HOST, port=PORT)
client.connect()
# Websocket class to echo received data
class Echo(WebSocket):
def handleMessage(self):
print("Echoing '%s'" % self.data)
self.sendMessage(self.data)
# command = self.data
# print(command)
# return command
return self.data
# if self.data == "relaiys1":
# print("debug")
# rq = client.write_coil(COILBASE + 0, True, unit= UNIT)
# print("debug")
# elif self.data() == relays1off:
# rq = client.write_coil(COILBASE + 0, False, unit= UNIT)
# elif self.data() == relays2:
# rq = client.write_coil(COILBASE + 1, True, unit= UNIT)
# elif self.data() == relays2off:
# rq = client.write_coil(COILBASE + 1, False, unit= UNIT)
def handleConnected(self):
print("Connected")
def handleClose(self):
print("Disconnected")
if self.data == "relaiys1":
print("debug")
rq = client.write_coil(COILBASE + 0, True, unit= UNIT)
print("debug")
elif self.data() == relays1off:
rq = client.write_coil(COILBASE + 0, False, unit= UNIT)
elif self.data() == relays2:
rq = client.write_coil(COILBASE + 1, True, unit= UNIT)
elif self.data() == relays2off:
rq = client.write_coil(COILBASE + 1, False, unit= UNIT)
# Handle ctrl-C: close server
def close_server(signal, frame):
server.close()
client.close()
sys.exit()
if __name__ == "__main__":
main()
print("Websocket server on port %s" % PORTNUM)
server = SimpleWebSocketServer('', PORTNUM, Echo)
signal.signal(signal.SIGINT, close_server)
server.serveforever()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
