Exemplo n.º 1
0
 def __init__(self):
     self.tcp_connection = Tcp(IP, TCP_PORT1)
     self.tcp_connection2 = Tcp(IP, TCP_PORT2)
     self.udp_connection = Udp(IP, UDP_PORT1)
     self.udp_connection2 = Udp(IP, UDP_PORT2)
     self.data = SOME_DATA
     pass
Exemplo n.º 2
0
 def __init__(self):
     super(ClientApp, self).__init__()
     self._cfg = Config("config.ini")
     self._cfg.loadFile()
     self.cfgToInputBoxes()
     rpiIp = self._cfg._rpiIp
     rpiPort = int(self._cfg._rpiPort)
     self._tcp = Tcp(port=rpiPort, bufferLen=1024, ip=rpiIp)
Exemplo n.º 3
0
 def __init__(self, parent, fps=30):
     Tcp.__init__(self, "capture:")
     wx.Panel.__init__(self, parent)
     # parent.SetSize((640, 480))
     self.fps = fps
     self.timer = wx.Timer(self)
     self.timer.Start(1000. / self.fps)
     self.Bind(wx.EVT_PAINT, self.OnPaint)
     self.Bind(wx.EVT_TIMER, self.NextFrame)
Exemplo n.º 4
0
 def __init__(self, width, height):
     Tcp.__init__(self, "command:")
     self.width, self.height = width, height
     self.hm = pyHook.HookManager()
     self.hm.KeyDown = self.onKeyboardEvent
     self.hm.MouseAll = self.onMouseEvent
     self.time = time.time()
     self.holder_1 = 90
     self.holder_2 = 90
Exemplo n.º 5
0
 def on_btnSaveConfig_click(self):
     self.updateSettings()
     popup = Popup(title='Settings',
                   content=Label(text='Saved!'),
                   size_hint=(None, None),
                   size=(410, 410))
     popup.open()
     rpiIp = self._cfg._rpiIp
     rpiPort = int(self._cfg._rpiPort)
     self._tcp = Tcp(port=rpiPort, bufferLen=1024, ip=rpiIp)
Exemplo n.º 6
0
 def connectServer(self, address, port):
     if Tcp.connectServer(self, address, port):
         self.frame = self.recvFrame()
         height, width = self.frame.shape[:2]
         self.bmp = wx.BitmapFromBuffer(width, height, self.frame)
         return True
     else:
         return False
Exemplo n.º 7
0
def listen_tcp():
    """Listen on requested port for TCP DNS requests"""
    try:
        common, tcp = Common(), Tcp()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((common.proxy_host(), int(common.proxy_port())))
        sock.listen(2)
        logging.info('Listening for TCP requests')
        while True:
            conn, addr = sock.accept()
            data = conn.recv(1024)
            thread.start_new_thread(tcp.handler, (data, addr, sock, conn, "tcp"))
    except Exception as e:
        logging.error(e)
        sock.close()
Exemplo n.º 8
0
def listen_tcp(address, port, dns, ca):
    """ Listening for DNS TCP requests """
    logging.info(
            "LISTENING TCP: %d",
            os.getpid()
            )
    try:
        tcp = Tcp()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((address, port))
        sock.listen(2)
        while True:
            conn, addr = sock.accept()
            data = conn.recv(1024)
            threading.Thread(
                    target=tcp.handler,
                    args=(data, addr, conn, dns, ca)
                    ).start()
    except Exception as e:
        logging.error(e)
    finally:
        sock.close()
Exemplo n.º 9
0
 def __init__(self, address):
     Tcp.__init__(self, address, "command:")
Exemplo n.º 10
0
 def __init__(self, address):
     Tcp.__init__(self, address, "capture:")
     self.frame = None
Exemplo n.º 11
0
class DroneControl:
    def __init__(self):
        self.tcp_connection = Tcp(IP, TCP_PORT1)
        self.tcp_connection2 = Tcp(IP, TCP_PORT2)
        self.udp_connection = Udp(IP, UDP_PORT1)
        self.udp_connection2 = Udp(IP, UDP_PORT2)
        self.data = SOME_DATA
        pass

    def reset_data(self):
        self.data = SOME_DATA

    def disconnect(self):
        pass

    async def loop(self):
        asyncio.create_task(self.tcp_connection.connect())
        asyncio.create_task(self.tcp_connection2.connect())

        await asyncio.gather(self.udp_connection.connect(),
                             self.udp_connection2.connect())

        asyncio.create_task(
            self.keep_sending_data(self.udp_connection, HAND_SHAKE))

        handshake = False
        while True:
            if not handshake:
                try:
                    print(
                        f"Sending Handshake to {self.udp_connection.ip}:{self.udp_connection.port}"
                    )
                    self.udp_connection2.send(SECOND_HANDSHAKE)
                    handshake = True
                    print("Handshake succeeded")
                except ConnectionRefusedError:
                    print("Sending Handshake failed")

            try:
                # print(SOME_DATA_test)
                # print(self.make_packet(SOME_DATA))
                self.udp_connection2.send(self.make_packet(self.data))
            except ConnectionRefusedError:
                print("Sending data failed")
            await asyncio.sleep(0.05)

    def checksum(self, data):
        return_data = (data[1] ^ data[2] ^ data[3] ^ data[4] ^ data[5]) & 0xFF
        return return_data

    def make_packet(self, data):
        data = DATA_HEAD + data + bytearray(bytes([self.checksum(data[:])
                                                   ])) + bytearray(b'\x33')
        # print(data)
        return data

    async def keep_sending_data(self, connection, data):
        while True:
            try:
                connection.send(data)
            except ConnectionRefusedError:
                pass
            finally:
                await asyncio.sleep(1)
Exemplo n.º 12
0
    def dissect(self, ip):
        pip = {}
        ip_flags = {}


        pip["layer"] = 3

        if isinstance(ip, dpkt.ip.IP):  # RFC 791
            pip["protocol_name"] = "IP4"
            pip["ver"] = ip.v_hl
            pip["headsize"] = (ip.v_hl & (0b00001111))  # TODO not present in dpkt.ip.IP (maybe computed)
            pip["tos"] = ip.tos
            pip["pktsize"] = ip.len
            pip["id"] = ip.id
            #pip["flags"] = (ip.off & (0b1110000000000000))>>13  # TODO not present in dpkt.ip.IP (maybe computed)
            ip_flags["reserved"] = (ip.off & (0b1000000000000000))>>15   # TODO not present in dpkt.ip.IP (maybe computed)
            ip_flags["do_not_fragment"] = (ip.off & (0b01000000000000000))>>14  # TODO not present in dpkt.ip.IP (maybe computed)
            ip_flags["more_fragments"] =(ip.off & (0b0010000000000000))>>13  # TODO not present in dpkt.ip.IP (maybe computed)
            pip["flags"] = ip_flags
            pip["offset"] = (ip.off & (0b0001111111111111))<<3
            pip["ttl"] = ip.ttl
            pip["prot"] = ip.p
            pip["ipsum"] = ip.sum
            pip["opts"] = ''  # setted this way on dpkt.ip.IP
            pip["src"] = socket.inet_ntoa(ip.src)
            pip["dst"] = socket.inet_ntoa(ip.dst)
        elif isinstance(ip, dpkt.ip6.IP6):
            pip["protocol_name"] = "IP6"
            pip["procotol"] = "IP"
            pip["ver"] = ip.v
            pip["prio"] = ''  # TODO not present in dpkt.ip6.IP6 (maybe computed)
            pip["flow"] = ''  # TODO not present in dpkt.ip6.IP6 (maybe computed)
            pip["paylen"] = ip.plen
            pip["nexthead"] = ip.nxt
            pip["hoplim"] = ip.hlim
            pip["src"] = socket.inet_ntop(socket.AF_INET6, ip.src)
            pip["dst"] = socket.inet_ntop(socket.AF_INET6, ip.dst)
        if tcp.check(ip.p):
            _tcp = ip.data
            if not isinstance(_tcp, dpkt.tcp.TCP):
                _tcp = dpkt.tcp.TCP(_tcp)
            # if exists data of type TCP realize parser
            # RFC 793
            if len(_tcp.data) > 0:
                pip["payload"] = tcp.dissect(_tcp)

        # if payload of IP is a package UDP
        elif udp.check(ip.p):
            _udp = ip.data
            if not isinstance(_udp, dpkt.udp.UDP):
                _udp = dpkt.udp.UDP(_udp)

            if len(_udp.data) > 0:
                pip["payload"] = udp.dissect(_udp)

        # if payload of IP is a package ICMP
        elif icmp.check(ip.p):
            _icmp = ip.data
            if not isinstance(_icmp, dpkt.icmp.ICMP):
                _icmp = dpkt.icmp.ICMP(_icmp)

            if len(_icmp.data) > 0:
                pip["payload"] = icmp.dissect(_icmp)  # Populate Dictionary ICMP founded and parsed
        else:
            pip["payload"] = "unknown protocol on layer" + str(pip["layer"]+1)

        return pip
Exemplo n.º 13
0
author:		Michael Binder
dependencies:	tcp.py, RPi.GPIO, sys
description:	Establishes a connection via Tcp/Ip in the local network 
		and waits for messages sent from the app.
		Then it evaluates those messages and sends them via the connected 433MHz RF-Module
		to the 433MHz receivers (eg. 433MHz outlets)
"""

from tcp import Tcp
import RPi.GPIO as gpio
import sys

from rfDevice import RFDevice


myTcp=Tcp(port=5000, bufferLen=1024, ip="0.0.0.0")
myTcp.bindSocket("0.0.0.0")



def isOutputPinHigh(pin):
    return gpio.input(pin)


print("Server running:")
print("")

rfdevice = RFDevice(17)
rfdevice.enable_tx()
success=rfdevice.tx_code(1361)
rfdevice.cleanup()
Exemplo n.º 14
0
 def __init__(self):
     Tcp.__init__(self, 'command:')
     self.ser = None
     self.isConnectToArduino = False
Exemplo n.º 15
0
class IrcConnector(object):
    _conn = None

    def __init__(self):
        self._nick = c.nick
        self._channels = c.channels
        self._server = c.server
        self._port = c.port
        self._queue = queue.Queue()
        self._outputQueue = queue.Queue()

        self._connect()

    def _connect(self):
        self._conn = Tcp(self._server, self._port)
        gevent.spawn(self._conn.connect)

        self.nick = self._nick
        self.cmd("USER", (self.nick, " 3 ", "* ", "Wat Who Where"))

    def _disconnect(self):
        self._conn.disconnect()

    def _reconnect(self):
        self._disconnect()
        self._connect()

    def run(self):
        jobs = [gevent.spawn(self.watch), gevent.spawn(self.send)]

    def watch(self):
        while True:
            line = self._conn.iqueue.get()
            if line[:4] == "ERROR":
                self._reconnect()
            try:
                prefix = ""
                trailing = []
                s = line

                if not s:
                    raise exc.IrcNullMessage("Received an empty line from the server.")

                if s[0] == ":":
                    prefix, s = s[1:].split(" ", 1)
                    name = prefix.split("!~")[0]

                if s.find(" :") != -1:
                    s, trailing = s.split(" :", 1)
                    args = s.split()
                    args.append(trailing)

                else:
                    args = s.split()

                command = args.pop(0)
                channel = args.pop(0)
                said = "".join(args)

                data = {"cmd": command, "channel": channel, "who": name, "said": said}

                logger.debug(data)

                if command == "433":  # nick in use
                    self.nick = self.nick + "_"

                elif command == "PING":
                    self.cmd("PONG", data["said"])

                elif command == "001":
                    if type(self._channels) is list:
                        for chan in self._channels:
                            self.cmd("JOIN", chan)
                    else:
                        self.cmd("JOIN", self._channels)

                elif command == "ERROR":
                    self._reconnect()

                elif command == "PRIVMSG":
                    self._queue.put(data)

            except exc.IrcNullMessage:
                logger.debug("Null message")

    def send(self):
        while True:
            what = self._outputQueue.get()
            if "action" not in what:
                self.reply(what["msg"], what["channel"])
            else:
                self.cmd(what["action"], (what["channel"] + " :" + what["msg"]))

    @property
    def nick(self):
        return self._nick

    @nick.setter
    def nick(self, value):
        self._nick = value
        self.cmd("NICK", self.nick)

    def join(self, channels=None):
        if channels is None:
            channels = self._channels
        if type(channels) is list:
            for chan in channels:
                self.cmd("JOIN", chan)
        else:
            self.cmd("JOIN", channels)

    def reply(self, msg, channel):
        self.cmd("PRIVMSG", (channel + " :" + msg))

    def msg(self, who, msg):
        self.cmd("PRIVMSG", (who + " :" + msg))

    def cmd(self, command, args):
        s = command + " " + "".join(args)

        logger.debug(s)
        self._conn.oqueue.put(s)
Exemplo n.º 16
0
 def __init__(self, CAMERA=0, IMG_QUILITY=80, captureInterval=0.01):
     Tcp.__init__(self, "capture:")
     self.CAMERA, self.IMG_QUILITY = CAMERA, IMG_QUILITY
     self.encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), self.IMG_QUILITY]
     self.capture = cv2.VideoCapture(self.CAMERA)
     self.captureInterval = captureInterval
Exemplo n.º 17
0
    def _connect(self):
        self._conn = Tcp(self._server, self._port)
        gevent.spawn(self._conn.connect)

        self.nick = self._nick
        self.cmd("USER", (self.nick, " 3 ", "* ", "Wat Who Where"))
Exemplo n.º 18
0
class ClientApp(TabbedPanel):
    def __init__(self):
        super(ClientApp, self).__init__()
        self._cfg = Config("config.ini")
        self._cfg.loadFile()
        self.cfgToInputBoxes()
        rpiIp = self._cfg._rpiIp
        rpiPort = int(self._cfg._rpiPort)
        self._tcp = Tcp(port=rpiPort, bufferLen=1024, ip=rpiIp)

    def updateSettings(self):
        self.inputBoxesToCfg()
        self._cfg.update()
        self._cfg.saveFile("config.ini")
        self._cfg.loadFile()
        self.cfgToInputBoxes()

    # button click events
    def on_btn1_click(self):
        msg = self.ids.btn1SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn2_click(self):
        msg = self.ids.btn2SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn3_click(self):
        msg = self.ids.btn3SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn4_click(self):
        msg = self.ids.btn4SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn5_click(self):
        msg = self.ids.btn5SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn6_click(self):
        msg = self.ids.btn6SwitchCode.text
        self._tcp.sendMsg(msg)

    def on_btn7_click(self):
        msg = "ALL_OFF:"
        states = str(self.ids.btn1AllOff.active) + "|"
        states = states + str(self.ids.btn2AllOff.active) + "|"
        states = states + str(self.ids.btn3AllOff.active) + "|"
        states = states + str(self.ids.btn4AllOff.active) + "|"
        states = states + str(self.ids.btn5AllOff.active) + "|"
        states = states + str(self.ids.btn6AllOff.active)
        msg = msg + states
        self._tcp.sendMsg(msg)

    def on_btnSaveConfig_click(self):
        self.updateSettings()
        popup = Popup(title='Settings',
                      content=Label(text='Saved!'),
                      size_hint=(None, None),
                      size=(410, 410))
        popup.open()
        rpiIp = self._cfg._rpiIp
        rpiPort = int(self._cfg._rpiPort)
        self._tcp = Tcp(port=rpiPort, bufferLen=1024, ip=rpiIp)

    def on_btnSaveCron_click(self):
        self.on_btnSaveConfig_click()
        self.sendCronToPi()

    def sendCronToPi(self):
        msg = "Cron:"
        states = str(self.ids.cronEnabled.active) + "|"
        states = states + str(self.ids.cronTurnOn.text) + "|"
        states = states + str(self.ids.cronTurnOff.text) + "|"
        states = states + str(self.ids.btn1CronOnOff.active) + "|"
        states = states + str(self.ids.btn2CronOnOff.active) + "|"
        states = states + str(self.ids.btn3CronOnOff.active) + "|"
        states = states + str(self.ids.btn4CronOnOff.active) + "|"
        states = states + str(self.ids.btn5CronOnOff.active) + "|"
        states = states + str(self.ids.btn6CronOnOff.active)
        msg = msg + states
        self._tcp.sendMsg(msg)

    def inputBoxesToCfg(self):
        # Network
        self._cfg._rpiIp = self.ids.rpiIp.text
        self._cfg._rpiPort = self.ids.rpiPort.text
        self._cfg._remoteCode = self.ids.remoteCode.text
        # Button Text Control
        self._cfg._btnTexts[1] = self.ids.btn1.text
        self._cfg._btnTexts[2] = self.ids.btn2.text
        self._cfg._btnTexts[3] = self.ids.btn3.text
        self._cfg._btnTexts[4] = self.ids.btn4.text
        self._cfg._btnTexts[5] = self.ids.btn5.text
        self._cfg._btnTexts[6] = self.ids.btn6.text
        self._cfg._btnTexts[0] = self.ids.btn7.text
        # Button Text Layout
        self._cfg._btnTexts[1] = self.ids.btn1Layout.text
        self._cfg._btnTexts[2] = self.ids.btn2Layout.text
        self._cfg._btnTexts[3] = self.ids.btn3Layout.text
        self._cfg._btnTexts[4] = self.ids.btn4Layout.text
        self._cfg._btnTexts[5] = self.ids.btn5Layout.text
        self._cfg._btnTexts[6] = self.ids.btn6Layout.text
        # Buttons All Off
        self._cfg._btnsAllOff[0] = self.ids.btn1AllOff.active
        self._cfg._btnsAllOff[1] = self.ids.btn2AllOff.active
        self._cfg._btnsAllOff[2] = self.ids.btn3AllOff.active
        self._cfg._btnsAllOff[3] = self.ids.btn4AllOff.active
        self._cfg._btnsAllOff[4] = self.ids.btn5AllOff.active
        self._cfg._btnsAllOff[5] = self.ids.btn6AllOff.active
        # Button Switch Codes
        self._cfg._switchCodes[0] = self.ids.btn1SwitchCode.text
        self._cfg._switchCodes[1] = self.ids.btn2SwitchCode.text
        self._cfg._switchCodes[2] = self.ids.btn3SwitchCode.text
        self._cfg._switchCodes[3] = self.ids.btn4SwitchCode.text
        self._cfg._switchCodes[4] = self.ids.btn5SwitchCode.text
        self._cfg._switchCodes[5] = self.ids.btn6SwitchCode.text
        # Cron
        self._cfg._cronEnabled = self.ids.cronEnabled.active
        self._cfg._cronTurnOn = self.ids.cronTurnOn.text
        self._cfg._cronTurnOff = self.ids.cronTurnOff.text
        # Btn Cron On Off
        self._cfg._btnsCronOnOff[0] = self.ids.btn1CronOnOff.active
        self._cfg._btnsCronOnOff[1] = self.ids.btn2CronOnOff.active
        self._cfg._btnsCronOnOff[2] = self.ids.btn3CronOnOff.active
        self._cfg._btnsCronOnOff[3] = self.ids.btn4CronOnOff.active
        self._cfg._btnsCronOnOff[4] = self.ids.btn5CronOnOff.active
        self._cfg._btnsCronOnOff[5] = self.ids.btn6CronOnOff.active

    def cfgToInputBoxes(self):
        # Network
        self.ids.rpiIp.text = self._cfg._rpiIp
        self.ids.rpiPort.text = self._cfg._rpiPort
        self.ids.remoteCode.text = self._cfg._remoteCode
        # Button Text Control
        self.ids.btn1.text = self._cfg._btnTexts[1]
        self.ids.btn2.text = self._cfg._btnTexts[2]
        self.ids.btn3.text = self._cfg._btnTexts[3]
        self.ids.btn4.text = self._cfg._btnTexts[4]
        self.ids.btn5.text = self._cfg._btnTexts[5]
        self.ids.btn6.text = self._cfg._btnTexts[6]
        self.ids.btn7.text = self._cfg._btnTexts[0]
        # Button Text Layout
        self.ids.btn1Layout.text = self._cfg._btnTexts[1]
        self.ids.btn2Layout.text = self._cfg._btnTexts[2]
        self.ids.btn3Layout.text = self._cfg._btnTexts[3]
        self.ids.btn4Layout.text = self._cfg._btnTexts[4]
        self.ids.btn5Layout.text = self._cfg._btnTexts[5]
        self.ids.btn6Layout.text = self._cfg._btnTexts[6]
        # Buttons All Off
        self.ids.btn1AllOff.active = self._cfg._btnsAllOff[0]
        self.ids.btn2AllOff.active = self._cfg._btnsAllOff[1]
        self.ids.btn3AllOff.active = self._cfg._btnsAllOff[2]
        self.ids.btn4AllOff.active = self._cfg._btnsAllOff[3]
        self.ids.btn5AllOff.active = self._cfg._btnsAllOff[4]
        self.ids.btn6AllOff.active = self._cfg._btnsAllOff[5]
        # Lables Buttons All Off
        self.ids.lbl1AllOff.text = "Button " + self.ids.btn1.text
        self.ids.lbl2AllOff.text = "Button " + self.ids.btn2.text
        self.ids.lbl3AllOff.text = "Button " + self.ids.btn3.text
        self.ids.lbl4AllOff.text = "Button " + self.ids.btn4.text
        self.ids.lbl5AllOff.text = "Button " + self.ids.btn5.text
        self.ids.lbl6AllOff.text = "Button " + self.ids.btn6.text
        # Button Switch Codes
        self.ids.btn1SwitchCode.text = self._cfg._switchCodes[0]
        self.ids.btn2SwitchCode.text = self._cfg._switchCodes[1]
        self.ids.btn3SwitchCode.text = self._cfg._switchCodes[2]
        self.ids.btn4SwitchCode.text = self._cfg._switchCodes[3]
        self.ids.btn5SwitchCode.text = self._cfg._switchCodes[4]
        self.ids.btn6SwitchCode.text = self._cfg._switchCodes[5]
        # Lables Button Switch Codes
        self.ids.lblBtn1SwitchCode.text = "Button " + self.ids.btn1.text
        self.ids.lblBtn2SwitchCode.text = "Button " + self.ids.btn2.text
        self.ids.lblBtn3SwitchCode.text = "Button " + self.ids.btn3.text
        self.ids.lblBtn4SwitchCode.text = "Button " + self.ids.btn4.text
        self.ids.lblBtn5SwitchCode.text = "Button " + self.ids.btn5.text
        self.ids.lblBtn6SwitchCode.text = "Button " + self.ids.btn6.text
        # Cron
        self.ids.cronEnabled.active = self._cfg._cronEnabled
        self.ids.cronTurnOn.text = self._cfg._cronTurnOn
        self.ids.cronTurnOff.text = self._cfg._cronTurnOff
        # Buttons Cron On Off
        self.ids.btn1CronOnOff.active = self._cfg._btnsCronOnOff[0]
        self.ids.btn2CronOnOff.active = self._cfg._btnsCronOnOff[1]
        self.ids.btn3CronOnOff.active = self._cfg._btnsCronOnOff[2]
        self.ids.btn4CronOnOff.active = self._cfg._btnsCronOnOff[3]
        self.ids.btn5CronOnOff.active = self._cfg._btnsCronOnOff[4]
        self.ids.btn6CronOnOff.active = self._cfg._btnsCronOnOff[5]
        # Lables Cron On Off
        self.ids.lbl1CronOnOff.text = "Button " + self.ids.btn1.text
        self.ids.lbl2CronOnOff.text = "Button " + self.ids.btn2.text
        self.ids.lbl3CronOnOff.text = "Button " + self.ids.btn3.text
        self.ids.lbl4CronOnOff.text = "Button " + self.ids.btn4.text
        self.ids.lbl5CronOnOff.text = "Button " + self.ids.btn5.text
        self.ids.lbl6CronOnOff.text = "Button " + self.ids.btn6.text