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

时间:2014-08-02 21:04:38

标签: python websocket serial-port

我有一个Raspberry Pi:

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

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

  • 串行接口类
  • WebSocket接口类

我正在尝试在网页和Arduinos之间中继数据。具体来说,我试图从Serial类调用Websocket类中的“send”方法,并从WebSocket类调用Serial类中的“send”方法

我花了很多时间阅读和研究,但我无法弄清楚。这是我现在的代码。我得到的具体错误是“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()

4 个答案:

答案 0 :(得分:0)

我认为你需要把@classmethod" decorator"通过HaSocketProtocol.send()方法,就像你有其他一些方法一样。

答案 1 :(得分:0)

类方法自动获取类:

@classmethod
def myMethod(cls):
   pass

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

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

如果您的方法中不需要cls,请将@classmethod替换为@staticmethod

P.S。检查其他类方法

答案 2 :(得分:0)

你的课堂方法应如下所示:

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

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

答案 3 :(得分:0)

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

相关问题