0

我在 twisted 上构建了一个多服务守护程序,它从 django 接收命令,发生的情况是

  1. django视图连接amp服务器
  2. DJango 未发送命令或 AMP 未收到命令

我的问题是我做错了什么

我的代码是:

AMP 服务器

from twisted.protocols.amp import AMP, Command, String

class AmpProcessor(Command):
    arguments = [('proto', String()),
                 ('imei', String()),
                 ('ip', String()),
                 ('port', String()),
                 ('cmmd', String())]
    response = [('answer', String())]

class AMPServer(AMP):


    @AmpProcessor.responder
    def processor(self, proto, imei, ip, port, cmmd):
        print cmmd
        self.factories['proto'].clients['ip'].sendMessage(cmmd)
        return {'answer': 'ok'}

TAC 文件

import os, sys
import ConfigParser
from twisted.application import internet, service
from twisted.internet import protocol, reactor
from listener.TrackerServer import TrackerFactory
from listener.AMPServer import AMPServer
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.application.internet import StreamServerEndpointService

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(PROJECT_DIR)

path = None
config = ConfigParser.ConfigParser()
config.read('protocols.cfg')

application = service.Application("tracker")

factories = {}

for device in config.get('protocols', 'keys').split(','):
    devicer = config.get(device, 'name')
    factories[devicer] = TrackerFactory(devicer)
    internet.TCPServer(int(config.get(device, 'port')), factories[devicer]).setServiceParent(application)

endpoint = TCP4ServerEndpoint(reactor, 8750)
factory = Factory()
factory.protocol = AMPServer
factory.protocol.factories = factories
ampService = StreamServerEndpointService(endpoint, factory)
ampService.setServiceParent(application)

Django 视图

def send_fence_to_device (request):
    device_fence_id = request.GET['device_fence_id']
    device_id = request.GET['device_id']
    fence_id = request.GET['fence_id']
    fnc = Fence.objects.get(id=fence_id)
    dev = Device.objects.get(id=device_id)
    try:
        devLog = dev.devicelog_set.filter(device_id=device_id, status = True).order_by('created').reverse()[:1].all()[0]
        params = simplejson.loads(fnc.other)
        lttdlgtd = simplejson.loads(fnc.points)
        strCommand = ".geo.%s,%s,%s,%s,%s,%s,%s,%s,%s" % (params['identificator'], fnc.name[:4], round(float(lttdlgtd[0][0]), 4), round(float(lttdlgtd[0][1]), 4), round(float(fnc.radius), 4), params['time_to_arrive'], params['fence_class'], params['tolerance'], 1)
        d = connect()
        def connected(protocol):
            return protocol.callRemote(
                AmpProcessor,
                proto='TELCOMIP',
                imei=devLog.ip,
                ip=devLog.ip,
                port=devLog.port,
                command=strCommand)
        d.addCallback(connected)

        def saved(result):
            return HttpResponse(simplejson.dumps(result), mimetype='application/json')
            #print 'Registration result:', result
        d.addCallback(saved)
        #d.addErrback(err, "Failed to register")

        def finished(ignored):
            reactor.stop()
        d.addCallback(finished)
        reactor.run(installSignalHandlers=0)

        #return HttpResponse(simplejson.dumps(1), mimetype='application/json')
    except:
        return HttpResponse(simplejson.dumps(0), mimetype='application/json')



def connect():
    endpoint = TCP4ClientEndpoint(reactor, "127.0.0.1", 8750)
    factory = Factory()
    factory.protocol = AMP
    return endpoint.connect(factory)


class DeviceUnavailable(Exception):
    pass

class AmpProcessor(Command):
    arguments = [('proto', String()),
                 ('imei', String()),
                 ('ip', String()),
                 ('port', String()),
                 ('cmmd', String())]

    response = [('answer', String())]

    errors = {DeviceUnavailable: 'device-unavailable'}
4

1 回答 1

0

每个进程只能调用reactor.run一次。我猜你send_fence_to_device每个请求都会调用一次。这意味着它可能工作一次,但所有后续调用都会失败。

如果您准备在 Django 应用程序中可靠地使用 Twisted,Crochet可能会有所帮助。

于 2013-07-05T00:26:26.473 回答