Esempio n. 1
0
class Libp2p:
    def __init__(self, socketPath):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

        try:
            self.sock.connect(socketPath)
            self.stream = Stream(self.sock)
        except socket.error as msg:
            print(msg, sys.stderr)
            sys.exit(1)

    def identify(self):
        req = p2pd_pb2.Request()
        req.type = p2pd_pb2.Request.IDENTIFY

        bb = req.SerializeToString()

        self.stream.write(bb)
        data = self.stream.read()

        res = p2pd_pb2.Response()
        res.ParseFromString(data)

        id = base58.b58encode(res.identify.id)

        addrs = []
        for add in res.identify.addrs:
            ma = Multiaddr(bytes_addr=add.hex())
            addrs.append(ma)

        return [id, addrs]

    def connect(self, peerId, addrs):

        req = p2pd_pb2.Request()
        for addr in addrs:
            req.connect.addrs.append(addr.to_bytes())
        req.connect.peer = base58.b58decode(peerId)
        req.type = p2pd_pb2.Request.CONNECT

        outbound = req.SerializeToString()
        self.stream.write(outbound)

        inbound = self.stream.read()
        res = p2pd_pb2.Response()
        res.ParseFromString(inbound)

        print(res)
Esempio n. 2
0
class Test:
    def __init__(self, stream):
        self.display = Display()
        self.stream = Stream(stream)

    def parse(self):
        if not self.stream.line:
            return False
        parse = self.stream.line.split('#')
        if len(parse) == 2:
            try:
                self.result = int(parse[0].rstrip(' '))
                self.message = parse[1].rstrip(' ')
            except:
                return False
            if self.result != 0 and self.result != 1:
                return False
            return True
        return False

    def launch(self):
        sucess = 0
        total = 0
        while self.stream.read():
            if self.parse():
                if self.result == 1:
                    sucess += 1
                else:
                    self.display.error("Error on" + self.message)
                total += 1
        self.display.summary(sucess, total)
Esempio n. 3
0
class Test:
  def __init__(self, stream):
    self.display = Display()
    self.stream = Stream(stream)

  def parse(self):
    if not self.stream.line:
      return False
    parse = self.stream.line.split('#')
    if len(parse) == 2:
      try:
        self.result = int(parse[0].rstrip(' '))
        self.message = parse[1].rstrip(' ')
      except:
        return False
      if self.result != 0 and self.result != 1:
        return False
      return True
    return False

  def launch(self):
    sucess = 0
    total = 0
    while self.stream.read():
      if self.parse():
        if self.result == 1:
          sucess += 1
        else:
          self.display.error("Error on" + self.message)
        total += 1
    self.display.summary(sucess, total)
Esempio n. 4
0
def mainStream():
    s = Stream()
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    nb_bytes_salt = 4
    last_salt = ''
    last_message = b''
    packet = ''
    size = 300

    if(len(sys.argv) == 2):
        sock.bind((sys.argv[1],53))
    else:
        sock.bind(("127.0.0.1",53))
    
    while(True):
        query, ad = sock.recvfrom(4096)
        query = bytesToMessage(query)
        data = query.qList[0].qname.split(".devtoplay.com")[0]
        salt = data[:nb_bytes_salt]
        answer = []

        if(salt != last_salt):
            if('you' in data):
                if(len(packet) > 0):
                    sys.stdout.buffer.write(bytes(packet,'latin-1'))
                    sys.stdout.flush()
                    packet=''
                
                if(len(answer) == 0):
                    d = s.read()
                    answer = [d[i:i+size] for i in range(0,len(d),size)]
                    if(len(answer) == 0 or answer[0] != b'nothing'):
                        answer.append(b'nothing')

                message = Message(Header(query.header.id,1,0,False,False,True,True,0,0,1,1,0,0),
                                  query.qList,
                                  [RR(query.qList[0].qname,writeTXT(answer.pop(0)),16,1,1)])
            else:
                message = defaultMessage(query)
                if(query.qList[0].qtype == 16 and data != 'devtoplay.com'):
                    if(nothing in data):
                        sys.stdout.buffer.write(bytes(packet,'latin-1'))
                        sys.stdout.flush()
                        packet = b''
                    else:
                        split = data.split('.')
                        data = ''
                    
                        for i in range(1,len(split),1):
                            data += insertPoint(split[i])
                        packet += data
        else:
            message = last_message
            message.header.id = query.header.id

        sock.sendto(message.getBytes(),ad)
        last_message = message
        last_salt = salt
class WirelessHeadset(Headset):
    """This class represents the wireless version of the mindwave

    Args:
        dev: device link 
        headset: the id of mindwave wireless version

    It has the basic functionality to connect, autoconnect and disconnect

    """

    def __init__(self, dev=None, headset_id=None, rate=None):

        Headset.__init__(self, headset_id)

        self.device = dev
        self.bauderate = rate

        self.stream = Stream(device=self.device, bauderate=rate, version=Version.MINDWAVE)
        time.sleep(2)

        self.connect()
        self.run(self.stream)

    # def open(self):
    #     if not self.stream or not self.stream.IsOpen():
    #         #self.stream = stream.stream(self.device, baudrate=115200, parity=stream.PARITY_NONE, stopbits=stream.STOPBITS_ONE,
    #         #    bytesize=stream.EIGHTBITS, writeTimeout=0, timeout=3, rtscts=True, xonxoff=False)
    #         self.stream = serial.Serial(self.device, self.baudrate, timeout=0.001, rtscts=True)

    def autoconnect(self):
        """This method autoconnects to the mindwave every."""

        self.stream.getStream().write(BytesStatus.AUTOCONNECT)  
        #the dongle switch to autoconnect mode it must wait 10 second to connect any headset
        time.sleep(10)

    def connect(self):
        """This method connects to the mindwave with the id."""

        if self.id is not None:
            # we send a byte to CONNECTED and other byte in hex of headset id
            self.stream.getStream().write(''.join([BytesStatus.CONNECT, self.id.decode('hex')]))
        else:
            self.autoconnect()

    def disconnect(self):
        """This method disconnects the mindwave."""

        self.stream.getStream().write(BytesStatus.DISCONNECT)
         
    def echo_raw(self):
        """This method prints the raw data from mindwave."""
        
        while 1:
            #time.sleep()
            data = self.stream.read(1)
    
            for b in data:
                print '0x%s, ' % b.encode('hex'),
            print ""
Esempio n. 6
0
from fps import FPS
import time
import cv2

# enable optimised mode if possible
optimized = cv2.useOptimized()
if not optimized:
    cv2.setUseOptimized(True)

# initialise new motion detector
motionDetector = MotionDetector(20, 20, 200)
motionDetector.enableDifferenceImage()

# start new video capture and initialise new frames
capture = Stream(src=0).start()
ret, frame = capture.read()
ret2, frame2 = capture.read()

# initialise an array to store detected objects
objects = []

# start FPS recorder
fps = FPS().start()

while True:

    # get new detected objects
    objects = motionDetector.detect(frame, frame2)

    # get 1st frame and make a copy for display
    ret, frame = capture.read()
Esempio n. 7
0
class Waves(object):
    def __init__(self):
        pygame.init()

        self.outputs = Outputs()
        self.stream = Stream(channels=1,
                             sample_rate=60 * 10**3,
                             sample_size=2**11)

        self.mouse_frequency = 0.0

        # visual params
        self.background_color = pygame.Color(50, 50, 50)
        self.colorA = pygame.Color("#ff0000")
        self.colorB = pygame.Color("#0000ff")
        self.num_bars = self.outputs.get_divisor()

        # surface params
        self.height = 1000
        self.dimensions = numpy.array([self.outputs.get_width(), self.height])
        self.surface_flags = pygame.HWSURFACE | pygame.DOUBLEBUF
        self.surface = pygame.display.set_mode(self.dimensions,
                                               self.surface_flags)
        self.time_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.freq_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.control_surface = pygame.Surface(self.dimensions // 2)
        self.control_surface.set_colorkey(self.background_color)

        self.controls = Controls(self.control_surface)

        self.sliders = {
            'pull':
            Slider(self.control_surface,
                   pygame.Rect(300, 46, 100, 10),
                   10,
                   15,
                   value=0.5),
            'smooth':
            Slider(self.control_surface,
                   pygame.Rect(300, 66, 100, 10),
                   10,
                   15,
                   value=0.5)
        }

        # smoothing history array
        self.t_history = numpy.full(self.num_bars, 0.5)
        self.f_history = numpy.full(self.num_bars, 0.0)

    def get_samples(self):
        format = '<{}h'.format(self.stream.sample_size)
        byte_string = self.stream.read(self.stream.sample_size)
        return list(map(util.normalize, struct.unpack(format, byte_string)))

    def draw_time_bars(self, samples, surface):
        width, height = surface.get_size()
        bar_width = width / self.num_bars

        s = self.sliders['smooth'].value
        for i in range(self.num_bars):
            power_i = samples[i]
            power_s = self.t_history[i] * s + power_i * (1 - s)
            power = self.t_history[i] = power_s

            bar_height = power * height
            top = height - bar_height
            left = i * bar_width
            rect = (left, top, bar_width, 5)  #bar_height)

            color = util.gradient(power, self.colorA, self.colorB)
            pygame.draw.rect(surface, color, rect)

    def draw_freq_bars(self, samples, surface):
        width, height = surface.get_size()
        y_max = self.stream.sample_size // 2
        bar_width = width / self.num_bars

        yf = numpy.log(numpy.abs(numpy.fft.fft(samples)) +
                       1) / numpy.log(y_max)

        s = self.sliders['smooth'].value

        pull = 1 - self.sliders['pull'].value
        g = (self.num_bars - 1) * (self.stream.sample_size // 2 - 1) * pull
        v, h = util.shift_inverse_consts(0, 1, self.num_bars - 1,
                                         self.stream.sample_size // 2 - 1, g)

        for x in range(self.num_bars):
            y = util.shift_inverse(x, g, v, h)

            power_i = yf[int(y)]
            power_s = self.f_history[x] * s + power_i * (1 - s)
            power = self.f_history[x] = power_s
            if power > 1.0:
                power = 1.0

            bar_height = power * height
            top = height - bar_height
            left = x * bar_width
            rect = (left, top, bar_width, bar_height)
            color = util.gradient(power, self.colorA, self.colorB)
            pygame.draw.rect(surface, color, rect)

    def resize_bars(self):
        self.num_bars = self.outputs.get_divisor()
        self.t_history.resize(self.num_bars)
        self.f_history.resize(self.num_bars)

    def resize(self):
        width = self.outputs.get_width()
        height = self.height
        self.time_surface = pygame.Surface((width, height // 2))
        self.freq_surface = pygame.Surface((width, height // 2))
        self.surface = pygame.display.set_mode((width, height),
                                               self.surface_flags)
        self.resize_bars()

    def process_key(self, key):
        HEIGHT_DELTA = 100
        HEIGHT_MIN = 300

        SIZE_MIN = 1

        RATE_DELTA = 1000
        RATE_MIN = 0

        mods = pygame.key.get_mods()
        shift = mods & pygame.KMOD_SHIFT

        if key == ord('b'):
            if shift:
                self.outputs.next_divisor()
            else:
                self.outputs.prev_divisor()
            self.resize_bars()

        if key == ord('h'):
            if shift:
                self.height += HEIGHT_DELTA
            elif self.height > HEIGHT_MIN:
                self.height -= HEIGHT_DELTA
            self.resize()

        if key == ord('n'):
            k = 2 if shift else 0.5
            if self.stream.sample_size > SIZE_MIN:
                self.stream.sample_size *= k

        if key == ord('r'):
            k = 1 if shift else -1
            if self.stream.sample_rate > RATE_MIN:
                self.stream.sample_rate += k * RATE_DELTA

        if key == ord('w'):
            if shift:
                self.outputs.next_width()
            else:
                self.outputs.prev_width()
            self.resize()

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.exit()

            if event.type == pygame.KEYDOWN:
                self.process_key(event.key)

            if event.type == pygame.MOUSEMOTION:
                x = event.pos[0]

                R = self.stream.sample_rate
                N = self.stream.sample_size
                pull = 1 - self.sliders['pull'].value
                g = (self.num_bars - 1) * (N // 2 - 1) * pull
                v, h = util.shift_inverse_consts(0, 1, self.num_bars - 1,
                                                 N // 2 - 1, g)

                bar_width = self.outputs.get_width() / self.num_bars
                bar_index = math.floor(x / bar_width)
                self.mouse_frequency = util.shift_inverse(
                    bar_index, g, v, h) * (R / 2) / (N / 2 - 1)

                for slider in self.sliders.values():
                    if slider.moving:
                        slider.set_value(x)

            if event.type == pygame.MOUSEBUTTONDOWN:
                for slider in self.sliders.values():
                    if slider.get_handle_rect().collidepoint(event.pos):
                        slider.moving = True

            if event.type == pygame.MOUSEBUTTONUP:
                for slider in self.sliders.values():
                    slider.moving = False

    def exit(self):
        self.stream.close()
        pygame.display.quit()
        pygame.quit()
        sys.exit(0)

    def loop(self):
        self.process_events()

        surfaces = [self.time_surface, self.freq_surface, self.control_surface]
        for surface in surfaces:
            surface.fill(self.background_color)

        samples = self.get_samples()

        self.controls.draw(self.stream.sample_rate, self.stream.sample_size,
                           self.sliders['pull'].value,
                           self.sliders['smooth'].value,
                           self.outputs.get_width(), self.num_bars,
                           self.mouse_frequency)

        for slider in self.sliders.values():
            slider.draw()

        self.draw_time_bars(samples, self.time_surface)
        self.draw_freq_bars(samples, self.freq_surface)

        self.surface.blit(self.time_surface, (0, 0))
        self.surface.blit(self.freq_surface, (0, self.height // 2))
        self.surface.blit(self.control_surface, (0, 0))

        pygame.display.flip()
Esempio n. 8
0
class Lexer():
    def __init__(self, stream):
        self.stream = Stream(stream)
        self.buffer = []
        self.tokens = []
        self.line = 1
        self.col = 1

    def read(self):
        r = self.stream.read()

        if r == "\n":
            self.col = 1

        return r

    def next(self):
        r = self.read()

        if r != "\x00":
            self.buffer.append(r)

        return r

    def ignore(self):
        self.buffer = []

    def skip(self):
        self.next()
        self.ignore()

    def fast_forward(self, n):
        for i in range(n):
            self.next()

    def peek(self):
        r = self.stream.read()
        self.stream.unread()

        return r

    def emit_value(self, token_type, value):
        t = Token((self.line, self.col), token_type, value)
        self.tokens.append(t)
        print(self.tokens[-1])
        self.ignore()

    def emit(self, token_type):
        self.emit_value(token_type, "".join(self.buffer))

    def follow(self, n):
        to_unread = 0
        for expected in n:
            r = self.stream.read()
            to_unread += 1

            if expected != r:
                return False

        for i in range(to_unread):
            self.stream.unread()

        return True

    def lex_main(self):
        while True:
            n = self.peek()

            if n == "#":
                return self.comment
            elif n in ("\n", "\r"):
                self.skip()
            elif n in (" ", "\t"):
                self.skip()
            elif n == '"':
                return self.string

            if n == "\x00":
                break

            time.sleep(0.25)

        return None

    def comment(self):
        while True:
            n = self.peek()

            if n == '\n' or n == "\x00":
                break

            if n == "\r" and self.follow("\r\n"):
                break

            self.next()

        self.ignore()

        return self.lex_main

    def string(self):
        self.skip()
        while True:
            n = self.peek()

            if n == '\n' or n == "\x00":
                self.emit(tt.tokenError)
                break

            if n == "\r" and self.follow("\r\n"):
                self.emit(tt.tokenError)
                break

            if n == '"':
                self.emit(tt.tokenString)
                self.skip()
                break

            self.next()

        return self.lex_main



    def run(self):
        state = self.lex_main
        while state != None:
            state = state()
Esempio n. 9
0
# initialise new frontal face detector
faceDetector = ObjectDetector(model='FRONTAL_FACE', minSize=35)

# start new video capture
capture = Stream(src=0).start()

# initialise an array to store detected objects
objects = []

# start FPS recorder
fps = FPS().start()

while True:

    ret, frame = capture.read()

    # optional resize to reduce computation
    # frame = cv2.resize(frame, (0, 0), fx=0.35, fy=0.35)

    # get new detected objects
    objects = faceDetector.detect(frame)

    # draw rectangle around each detected object
    for (x, y, w, h) in objects:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255, 0), 1)

    # display result
    cv2.imshow('Video', frame)
    
    # update FPS data