WinFuture-Forum.de: Python TCP asynchat Kommunikation mit anderen Programmen - WinFuture-Forum.de

Zum Inhalt wechseln

Nachrichten zum Thema: Entwicklung
Seite 1 von 1

Python TCP asynchat Kommunikation mit anderen Programmen


#1 Mitglied ist offline   Paradise 

  • Gruppe: aktive Mitglieder
  • Beiträge: 640
  • Beigetreten: 13. September 06
  • Reputation: 43
  • Geschlecht:Männlich
  • Wohnort:Nähe Frankfurt
  • Interessen:Audio-Animatronic, Arduino, Konsolen, Handhelds, Elektronik, Computer, Bodybuilding, Web design, 3D CAD...

geschrieben 12. November 2014 - 17:16

Hi,

ich bin neu was Python betrifft und vielleicht hab ich ja hier glück und es ist ein Python Guru unterwegs.
Ich habe zwar was am laufen wo Python der client ist und sich zum Programm (TCP server) verbindet,
aber ich brauche es andersherum.
Z.b. Zoomplayer ist der server und Python der client:
import asynchat
import asyncore
import socket
import paho.mqtt.client as mqtt
import threading

MQTT_SERVER = "192.168.0.14"
MQTT_PORT = 1883
MQTT_KEEPALIVE = 60
ZOOM_PLAYER_TCP_IP = "127.0.0.1"
ZOOM_PLAYER_PORT = 4769
CRLF = '\r\n'

class ZoomPlayerSession(asynchat.async_chat):

    def __init__(self, host, port):
        asynchat.async_chat.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))

        self.set_terminator(b'\r\n')
        self.buffer = []

    def handle_connect(self):
        # Called when the active opener's socket actually makes a connection.
        print("ZoomPlayer Connected")       

    def handle_close(self):
        # Called when the socket is closed.
        print("ZoomPlayer Connection Lost")
        self.close()

    def collect_incoming_data(self, data):
        self.buffer.append(data.decode('utf-8'))

    def found_terminator(self):
        msg = ''.join(self.buffer)
        print('Received: ' + msg)
        self.buffer = []


def on_connect(mqttc, obj, flags, rc):
    print("Johnny Five connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    mqttc.subscribe("skulltronics.net/hive/parlor/Johnny-Five/#", qos=1)
    mqttc.publish("skulltronics.net/status/Johnny-Five", "Johnny Five is alive", qos=0, retain=True);


def on_message_to_zoom_player(mosq, obj, msg):
    print(msg.topic+" "+str(msg.payload, 'utf-8'))
    if (str(msg.payload) == "5100 fnStop"):
        client.push("5100 fnStop" + CRLF)
        client.push("5100 fnMinimize" + CRLF)
    #elif (str(msg.payload) == "5100 fnStop"):
        #client.push("5100 fnMinimize" + CRLF)
        #client.push(msg.payload + CRLF)
    else:
        #client.push("5100 fnBringToFront" + CRLF)
        client.push(msg.payload + bytes(CRLF, 'utf-8'))


def on_message(mosq, obj, msg):
    # This callback will be called for messages that we receive that do not
    # match any patterns defined in topic specific callbacks.
    print(msg.topic+" "+str(msg.payload))


client = ZoomPlayerSession(ZOOM_PLAYER_TCP_IP, ZOOM_PLAYER_PORT)

comm = threading.Thread(target=asyncore.loop)
comm.daemon = True
comm.start()

mqttc = mqtt.Client(client_id="Johnny-Five", clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
mqttc.will_set("skulltronics/LastWill/Johnny-Five", payload="Sorry, I seem to have died.", qos=0, retain=False)
mqttc.message_callback_add("skulltronics.net/hive/parlor/Johnny-Five/ZoomPlayer/#", on_message_to_zoom_player)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.connect(MQTT_SERVER, MQTT_PORT, MQTT_KEEPALIVE)

mqttc.loop_forever()

Per MQTT kann ich befehle an Zoomplayer senden und das funktioniert auch alles.
Nun habe ich das gefunden "http://www.grantjenks.com/wiki/random/python_asynchat_chat_example" und versuche daraus was zu machen. Aber chat_client_read.py empfängt nichts.
Muss dazu sagen das ich es für Python 3 angepasst habe.

Nun habe ich mal angefangen etwas zu versuchen:
import asynchat
import asyncore
import socket
import paho.mqtt.client as mqtt
import threading


MQTT_SERVER = "192.168.0.14"
MQTT_PORT = 1883
MQTT_KEEPALIVE = 60
ZOOM_PLAYER_TCP_IP = "127.0.0.1"
ZOOM_PLAYER_PORT = 4769
CRLF = '\r\n'
chat_room = {}

class ChatHandler(asynchat.async_chat):

    def __init__(self, sock):
        asynchat.async_chat.__init__(self, sock=sock, map=chat_room)

        self.set_terminator(b'\r\n')
        self.buffer = []        

    def handle_close(self):
        # Called when the socket is closed.
        print("ZoomPlayer Connection Lost")
        self.close()

    def collect_incoming_data(self, data):
        self.buffer.append(data.decode('utf-8'))

    def found_terminator(self):
        msg = ''.join(self.buffer)
        print('Received: ' + msg)
        for handler in chat_room.items():
            if hasattr(handler, 'push'):
                handler.push((msg + CRLF).encode('utf-8'))
        self.buffer = []

class ChatServer(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self, map=chat_room)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            print('Incoming connection from %s' % repr(addr))
            handler = ChatHandler(sock)

def on_connect(mqttc, obj, flags, rc):
    print("Johnny Five connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    mqttc.subscribe("skulltronics.net/hive/parlor/Johnny-Five/#", qos=1)
    mqttc.publish("skulltronics.net/status/Johnny-Five", "Johnny Five is alive", qos=0, retain=True);


def on_message_to_zoom_player(mosq, obj, msg):
    print(msg.topic+" "+str(msg.payload, 'utf-8'))
    if (str(msg.payload) == "5100 fnStop"):
        client.push("5100 fnStop" + CRLF)
        client.push("5100 fnMinimize" + CRLF)
    #elif (str(msg.payload) == "5100 fnStop"):
        #client.push("5100 fnMinimize" + CRLF)
        #client.push(msg.payload + CRLF)
    else:
        #client.push("5100 fnBringToFront" + CRLF)
        server.push(msg.payload + bytes(CRLF, 'utf-8'))


def on_message(mosq, obj, msg):
    # This callback will be called for messages that we receive that do not
    # match any patterns defined in topic specific callbacks.
    print(msg.topic+" "+str(msg.payload))


server = ChatServer('localhost', 4769)

comm = threading.Thread(target=asyncore.loop(map=chat_room))
comm.daemon = True
comm.start()

mqttc = mqtt.Client(client_id="Johnny-Five", clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
mqttc.will_set("skulltronics/LastWill/Johnny-Five", payload="Sorry, I seem to have died.", qos=0, retain=False)
mqttc.message_callback_add("skulltronics.net/hive/parlor/Johnny-Five/ZoomPlayer/#", on_message_to_zoom_player)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.connect(MQTT_SERVER, MQTT_PORT, MQTT_KEEPALIVE)

mqttc.loop_forever()

Aber damit startet mein MQTT client nicht mehr.
Ich brauche eigentlich TCP server und client in einem.
So das ich das empfangene von z.b. Zoomplayer mit MQTT weiter senden und andersrum per MQTT Befehle hin senden kann.
Zoomplayer kann sich natürlich selbst mit einem TCP server verbinden und hab ich nur einen server
dann funktioniert das auch. Aber beides kombinieren macht mir Probleme.
Ich würde sagen, ungefähr ein halbes Gramm zu schwer am Griff.

You know the problem with these gyms now? Health clubs for waffle eatin’ pussies.
0

Anzeige



Thema verteilen:


Seite 1 von 1

1 Besucher lesen dieses Thema
Mitglieder: 0, Gäste: 1, unsichtbare Mitglieder: 0