예제 #1
0
class CommandInitiater(LogImplementer, Thread):

    transmitter = None

    def __init__(self, targetDevice, initMessage):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.targetDevice = targetDevice
        self.initMessage = initMessage

        self.transmitter = Transmitter()

    def run(self):

        isRunning = True
        self.transmitter.setTimeout(5)
        while isRunning:

            self.transmitter.sendInitMessage(self.initMessage)
            try:
                response = self.transmitter.listen()
                self.runSanityChecks(response)
                isRunning = False
            except timeout:
                self.logger.debug(f'No response received, resending message')
            except:
                raise

        self.logger.info("Command sent and response received, finishing up")

    def runSanityChecks(self, message):
        assert (message.target == self.initMessage.sender)
        assert (message.type == MessageType.ACK)
예제 #2
0
    def __init__(self, targetDevice, initMessage):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.targetDevice = targetDevice
        self.initMessage = initMessage

        self.transmitter = Transmitter()
예제 #3
0
 def __init__(self, pingMessage):
     Thread.__init__(self)
     LogImplementer.__init__(self)
     self.socket = Transmitter()
     self.socket.setTimeout(PING_TIMEOUT)
     self.initialMessage = pingMessage
     self.setName('Ping-Init Thread')
예제 #4
0
 def __init__(self, targetIpAddress):
     Thread.__init__(self)
     LogImplementer.__init__(self)
     self.socket = Transmitter()
     self.socket.setTimeout(PING_TIMEOUT)
     self.pingTargetName = targetIpAddress
     self.setName('Ping-Init Thread')
예제 #5
0
class HandshakeReceiver(Thread, LogImplementer):

    communicationSocket = None
    initialMessage = None
    targetPort = None
    targetIpAddress = ""

    def __init__(self, initialMessage):
        Thread.__init__(self)
        LogImplementer.__init__(self)

        self.initialMessage = initialMessage
        self.targetPort = initialMessage.senderAddress[1]
        self.communicationSocket = Transmitter()
        self.setName('Hand-Handler Thread')

    def run(self):
        self.logger.info('Handshake protocol Initiated')

        InsTable().newHandshakeInitiated(self.initialMessage)

        self.SendAck()

    def SendAck(self):
        ackMessage = self.CreateMessage(MessageType.POLO)
        self.communicationSocket.sendMessage(ackMessage, self.targetPort)

    def CreateMessage(self, messageType=MessageType.INVALID):
        newMessage = Message(messageType, self.initialMessage.sender)

        return newMessage
예제 #6
0
class PingInitiater(Thread, LogImplementer):
    socket = None
    pingTargetName = 'BROADCAST'

    def __init__(self, targetIpAddress):
        Thread.__init__(self)
        LogImplementer.__init__(self)
        self.socket = Transmitter()
        self.socket.setTimeout(PING_TIMEOUT)
        self.pingTargetName = targetIpAddress
        self.setName('Ping-Init Thread')

    def run(self):
        initMessage = self.CreateMessage(MessageType.PING)
        self.socket.sendInitMessage(initMessage)
        loop = True
        while loop:
            try:
                response = self.socket.listen()

                if response.type == MessageType.ACK:
                    loop = False

            except timeout:
                self.logger.warn('Ping timed out, Isaac unit unresponsive.')
                loop = False

        self.logger.debug('Pinging complete')

    def CreateMessage(self, messageType=MessageType.INVALID):
        newMessage = Message(messageType, self.pingTargetName)

        return newMessage
예제 #7
0
  def __init__  (
    self, bitDepth, numberOfChannels, sampleRate, bitsPerSymbol,
    samplesPerSymbol, carrierFrequency, outputFileName, firstStopband,
    firstPassband, secondPassband, secondStopband, passbandAttenuation,
    stopbandAttenuation, writeOutput
                ):

    Transmitter.__init__  (
      self, bitDepth, numberOfChannels, sampleRate,
      bitsPerSymbol, samplesPerSymbol, carrierFrequency,
      outputFileName, writeOutput
                          )

    self.firstStopband        = firstStopband
    self.firstPassband        = firstPassband
    self.secondPassband       = secondPassband
    self.secondStopband       = secondStopband
    self.passbandAttenuation  = passbandAttenuation
    self.stopbandAttenuation  = stopbandAttenuation

    self.filter =  \
      python_initialize_kaiser_filter (
        self.firstStopband,
        self.firstPassband,
        self.secondPassband,
        self.secondStopband,
        self.passbandAttenuation,
        self.stopbandAttenuation,
        int( self.sampleRate )
                                      )
예제 #8
0
    def __init__(self, initialMessage):
        Thread.__init__(self)
        LogImplementer.__init__(self)

        self.initialMessage = initialMessage
        self.targetPort = initialMessage.senderAddress[1]
        self.communicationSocket = Transmitter()
        self.setName('Hand-Handler Thread')
예제 #9
0
 def __init__(self, numOfInputs):
     self.transmitter = Transmitter()
     self.receiver = Receiver()
     self.wirelessChannel = WirelessChannel(0.1)
     self.numOfInputs = numOfInputs
     self.sigmaValues = [10, 1, 0.1]
     self.reveivedPoints = []
     self.colors = ['purple', 'yellow', 'orange']
     self.hammingProbs = []
     self.qpskProbs = []
예제 #10
0
    def CreateTransmissions(self, binInput, modulationScheme):
        transmitter1 = Transmitter(self.transmitPower)
        transmitter2 = Transmitter(self.transmitPower)
        symbols = transmitter1.BinStreamToSymbols(binInput, modulationScheme)
        #2d array of transmissions.
        #transmissions [transmitter Number][transmission Number]
        transmissions = [[0 for x in range(len(symbols))] for y in range(2)]

        for x in range(len(symbols) / 2):
            s0 = symbols[2 * x]
            s1 = symbols[2 * x + 1]
            s1ConjNeg = -1 * (s1.conjugate())
            s0Conj = s0.conjugate()

            #Transmitter 1
            transmissions[0][(2 * x)] = transmitter1.CreateTransmission(s0)
            transmissions[0][(2 * x) +
                             1] = transmitter1.CreateTransmission(s1ConjNeg)

            #Transmitter 2
            transmissions[1][(2 * x)] = transmitter2.CreateTransmission(s1)
            transmissions[1][(2 * x) +
                             1] = transmitter2.CreateTransmission(s0Conj)

        return transmissions
예제 #11
0
class InputMethod:
	def __init__(self):
		self.motor_speeds = [0, 0, 0]
		# Init transmitter
		self.t = Transmitter()

	def doListenLoop(self):
		while True:
			self.getInput()
			self.t.send(self.motor_speeds)

	def getInput(self):
		pass
예제 #12
0
    def __init__(self, linkID, qrVersion, qrECC, duration, speed):
        """Constructor"""
        self.linkID = linkID
        self.speed = self.speedValue(speed)
        self.qrVersion = qrVersion
        self.qrECC = qrECC
        self.duration = duration
        ##		self.matrix = Adafruit_RGBmatrix(32,1)

        print("QOTR System Booting: \nQR Verion %d ECC %s \nLink ID %d \n" %
              (self.qrVersion, self.qrECC, self.linkID))

        self.manager = multiprocessing.Manager()
        self.queue = self.manager.list([])

        self.buildQueue()

        #Uncomment these lines to support full duplex link
        ##                trans = multiprocessing.Process(target=Transmitter.__startTransmitter__, args=(self.transmitter, self.queue))
        ##                trans.start()

        ##		self.EthernetReader = ethernetReader.EthernetReader()
        ##		self.EthernetWriter = EthernetWriter.EthernetWriter()

        ##		reader = multiprocessing.Process(target=ethernetReader.EthernetReader.read, args=(self.EthernetReader, self.queue))
        ##		writer = multiprocessing.Process(target=EthernetWriter.EthernetWriter.checkForPacket, args=(self.EthernetWriter, self.queue))

        ##		reader.start()
        ##		writer.start()

        self.transmitter = Transmitter(self.qrVersion, self.qrECC, self.linkID,
                                       self.duration, self.speed)
        self.transmitter.__startTransmitter__(self.queue)

        reader.terminate()

        # self.EthernetReader.read()
        # self.EthernetWriter.checkForPacket()

        try:
            while True:
                pass
        except KeyboardInterrupt:
            reader.terminate()
            ##			writer.terminate()
            sys.exit()
        except:
            pass
예제 #13
0
class CommandReceiver(LogImplementer, Thread):

    responseSocket = Transmitter()
    targetPort = None

    def __init__(self, initialMessage):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.targetDevice = initialMessage.sender
        self.targetPort = initialMessage.senderAddress[1]
        self.initialMessage = initialMessage

    def run(self):
        payload = self.initialMessage.payload

        response = self.createNextAck()
        self.responseSocket.sendMessage(response, self.targetPort)

        self.logger.debug(f'<<<<<Response sent, closing up for the night')
        networkApi.pushIncomingCommand(self.initialMessage.sender, payload)

    def createNextAck(self):
        message = Message(MessageType.ACK, self.targetDevice)

        return message

    def sendNextAck(self):
        message = self.createNextAck()
        self.socket.sendMessage(message, self.targetPort)
        self.counter += 1
    def setUp(self):
        """ Setup function TestTypes for class Transmitter """

        self.TransmitterObj = Transmitter(transmitter_config, tx_data, bypass)

        self.transmitter_config = self.TransmitterObj.transmitter_config
        self.tx_data_in = self.TransmitterObj.tx_data_in
        self.bypass = self.TransmitterObj.bypass

        pass
예제 #15
0
def transmit():
  if( args.message and args.deviceName ):
    print "Transmit info:"
    print "\tMessage:\t\t'%s'" %( args.message )
    print "\tDevice:\t\t\t%s" %( args.deviceName )
    print "\tOutput signal:\t\t%s" %( "Yes" if( args.writeOutput ) else "No" )
    print "\nFormat info:"
    print "\tBit depth:\t\t%d" %( args.bitDepth )
    print "\tNumber of channels:\t%d" %( args.numberOfChannels )
    print "\tSample rate:\t\t%.02f" %( args.sampleRate )
    print "\nModulation info:"
    print "\tBits per symbol:\t%d" %( args.bitsPerSymbol )
    print "\tSamples per symbol:\t%d" %( args.samplesPerSymbol )
    print "\tCarrier frequency:\t%.02f" %( args.carrierFrequency )

    if( args.writeOutput ):
      print "\nOutput info:"
      print "\tFile name:\t\t%s" %( args.outputFileName )

    device = findDevice( args.deviceName )

    if( device ):
      if( device.doesSupportPlayback() ):
        transmitter = \
          Transmitter (
            args.bitDepth,
            args.numberOfChannels,
            args.sampleRate,
            args.bitsPerSymbol,
            args.samplesPerSymbol,
            args.carrierFrequency,
            args.outputFileName,
            args.writeOutput
                      )

        transmitter.transmit( device, args.message )
      else:
        print "ERROR: Device %s does not support playback." \
          %( args.deviceName )
    else:
      print "ERROR: Could not find device %s." %( args.deviceName )
  else:
    print "ERROR: Message and device name must be set for transmit."
예제 #16
0
    def start_up(self, ser, ros_is_on, traj, step_is_on):
        self.last_print_time = time.time()

        if (not self.first):
            self.ser = ser
            self.tx.change_port(ser)
            self.rx.change_port(ser)
            return

        self.first = False
        self.ros_is_on = ros_is_on
        self.step_is_on = step_is_on
        self.use_trajectory = False

        self.tx = Transmitter(ser)
        self.rx = Receiver(ser, ros_is_on)

        if (self.ros_is_on == True):
            rospy.init_node('soccer_hardware', anonymous=True)
            rospy.Subscriber("robotGoal",
                             RobotGoal,
                             self.trajectory_callback,
                             queue_size=1)
            self.rx.pub = rospy.Publisher('soccerbot/imu', Imu, queue_size=1)
            self.rx.pub2 = rospy.Publisher('soccerbot/robotState',
                                           RobotState,
                                           queue_size=1)
        else:
            trajectories_dir = os.path.join("trajectories", traj)
            try:
                self.trajectory = np.loadtxt(open(trajectories_dir, "rb"),
                                             delimiter=",",
                                             skiprows=0)

                logString("Opened trajectory {0}".format(traj))
                self.use_trajectory = True
            except IOError as err:
                logString("Error: Could not open trajectory: {0}".format(err))
                logString(
                    "(Is your shell running in the soccer-communication directory?)"
                )
                logString("Standing pose will be sent instead...")
예제 #17
0
class PingReceiver(Thread, LogImplementer):
    socket = None
    initialMessage = None

    def __init__(self, pingMessage):
        Thread.__init__(self)
        LogImplementer.__init__(self)
        self.socket = Transmitter()
        self.socket.setTimeout(PING_TIMEOUT)
        self.initialMessage = pingMessage
        self.setName('Ping-Init Thread')

    def run(self):
        initMessage = self.createMessage(MessageType.ACK)
        self.socket.sendMessage(initMessage,
                                self.initialMessage.senderAddress[1])

    def createMessage(self, messageType=MessageType.INVALID):
        newMessage = Message(messageType, self.initialMessage.sender)

        return newMessage
예제 #18
0
class HandshakeInitiater(Thread, LogImplementer):
    socket = None
    partnerIpAddress = 'BROADCAST'
    def __init__(self):
        Thread.__init__(self)
        LogImplementer.__init__(self)
        self.socket = Transmitter()
        self.socket.setTimeout(HANDSHAKE_TIMEOUT)
        self.setName('Hand-Init Thread')

    def run(self):
        initMessage = self.CreateMessage(MessageType.MARCO)
        self.socket.broadcastInitMessage(initMessage)
        loop = True
        while loop:
            try:
                response = self.socket.listen()

                if response.type == MessageType.POLO:
                    InsTable().newHandshakeInitiated(response)

            except timeout as err:
                self.logger.info('Listening timed out, no other Isaac units found.')
                loop = False

        self.logger.debug('Handshake complete')
        self.finish()

    def CreateMessage(self, messageType = MessageType.INVALID):
        newMessage = Message(messageType, self.partnerIpAddress)

        return newMessage

    def finish(self):
        newState = networkApi.NetworkState.STABLE
        if (len(InsTable().getNames()) > 0):
            newState = networkApi.NetworkState.CONNECTED

        networkApi.completeInitialisation(newState)
        InsTable().printTable()
예제 #19
0
def main(argv):
    start_time = time.time()
    ip, port = argv[2].split(':')
    transmitter = Transmitter(int(argv[3]), float(argv[5]), int(argv[4]), ip,
                              int(port))

    # transmitter.udp.bind((socket.gethostname(), 3000))

    with open(argv[1]) as fp:
        sequence_number = 0
        for line in fp:
            packet = transmitter.mount_packet(sequence_number,
                                              line.split('\n')[0])
            # packet = transmitter.mount_packet(sequence_number, line)

            window_element = SlidingWindowElement(packet, sequence_number,
                                                  transmitter.timeout,
                                                  transmitter.resend_packet)
            transmitter.window.insert(window_element)  # insere na janela

            if (utils.compare_error(transmitter.p_error)):
                packet = utils.corrupt_md5(packet)
                transmitter.lock.acquire()
                transmitter.incorrect_messages += 1
                transmitter.lock.release()

            transmitter.send_packet(packet)
            window_element.timer.start()  # seta timeout
            sequence_number += 1

            if (transmitter.window.current_size ==
                    transmitter.window.window_size):
                while (not transmitter.window.buffer[0].ack):
                    transmitter.handle_ack()

    while (not transmitter.window.check_all_acks()):
        transmitter.handle_ack()

    print(transmitter.messages, transmitter.messages_sent,
          transmitter.incorrect_messages, round(time.time() - start_time, 3))
예제 #20
0
    def __init__(self, DEBUG=False):
        """Constructor"""

        if DEBUG:
            print('Running Main...')

        # Message object.
        self.message_obj = Message(input_info=input_info, n_frames=n_frames)

        # Mapping object.
        self.mapping_obj = Mapping(bitstream_frames=bitstream_frames,
                                   mapping_type=mapping_type,
                                   bits_per_symbol=bits_per_symbol)

        # Modulator object.
        self.modulator_obj = Modulator(mapped_info=mapped_info,
                                       modulation_type=modulation_type)

        # Transmitter object.
        self.transmitter_obj = Transmitter(
            transmitter_config=transmitter_config,
            tx_data=tx_data,
            bypass=bypass)

        # Channel object
        self.channel_obj = Channel(tx_data_in=tx_data_in, raytrace=raytrace)

        # Receiver object.
        self.receiver_obj = Receiver(receiver_config=receiver_config,
                                     rx_data=rx_data,
                                     bypass=bypass)

        # Merit Funcions object
        self.merit_functions_obj = MeritFunctions()

        # Global object.
        self.global_obj = Global()

        pass
예제 #21
0
def run(ctx, passive, low, home_id, test):
    """Starts the IoT honeypot"""
    configuration = ctx.obj[CONFIGURATION]
    configuration.home_id = home_id
    logger = ctx.obj[LOGGER]

    if passive:
        signal.signal(signal.SIGINT, signal_handler)
        network = load_json(configuration.networks_path + '/' +
                            configuration.real_networks_name)
        decoys = load_json(configuration.networks_path + '/' +
                           configuration.virtual_networks_name)

        receiver = Receiver(configuration, network, decoys, logger, None, None)
        monitor = Monitor(configuration, network, decoys, logger, None,
                          receiver)
        receiver.monitor = monitor

        configuration_process = Process(target=set_configuration,
                                        args=(configuration, logger))
        configuration_process.start()

        signal.signal(signal.SIGINT, signal_handler)
        global monitor_stats
        monitor_stats = monitor.stats

        monitor.start(passive=True)

    else:
        with multiprocessing.Manager() as manager:

            # load networks to shared dictionaries of manager
            network = manager.dict(
                load_json(configuration.networks_path + '/' +
                          configuration.real_networks_name))
            decoys = manager.dict(
                load_json(configuration.networks_path + '/' +
                          configuration.virtual_networks_name))

            if home_id and home_id not in decoys.keys():
                sys.exit(ERROR_MISSING_DECOYS)

            signal.signal(signal.SIGINT, signal_handler)

            monitor_conn, generator_conn = Pipe()
            receiver_conn, transmitter_conn = Pipe()

            transmitter = Transmitter(configuration, transmitter_conn)
            if not low:
                responder = Responder(transmitter, decoys, logger)
            else:
                responder = None
            receiver = Receiver(configuration, network, decoys, logger,
                                receiver_conn, responder)
            monitor = Monitor(configuration, network, decoys, logger,
                              monitor_conn, receiver)
            receiver.monitor = monitor
            generator = TrafficGenerator(configuration, network, decoys,
                                         logger, generator_conn, transmitter)

            # init processes
            monitor_process = Process(target=monitor_target, args=(monitor, ))
            configuration_process = Process(target=set_configuration,
                                            args=(configuration, logger))

            # start processes
            try:
                configuration_process.start()
                monitor_process.start()
                generator.start(test)
            except KeyboardInterrupt:
                logger.info('\nTerminating...')
                monitor_process.terminate()
                configuration_process.terminate()

            configuration_process.join()
            monitor_process.join()
예제 #22
0
class LinkLayerInterface:
    def __init__(self, linkID, qrVersion, qrECC, duration, speed):
        """Constructor"""
        self.linkID = linkID
        self.speed = self.speedValue(speed)
        self.qrVersion = qrVersion
        self.qrECC = qrECC
        self.duration = duration
        ##		self.matrix = Adafruit_RGBmatrix(32,1)

        print("QOTR System Booting: \nQR Verion %d ECC %s \nLink ID %d \n" %
              (self.qrVersion, self.qrECC, self.linkID))

        self.manager = multiprocessing.Manager()
        self.queue = self.manager.list([])

        self.buildQueue()

        #Uncomment these lines to support full duplex link
        ##                trans = multiprocessing.Process(target=Transmitter.__startTransmitter__, args=(self.transmitter, self.queue))
        ##                trans.start()

        ##		self.EthernetReader = ethernetReader.EthernetReader()
        ##		self.EthernetWriter = EthernetWriter.EthernetWriter()

        ##		reader = multiprocessing.Process(target=ethernetReader.EthernetReader.read, args=(self.EthernetReader, self.queue))
        ##		writer = multiprocessing.Process(target=EthernetWriter.EthernetWriter.checkForPacket, args=(self.EthernetWriter, self.queue))

        ##		reader.start()
        ##		writer.start()

        self.transmitter = Transmitter(self.qrVersion, self.qrECC, self.linkID,
                                       self.duration, self.speed)
        self.transmitter.__startTransmitter__(self.queue)

        reader.terminate()

        # self.EthernetReader.read()
        # self.EthernetWriter.checkForPacket()

        try:
            while True:
                pass
        except KeyboardInterrupt:
            reader.terminate()
            ##			writer.terminate()
            sys.exit()
        except:
            pass

    def speedValue(self, speed):
        if speed == "S":
            return .1
        elif speed == "M":
            return .05
        elif speed == "F":
            return 0

    def buildQueue(self):
        """For testing purposes, instead of using the ethernetRead.py this version reads packets from a PCAP.  To create variation
                it randomizes which packets from the file are used."""
        packets = open("parsedPackets.txt", "r")
        thresh = 1000
        count = 0
        for line in packets:
            if thresh <= count:
                break
            if len(line) < 40:
                pass
            elif "(" in line:
                pass
            else:
                packet = line.strip("\n")
                self.queue.append(packet)
                count += 1
        random.shuffle(self.queue)
        self.queue = self.queue[0:50]
        print("Test Queue Built")
예제 #23
0
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
    SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
    WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
#
#################################################################################################
import time
import sys
from Transmitter import Transmitter

transmitter = Transmitter(100.0, "wav/bird.wav")
transmitter.init()
transmitter.reader.stat()
transmitter.transmit()

while transmitter.busy:
  try:
    time.sleep(1)
  except KeyboardInterrupt:
    transmitter.close()
    sys.exit(0)
    
transmitter.newJob("wav/star_wars.wav")
transmitter.reader.stat()
transmitter.transmit()
예제 #24
0
        tmp += str(data[i])
    return tmp


# ---RUN---
# parametres

mode = "CRC"
data_length = 4
packet_length = 2
cross_prob = 0.6

# init
generator = Generator()
sender = Sender()
transmitter = Transmitter(cross_prob)
receiver = Receiver()
analyzer = Analyzer(sender, receiver)

running = True
while running:
    print("---Menu---")
    print("1.zmien tryb: ", mode, "\n2.zmien dlugosc sygnalu:", data_length,
          "\n3.zmien dlugosc pakietu:", packet_length,
          "\n4.zmien prawdopodobienstwo zaklocenia:", cross_prob,
          "\n5.Uruchom symulacje", "\n0.Wyjdz z programu")
    choice = input()
    if choice == "0":
        running = False
    elif choice == "1":
        mode = input("podaj tryb: (CRC/PAR): ")
예제 #25
0
  def __del__( self ):
    Transmitter.__del__( self )

    if( self.filter ):
      csignal_destroy_passband_filter( self.filter )
예제 #26
0
class WirelessSystem:
    def __init__(self, numOfInputs):
        self.transmitter = Transmitter()
        self.receiver = Receiver()
        self.wirelessChannel = WirelessChannel(0.1)
        self.numOfInputs = numOfInputs
        self.sigmaValues = [10, 1, 0.1]
        self.reveivedPoints = []
        self.colors = ['purple', 'yellow', 'orange']
        self.hammingProbs = []
        self.qpskProbs = []
    
    def runForScatterPlot(self):
        u = Utils() 
        probabilities = []
        for i in range(len(self.sigmaValues)):
            self.reveivedPoints = []
            input = open("input.txt", "r")
            numOfCorrectOutputs = 0
            AWGNsigma = self.sigmaValues[i]
            self.wirelessChannel.setSigma(1/AWGNsigma)
            for line in input:
                data = line.rstrip()
                point = self.transmitter.modulate(data)
                (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                self.wirelessChannel.applyAWGN(point)
                self.reveivedPoints.append(point)

            u.showScatterPlot(self.reveivedPoints ,AWGNsigma, self.colors[i])
            input.close()


    def runForScatterPlot16(self):
        u = Utils() 
        probabilities = []
        for i in range(len(self.sigmaValues)):
            self.reveivedPoints = []
            input = open("input.txt", "r")
            numOfCorrectOutputs = 0
            AWGNsigma = self.sigmaValues[i]
            self.wirelessChannel.setSigma(1/AWGNsigma)
            cntr = 0
            for line in input:
                if(cntr == 0):
                    data = line.rstrip()
                    cntr += 1
                    continue
                else:
                    data += line.rstrip()
                    cntr = 0
                    point = self.transmitter.modulate16QAM(data)
                    (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                    self.wirelessChannel.applyAWGN(point)
                    self.reveivedPoints.append(point)

            u.showScatterPlotQAM(self.reveivedPoints ,AWGNsigma, self.colors[i])
            input.close()
               
    def runForLinePlot(self):
        u = Utils() 
        probabilities = []
        for i in range(1, 100, 1):
            input = open("input.txt", "r")
            numOfCorrectOutputs = 0
            SNR = i / 10
            print('i=', i, 'for AWGNSgima =', 1/SNR)
            self.wirelessChannel.setSigma(1/SNR)
            for line in input:
                data = line.rstrip()
                point = self.transmitter.modulate(data)
                (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                self.wirelessChannel.applyAWGN(point)
                self.receiver.removeChannelImpact(point, hI, hQ)
                receiverOut = self.receiver.demodulate2(point)
                if(data == receiverOut):
                    numOfCorrectOutputs += 1
            probabilities.append(1 - (numOfCorrectOutputs/self.numOfInputs))
            input.close()

        print(probabilities)
        self.qpskProbs = probabilities
        u.probVsSNR([(i/10.0) for i in range(1, 100, 1)], probabilities)


    def runForLinePlot16(self):
        u = Utils() 
        probabilities = []
        for i in range(1, 100, 1):
            input = open("input.txt", "r")
            numOfCorrectOutputs = 0
            SNR = i / 10
            print('i=', i, 'for AWGNSgima =', 1/SNR)
            self.wirelessChannel.setSigma(1/SNR)
            cntr = 0
            for line in input:
                if(cntr == 0):
                    data = line.rstrip()
                    cntr += 1
                    continue
                else :
                    cntr = 0
                    data += line.rstrip()
                    point = self.transmitter.modulate16QAM(data)
                    (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                    self.wirelessChannel.applyAWGN(point)
                    self.receiver.removeChannelImpact(point, hI, hQ)
                    receiverOut = self.receiver.demodulate16(point)
                    if(data == receiverOut):
                        numOfCorrectOutputs += 1
            probabilities.append(1 - (numOfCorrectOutputs/(self.numOfInputs/2)))
            input.close()

        u.probVsSNR([i/10.0 for i in range(1, 100, 1)], probabilities)
    
    def runWithHammingCode(self):
        u = Utils() 
        probabilities = []
        self.encodeAllWithHamming()
        for i in range(1, 100, 1):
            allDemodulated = open('demodulated.txt', 'w')
            SNR = i / 10.0
            print('for AWGNSgima =', 1/SNR)
            self.wirelessChannel.setSigma(1/SNR)
            content_file = open('encoded.txt', 'r')
            content = content_file.read()
            for data in [content[i:i+2] for i in range(0, len(content), 2)] :
                point = self.transmitter.modulate(data)
                (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                self.wirelessChannel.applyAWGN(point)
                self.receiver.removeChannelImpact(point, hI, hQ)
                receiverOut = self.receiver.demodulate2(point)
                allDemodulated.write(receiverOut)
            allDemodulated.close()

            self.decodeAll()
            numOfCorrectOutputs = self.reconstructAndCalcCorrectOutputs()
            probabilities.append(1 - (numOfCorrectOutputs/(self.numOfInputs)))

        self.hammingProbs = probabilities
        u.probVsSNR([i/10.0 for i in range(1, 100, 1)], probabilities)
        #plt.plot([i/10.0 for i in range(1, 100, 1)], probabilities,  color='green')
        #plt.plot([i/10.0 for i in range(1, 100, 1)], self.qpskProbs)
        #plt.show()

    def runForScatterPlotHamming(self):
        u = Utils() 
        probabilities = []
        self.receivedPoints = []
        for i in range(len(self.sigmaValues)):
            AWGNsigma = self.sigmaValues[i]
            self.wirelessChannel.setSigma(1/AWGNsigma)
            content_file = open('encoded.txt', 'r')
            content = content_file.read()
            for data in [content[x:x+2] for x in range(0, len(content), 2)] :
                point = self.transmitter.modulate(data)
                (hI, hQ) = self.wirelessChannel.applyChannelGain(point)
                self.wirelessChannel.applyAWGN(point)
                self.reveivedPoints.append(point)

            u.showScatterPlot(self.reveivedPoints , AWGNsigma, self.colors[i])
        content_file.close()


    def encodeAllWithHamming(self):
        input = open("input.txt", "r") 
        output = open("encoded.txt", "w")
        cntr = 0
        for line in input: 
            if(cntr == 0):
                data = line.rstrip()
                cntr +=1
                continue
            else:
                data += line.rstrip()
                cntr = 0
                encoded = self.transmitter.encodeHamming(map(int, data))
                mystring = ""
                for bit in encoded:
                    mystring += str(bit)
                output.write(mystring)
        input.close()
        output.close()
    
    def decodeAll(self):
        demod = open('demodulated.txt', 'r')
        decodedFile = open("decoded.txt", "w")
        lines = demod.read()
        for data in [lines[i:i+7] for i in range(0, len(lines), 7)] :
            decoded = self.receiver.decodeHamming(map(int, data))
            actualData = data[0:4]
            mystring = ""
            for bit in decoded:
                mystring += str(bit)
            decodedFile.write(actualData + mystring)
                    
        decodedFile.close()
        demod.close()
    
    def reconstructAndCalcCorrectOutputs(self):
        numOfCorrects = 0
        counter = 0
        decodedFile = open('decoded.txt', 'r')
        lines = tuple(open('input.txt', 'r'))
        content = decodedFile.read()
        for line in [content[i:i+7] for i in range(0, len(content), 7)] :
            actualData = line[0 : 4]
            syndromes = line[4:7]
            inputLine1 = lines[counter].rstrip() 
            inputLine2 = lines[counter + 1].rstrip()
            correctedOutput = self.receiver.findAndCorrectError(syndromes, actualData)
            if(correctedOutput[0 : 2] == inputLine1):
                numOfCorrects += 1
            if(correctedOutput[2 : 4] == inputLine2):
                numOfCorrects += 1
            counter += 2

        return numOfCorrects
예제 #27
0
class CountInitiater(LogImplementer, Thread):

    counter = 0
    target = 0
    currentSequenceNumber = 0
    socket = Transmitter()
    targetDevice = None
    targetPort = None

    def __init__(self, n=8, targetDevice='BROADCAST'):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.target = n
        self.targetDevice = targetDevice

    def run(self):

        self.sendInitMessage()

        self.listenForInitAck()

        while self.counter < self.target:
            # Create next message
            self.sendNextMessage()

            # listen for message
            message = self.listenForAck()

            # assert
            self.runSanityChecks(message)
            self.counter += 2
        self.logger.debug(
            f'>>>> Counting complete, counter: {self.counter}/{self.target}')

    def createNextMessage(self):
        message = Message(MessageType.COUNT, self.targetDevice)
        payload = self.packInt(self.counter)
        message.setPayload(payload)
        message.setSequenceNumbers(self.currentSequenceNumber,
                                   int(self.target / 2))

        return message

    def packInt(self, n):
        return pack('>i', n)

    def sendInitMessage(self):
        message = self.createNextMessage()
        newPayload = message.payload + self.packInt(self.target)
        message.setPayload(newPayload)
        self.socket.sendInitMessage(message)

    def listenForInitAck(self):
        responseMessage = self.socket.listen()
        self.runSanityChecks(responseMessage)
        self.targetPort = responseMessage.senderAddress[1]
        self.counter += 2

    def sendNextMessage(self):
        self.currentSequenceNumber += 1
        message = self.createNextMessage()
        self.socket.sendMessage(message, self.targetPort)

    def listenForAck(self):
        try:
            return self.socket.listen()
        except:
            raise

    def runSanityChecks(self, response):
        assert len(response.payload) > 0, 'Response must have a payload'

        seqNumber = unpack(">i", response.payload)[0]
        assert (seqNumber == self.counter + 1)
        assert (response.currentSequenceNumber == self.currentSequenceNumber)
        assert (response.sender == self.targetDevice
                ), F'{response.sender} is not the target ({self.target})'
예제 #28
0
def run(ctx, low, home_id):
    """
    Run main function of the IoT honeypot
    :param ctx: shared context
    :param low: low-interaction mode means that the honeypot does not respond to malicious frames
    :param home_id: specifies the network identifier
    """
    # initialization
    signal.signal(signal.SIGINT, signal_handler)
    cfg = ctx.obj[CONFIGURATION]
    cfg.home_id = home_id
    honeylog = ctx.obj[LOGGER]

    # manager handles shared content between TX and RX processes
    with multiprocessing.Manager() as manager:
        network = manager.dict(load_json(cfg.networks_path + '/' + cfg.network_file))
        decoys = manager.dict(load_json(cfg.networks_path + '/' + cfg.decoys_file))

        # init stats
        inner_stats = init_stats_dict()
        stats_real = manager.dict(inner_stats.copy())
        stats_malicious = manager.dict(inner_stats.copy())
        stats_invalid = manager.dict(inner_stats.copy())
        stats_in = manager.dict(inner_stats.copy())
        stats_out = manager.dict(inner_stats.copy())

        stats = {STAT_REAL: stats_real,
                 STAT_MALICIOUS: stats_malicious,
                 STAT_INVALID: stats_invalid,
                 STAT_IN: stats_in,
                 STAT_OUT: stats_out}

        frames_in = manager.list()
        frames_out = manager.list()

        # display real-time statistics
        statsview_process = Process(target=stats_view, args=(stats, ctx.obj[DEBUG_LEVEL]))

        # if records for specified network are missing
        if not safe_key_in_dict(home_id, decoys.keys()):
            # honeypot stops and display error
            sys.exit(ERROR_MISSING_DECOYS)

        signal.signal(signal.SIGINT, signal_handler)

        # init frame transmitter
        transmitter = Transmitter(cfg, frames_out, stats)

        # if not low-interaction mode
        if not low:
            # init responder
            responder = Responder(transmitter, decoys, honeylog)
        else:
            # else responder not needed
            responder = None

        # init receiver and monitor
        receiver = Receiver(cfg, network, decoys, honeylog, frames_in, frames_out, responder)
        monitor = Monitor(cfg, network, decoys, honeylog, stats)

        receiver.monitor = monitor
        monitor.receiver = receiver

        # init traffic generator
        generator = TrafficGenerator(cfg, network, decoys, honeylog, stats, transmitter)

        # honeypot configuration process
        configuration_process = Process(target=set_configuration, args=(cfg, honeylog))

        # receiver process
        receiver_process = Process(target=receiver_target, args=(receiver, False, False))

        try:
            configuration_process.start()
            receiver_process.start()
            statsview_process.start()
            # generator works in main process
            generator.start()
        except KeyboardInterrupt:
            honeylog.info('\nTerminating...')
            receiver_process.terminate()
            configuration_process.terminate()

        configuration_process.join()
        receiver_process.join()
        statsview_process.join()
예제 #29
0
 def __init__(self):
     Thread.__init__(self)
     LogImplementer.__init__(self)
     self.socket = Transmitter()
     self.socket.setTimeout(HANDSHAKE_TIMEOUT)
     self.setName('Hand-Init Thread')
예제 #30
0
	def __init__(self):
		self.motor_speeds = [0, 0, 0]
		# Init transmitter
		self.t = Transmitter()
예제 #31
0
class CountReceiver(LogImplementer, Thread):

    counter = 0
    target = 0
    currentSequenceNumber = 0
    socket = Transmitter()
    targetPort = None

    def __init__(self, initialMessage):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.targetDevice = initialMessage.sender
        self.targetPort = initialMessage.senderAddress[1]
        self.target = unpack('>i', initialMessage.payload[4:])[0]
        self.counter = 1

    def run(self):

        self.logger.debug(f'>>>>> Received init count.')
        while self.counter < self.target:
            # Create next ack
            self.logger.debug((f'>>>> Counter: {self.counter} Sending ack'))
            self.sendNextAck()

            if self.counter < self.target:
                # listen for message
                message = self.listenForNext()

                self.logger.debug(
                    f'>>>>> Received updated count: {unpack(">i", message.payload)[0]} Need to increment counter ({self.counter})'
                )
                # assert
                self.runSanityChecks(message)
                self.counter += 1
                self.currentSequenceNumber = message.currentSequenceNumber

        self.logger.debug(
            f'>>>> Counting complete, counter: {self.counter}/{self.target}')

    def createNextAck(self):
        message = Message(MessageType.ACK, self.targetDevice)
        payload = pack('>i', self.counter)
        message.setPayload(payload)
        message.setSequenceNumbers(self.currentSequenceNumber,
                                   int(self.target / 2))

        return message

    def sendNextAck(self):
        message = self.createNextAck()
        # self.logger.info(f'sending ack to {self.targetDevice}: {self.targetPort}')
        self.socket.sendMessage(message, self.targetPort)
        self.counter += 1

    def listenForNext(self):
        try:
            return self.socket.listen()
        except:
            raise

    def runSanityChecks(self, response):
        assert len(response.payload) > 0, 'Response must have a payload'

        seqNumber = unpack(">i", response.payload)[0]
        assert (seqNumber == self.counter)
        assert (response.currentSequenceNumber == self.currentSequenceNumber +
                1)
        assert (response.sender == self.targetDevice)
예제 #32
0
class Comm:
    def __init__(self):
        self.first = True

    def start_up(self, ser, ros_is_on, traj, step_is_on):
        self.last_print_time = time.time()

        if (not self.first):
            self.ser = ser
            self.tx.change_port(ser)
            self.rx.change_port(ser)
            return

        self.first = False
        self.ros_is_on = ros_is_on
        self.step_is_on = step_is_on
        self.use_trajectory = False

        self.tx = Transmitter(ser)
        self.rx = Receiver(ser, ros_is_on)

        if (self.ros_is_on == True):
            rospy.init_node('soccer_hardware', anonymous=True)
            rospy.Subscriber("robotGoal",
                             RobotGoal,
                             self.trajectory_callback,
                             queue_size=1)
            self.rx.pub = rospy.Publisher('soccerbot/imu', Imu, queue_size=1)
            self.rx.pub2 = rospy.Publisher('soccerbot/robotState',
                                           RobotState,
                                           queue_size=1)
        else:
            trajectories_dir = os.path.join("trajectories", traj)
            try:
                self.trajectory = np.loadtxt(open(trajectories_dir, "rb"),
                                             delimiter=",",
                                             skiprows=0)

                logString("Opened trajectory {0}".format(traj))
                self.use_trajectory = True
            except IOError as err:
                logString("Error: Could not open trajectory: {0}".format(err))
                logString(
                    "(Is your shell running in the soccer-communication directory?)"
                )
                logString("Standing pose will be sent instead...")

    def print_angles(self, sent, received):
        ''' Prints out 2 numpy vectors side-by-side, where the first vector entry
            is interpreted as belonging to motor 1, the seconds to motor 2, etc.
        '''
        assert sent.shape[0] == received.shape[0]
        t = PrettyTable(['Motor Number', 'Sent', 'Received'])

        for i in range(sent.shape[0]):
            t.add_row(
                [str(i + 1),
                 round(sent[i][0], 4),
                 round(received[i][0], 2)])

        print(t)

    def print_imu(self, received):
        ''' Prints out a numpy vector interpreted as data from the IMU, in the
            order X-gyro, Y-gyro, Z-gyro, X-accel, Y-accel, Z-accel.
        '''

        t = PrettyTable(['', 'Gyro (deg/s)', 'Accel (m/s^2)'])

        t.add_row(["X", round(received[0][0], 2), round(received[3][0], 2)])
        t.add_row(["Y", round(received[1][0], 2), round(received[4][0], 2)])
        t.add_row(["Z", round(received[2][0], 2), round(received[5][0], 2)])

        print(t)

    def print_handler(self, goal_angles):
        current_time = time.time()
        if (current_time - self.last_print_time >= 1):
            self.last_print_time = current_time
            print('\n')
            logString("Received: {0}".format(self.rx.num_receptions))
            logString("Transmitted: {0}\n".format(self.tx.num_transmissions))
            if (self.rx.num_receptions > 0):
                # Prints the last valid data received
                self.print_angles(goal_angles[0:12],
                                  self.rx.received_angles[0:12])
                self.print_imu(self.rx.received_imu)

    def communicate(self, goal_angles):
        self.tx.transmit(goal_angles)
        self.rx.receive()
        self.print_handler(goal_angles)

    def trajectory_callback(self, robotGoal):
        '''
        Used by ROS. Converts the motor array from the order and sign convention
        used by controls to that used by embedded
        '''
        m = getCtrlToMcuAngleMap()
        goalangles = m.dot(robotGoal.trajectories[0:18])
        goalangles = goalangles[:, np.newaxis]
        self.communicate(goalangles)

    def begin_event_loop(self):
        if (self.ros_is_on == True):
            rospy.spin()
        else:
            while (True):
                if (self.use_trajectory):
                    # Iterate through the static trajectory forever
                    # TODO: If the static trajectories are ever re-generated, we will need
                    # TODO: to dot the trajectories with the ctrlToMcuAngleMap to shuffle
                    # TODO: them properly
                    for i in range(self.trajectory.shape[1]):
                        if (self.step_is_on):
                            wait = input('Press enter to send next pose')

                        goal_angles = self.trajectory[:, i:i + 1]
                        self.communicate(goal_angles)
                else:
                    # Send standing pose
                    if (self.step_is_on):
                        wait = input('Press enter to send next pose')

                    self.communicate(np.zeros((18, 1)))
예제 #33
0
 def __init__(self, transmitter_count):
     self.transmitter_count = transmitter_count
     self.transmitter = []
     for i in range(1, self.transmitter_count + 1):
         self.transmitter.append(Transmitter(i, medium))