如何在Python中从不同的类调用类方法



我有一个树莓派:

  • Xbee到Arduinos的串行接口
  • WebSocket服务器接口到网页(html/javascript)

我写了一个Python脚本来协调通信(我是Python新手)。它包含:

  • 串行接口类
  • WebSocket接口类

我正试图在网页和Arduinos之间中继数据。具体来说,我试图从串行类调用Websocket类中的"发送"方法,并从Websocket类调用串行类中的"发送"方法。

我花了很多时间阅读和研究,但我就是不明白。这是我的代码现在的样子。我得到的具体错误是"sendSocket()正好接受2个参数(给定3个)。"

# server.py
DEBUG = True;
import serial
import time
import sys
import json
import os
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet import reactor
from twisted.internet import task
# I think I need these for the instances?
global socket, serial
# ---------------------------------
# WebSocket Interface
# ---------------------------------
class HaSocketProtocol(WebSocketServerProtocol):
    # I'm not sure of any other way to incorporate the instance
    global serial
    def __init__(self):
        pass
    def onConnect(self, request):
        debug("Client connected")
    def onOpen(self):
        debug("WebSocket Server Open")
    def onMessage(self, payload, isBinary):
        if not isBinary:
            payload = payload.decode('utf8')
            debug("Incoming socket message: {} -- Writing as-is to xbee".format(payload))
            # Here is where I'm trying to send the data I received out the serial port using the SerialInterface class method
            self.sendSerial(serial, payload)
    def onClose(self, wasClean, code, reason):
        debug("WebSocket connection closed - {}".format(reason))
    # Socket server sending over socket    
    def send(self, message):
        self.sendMessage(message)
    # Here is where I'm trying to link them 
    @classmethod
    def sendSerial(SerialInterface, message):
        SerialInterface.send(message)
# ---------------------------------
# Serial Interface
# ---------------------------------
class SerialInterface:
    xbee = None
    # trying to iunclude the instance
    global socket
    def __init__(self, devname, baud, to):
        self.xbee = serial.Serial(devname, baud, timeout=to)
        debug(self.xbee)
    def check(self):
        incoming = None
        # will timeout if there's no data to be read
        incoming = self.xbee.readline().strip()
        if incoming != None and incoming != "":
            self.handle(incoming)
    # serial send over serial
    def send(self, message):
        self.xbee.write(message)
        self.xbee.write("n")
    # here is where i'm trying to link them    
    @classmethod
    def sendSocket(HaSocketProtocol, message):
        HaSocketProtocol.send(message)        
    def handle(self, incoming):
        debug("Incoming serial: {}".format(incoming))
        # ...
        # my logic is in here that leads to several instances where I
        # create a command string that I send over the serial port
        # ...
        socketMessage = "ArduinoCommand"
        self.sendSocket(socket, socketMessage)
# ------------------------------
# main
# ------------------------------
def main():
    global socket, serial
    serial = SerialInterface('/dev/ttyUSB0', 9600, 1)
    socket = HaSocketProtocol()
    factory = WebSocketServerFactory("ws://localhost:9000", debug=False)
    factory.protocol = socket
    # check Serial port for data every 1 second
    ser = task.LoopingCall(serial.check)
    ser.start(1.0)
    reactor.listenTCP(9000, factory)
    reactor.run()
def debug(msg):
    if DEBUG:
        print "{}n".format(msg)    

main()

我认为你需要在HaSocketProtocol.send()方法上放一个@classmethod "decorator",就像你对其他一些方法一样。

类方法自动获取类:

@classmethod
def myMethod(cls):
   pass

这就是为什么你得到这个错误- 2个参数+ cls = 3。但是这个方法只需要两个。所以你必须添加"cls"参数到sendSocket方法

 @classmethod
    def sendSocket(cls, HaSocketProtocol, message):
        HaSocketProtocol.send(message)        

如果你的方法中不需要cls,用@staticmethod代替@classmethod

注:查看其他类方法

你的类方法应该是这样的:

@classmethod
def sendSocket(cls, hsockprotocol, message):
    hsockprotocol.send(message)

注意第二个参数的变化。它应该只是一个变量,而不是一个类引用。

这个问题实际上是关于如何实现Autobahn框架,而不是关于如何用Python编程。对我来说,用JavaScript重写它并把它放在Node.js上更容易。运行很好。

相关内容

  • 没有找到相关文章

最新更新