Example #1
0
    def handle(self):
        data = 'dummy'
        print("Client connected with: ", self.client_address)
        devaddr = "f1:99:d1:ce:d9:1d random"
        bleconn = Peripheral(devaddr)
        while len(data):
            data = self.request.recv(1024)
            self.request.send(data)
            cmd = asc2hex(data.decode('utf-8')).rstrip('0d0a')
            print("data", len(data))
            if len(data) != 0:
                bleconn.writeCharacteristic(0x0011, cmd)

        print("Client exited")
        bleconn.disconnect()
        self.request.close()
Example #2
0
    def handle(self):
        data = 'dummy'
        print ("Client connected with: ", self.client_address)
        devaddr = "f1:99:d1:ce:d9:1d random"
        bleconn = Peripheral(devaddr)
        while len(data):
            data = self.request.recv(1024)
            self.request.send(data)
            cmd=asc2hex(data.decode('utf-8')).rstrip('0d0a')
            print ("data",len(data))
            if len(data)!=0:
                bleconn.writeCharacteristic(0x0011,cmd)

        print("Client exited")
        bleconn.disconnect()
        self.request.close()
Example #3
0
def threaded_client(conn):
    conn.send(str.encode('Welcome, to smartLink\n'))
    
    while True:
        
        a='s'
        while a=='s':
            try:
                bleconn = Peripheral("f1:99:d1:ce:d9:1d random")
                while True:
                    #-----------receive data from telnet---------------------
                    data=conn.recv(2048)
                    if not data:
                        a='n'
                        break
                    print("data",data[0])
                    if data[0]!=255:
                        reply = 'Server output:' +data.decode('utf-8')
                        print("raw server ouput",data.decode('utf-8'))
                        cmd=asc2hex(data.decode('utf-8')).rstrip('0d0a')
                        print("raw cmd:",cmd)
                        bleconn.writeCharacteristic(0x0011,cmd)
                        conn.sendall(str.encode(reply))
            except socket.error as e:
                if isinstance(e.args, tuple):
                    print("errno is %d" % e[0])
                    if e[0] == errno.EPIPE:
                        # remote peer disconnected
                        print("Detected remote disconnect")
                    else:
                        # determine and handle different error
                        pass
                else:
                    print("socket error ", e)

                bleconn.disconnect()
                conn.close()
                break
            except BTLEException as e:
                #conn.sendall(str.encode("ERROR!!!!"))
                print(e)
                #conn.sendall(str.encode("Try again (y/n)?"))
    bleconn.disconnect()            
    conn.close()
Example #4
0
 def handle(self):
     data = 'dummy'
     isConnected=False
     print ("Client connected with: ", self.client_address)
     while len(data):
         data = self.request.recv(1024)
         if len(data)>0 and len(data)<5 and data[0]==99 and isConnected==False:  #Not null, its (C)onnect command, 4 len command
             if data[1]>=48 and data[1]<=57:
                 try:
                     bleconn = Peripheral(elements[data[1]-48])
                 except BTLEException as e:
                     self.request.send(b'error connecting to device\r\n')
                     isConnected=False
                 else:
                     isConnected=True
                     self.request.send(b'connected\r\n')
                     bleconn.writeCharacteristic(0x000f,binascii.a2b_hex("0100"))
         if len(data)!=0 and isConnected==True:
             cmd=data.rstrip(b'\r\n')
             if cmd!=b'' and cmd[0]!=99 and cmd[0]!=100:  #if command is not (c)onnect or (d)isconnect
                 try:
                     notify=bleconn.writeCharacteristicWn(0x0011,cmd,True)
                 except BTLEException as e:
                     isConnected=False
                     self.request.send(b'error writing to device\r\n')
                 else:
                     isConnected=True
                     self.request.send(notify['d'][0])
                     self.request.send(b'\r\n')
         if len(data)>0 and len(data)<5 and data[0]==100 and isConnected==True:  #
             cmd=data.rstrip(b'\r\n')
             if cmd!=b'':
                 bleconn.disconnect()
                 self.request.send(b'disconnected\r\n')
                 isConnected=False
     print("Client exited")
     if isConnected==True:
         bleconn.disconnect()
     self.request.close()
Example #5
0
class OpenBCIBoard(object):
  """
  Handle a connection to an OpenBCI board.

  Args:
    port: MAC address of the Ganglion Board. "None" to attempt auto-detect.
    aux: enable on not aux channels (i.e. switch to 18bit mode if set)
    impedance: measures impedance when start streaming
    timeout: in seconds, if set will try to disconnect / reconnect after a period without new data -- should be high if impedance check
    max_packets_to_skip: will try to disconnect / reconnect after too many packets are skipped
    baud, filter_data, daisy: Not used, for compatibility with v3
  """

  def __init__(self, port=None, baud=0, filter_data=False,
    scaled_output=True, daisy=False, log=True, aux=False, impedance=False, timeout=2, max_packets_to_skip=20):
    # unused, for compatibility with Cyton v3 API
    self.daisy = False
    # these one are used 
    self.log = log # print_incoming_text needs log
    self.aux = aux
    self.streaming = False
    self.timeout = timeout
    self.max_packets_to_skip = max_packets_to_skip
    self.scaling_output = scaled_output
    self.impedance = False

    # might be handy to know API
    self.board_type = "ganglion"

    print("Looking for Ganglion board")
    if port == None:
      port = self.find_port()   
    self.port = port # find_port might not return string

    self.connect()

    self.streaming = False
    # number of EEG channels and (optionally) accelerometer channel
    self.eeg_channels_per_sample = 4
    self.aux_channels_per_sample = 3 
    self.imp_channels_per_sample = 5 
    self.read_state = 0
    self.log_packet_count = 0
    self.packets_dropped = 0
    self.time_last_packet = 0

    # Disconnects from board when terminated
    atexit.register(self.disconnect)

  def getBoardType(self):
    """ Returns the version of the board """
    return self.board_type

  def setImpedance(self, flag):
    """ Enable/disable impedance measure """
    self.impedance = bool(flag)
  
  def connect(self):
    """ Connect to the board and configure it. Note: recreates various objects upon call. """
    print ("Init BLE connection with MAC: " + self.port)
    print ("NB: if it fails, try with root privileges.")
    self.gang = Peripheral(self.port, 'random') # ADDR_TYPE_RANDOM

    print ("Get mainservice...")
    self.service = self.gang.getServiceByUUID(BLE_SERVICE)
    print ("Got:" + str(self.service))
    
    print ("Get characteristics...")
    self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0]
    print ("receive, properties: " + str(self.char_read.propertiesToString()) + ", supports read: " + str(self.char_read.supportsRead()))

    self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0]
    print ("write, properties: " + str(self.char_write.propertiesToString()) + ", supports read: " + str(self.char_write.supportsRead()))

    self.char_discon = self.service.getCharacteristics(BLE_CHAR_DISCONNECT)[0]
    print ("disconnect, properties: " + str(self.char_discon.propertiesToString()) + ", supports read: " + str(self.char_discon.supportsRead()))

    # set delegate to handle incoming data
    self.delegate = GanglionDelegate(self.scaling_output)
    self.gang.setDelegate(self.delegate)

    # enable AUX channel
    if self.aux:
      print("Enabling AUX data...")
      try:
        self.ser_write(b'n')
      except Exception as e:
        print("Something went wrong while enabling aux channels: " + str(e))
    
    print("Turn on notifications")
    # nead up-to-date bluepy, cf https://github.com/IanHarvey/bluepy/issues/53
    self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0]
    try:
      self.desc_notify.ser_write(b"\x01")
    except Exception as e:
      print("Something went wrong while trying to enable notification: " + str(e))
    
    print("Connection established")

  def init_streaming(self):
    """ Tell the board to record like crazy. """
    try:
      if self.impedance:
        print("Starting with impedance testing")
        self.ser_write(b'z')
      else:
        self.ser_write(b'b')
    except Exception as e:
      print("Something went wrong while asking the board to start streaming: " + str(e))
    self.streaming = True
    self.packets_dropped = 0
    self.time_last_packet = timeit.default_timer() 
    
  def find_port(self):
    """Detects Ganglion board MAC address -- if more than 1 around, will select first. Needs root privilege."""

    print("Try to detect Ganglion MAC address. NB: Turn on bluetooth and run as root for this to work! Might not work with every BLE dongles.")
    scan_time = 5
    print("Scanning for 5 seconds nearby devices...")

    #   From bluepy example
    class ScanDelegate(DefaultDelegate):
      def __init__(self):
        DefaultDelegate.__init__(self)

      def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
          print ("Discovered device: " + dev.addr)
        elif isNewData:
          print ("Received new data from: " + dev.addr)
  
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(scan_time)

    nb_devices = len(devices)
    if nb_devices < 1:
      print("No BLE devices found. Check connectivity.")
      return ""
    else:
      print("Found " + str(nb_devices) + ", detecting Ganglion")
      list_mac = []
      list_id = []
  
      for dev in devices:
        # "Ganglion" should appear inside the "value" associated to "Complete Local Name", e.g. "Ganglion-b2a6"
        for (adtype, desc, value) in dev.getScanData():
          if desc == "Complete Local Name" and   value.startswith("Ganglion"): 
            list_mac.append(dev.addr)
            list_id.append(value)
            print("Got Ganglion: " + value + ", with MAC: " + dev.addr)
            break
    nb_ganglions = len(list_mac)
  
    if nb_ganglions < 1:
      print("No Ganglion found ;(")
      raise OSError('Cannot find OpenBCI Ganglion MAC address')

    if nb_ganglions > 1:
      print("Found " + str(nb_ganglions) + ", selecting first")

    print("Selecting MAC address " + list_mac[0] + " for " + list_id[0])
    return list_mac[0]
    
  def ser_write(self, b):
    """Access serial port object for write""" 
    self.char_write.ser_write(b)

  def ser_read(self):
    """Access serial port object for read""" 
    return self.char_read.ser_read()

  def ser_inWaiting(self):
      """ Slightly different from Cyton API, return True if ASCII messages are incoming."""
      # FIXME: might have a slight problem with thread because of notifications...
      if self.delegate.receiving_ASCII:
        # in case the packet indicating the end of the message drops, we use a 1s timeout
        if timeit.default_timer() - self.delegate.time_last_ASCII > 2:
          self.delegate.receiving_ASCII = False
      return self.delegate.receiving_ASCII
  
  def getSampleRate(self):
      return SAMPLE_RATE
  
  def getNbEEGChannels(self):
    """Will not get new data on impedance check."""
    return self.eeg_channels_per_sample
  
  def getNbAUXChannels(self):
    """Might not be used depending on the mode."""
    return self.aux_channels_per_sample

  def getNbImpChannels(self):
    """Might not be used depending on the mode."""
    return  self.imp_channels_per_sample

  def start_streaming(self, callback, lapse=-1):
    """
    Start handling streaming data from the board. Call a provided callback
    for every single sample that is processed

    Args:
      callback: A callback function -- or a list of functions -- that will receive a single argument of the
          OpenBCISample object captured.
    """
    if not self.streaming:
      self.init_streaming()

    start_time = timeit.default_timer()

    # Enclose callback funtion in a list if it comes alone
    if not isinstance(callback, list):
      callback = [callback]

    while self.streaming:
      # should the board get disconnected and we could not wait for notification anymore, a reco should be attempted through timeout mechanism
      try:
        # at most we will get one sample per packet
        self.waitForNotifications(1./self.getSampleRate())
      except Exception as e:
        print("Something went wrong while waiting for a new sample: " + str(e))
      # retrieve current samples on the stack
      samples = self.delegate.getSamples()
      self.packets_dropped = self.delegate.getMaxPacketsDropped()
      if samples:
        self.time_last_packet = timeit.default_timer() 
        for call in callback:
          for sample in samples:
            call(sample)
      
      if(lapse > 0 and timeit.default_timer() - start_time > lapse):
        self.stop();
      if self.log:
        self.log_packet_count = self.log_packet_count + 1;
  
      # Checking connection -- timeout and packets dropped
      self.check_connection()

  def waitForNotifications(self, delay):
    """ Allow some time for the board to receive new data. """
    self.gang.waitForNotifications(delay)


  def test_signal(self, signal):
    """ Enable / disable test signal """
    if signal == 0:
      self.warn("Disabling synthetic square wave")
      try:
        self.char_write.ser_write(b']')
      except Exception as e:
        print("Something went wrong while setting signal: " + str(e))
    elif signal == 1:
      self.warn("Eisabling synthetic square wave")
      try:
        self.char_write.ser_write(b'[')
      except Exception as e:
        print("Something went wrong while setting signal: " + str(e))
    else:
      self.warn("%s is not a known test signal. Valid signal is 0-1" %(signal))

  def set_channel(self, channel, toggle_position):
    """ Enable / disable channels """
    try:
      #Commands to set toggle to on position
      if toggle_position == 1:
        if channel is 1:
          self.ser.ser_write(b'!')
        if channel is 2:
          self.ser.ser_write(b'@')
        if channel is 3:
          self.ser.ser_write(b'#')
        if channel is 4:
          self.ser.ser_write(b'$')
      #Commands to set toggle to off position
      elif toggle_position == 0:
        if channel is 1:
          self.ser.ser_write(b'1')
        if channel is 2:
          self.ser.ser_write(b'2')
        if channel is 3:
          self.ser.ser_write(b'3')
        if channel is 4:
          self.ser.ser_write(b'4')
    except Exception as e:
      print("Something went wrong while setting channels: " + str(e))
    
  """

  Clean Up (atexit)

  """
  def stop(self):
    print("Stopping streaming...")
    self.streaming = False
    # connection might be already down here
    try:
      if self.impedance:
        print("Stopping with impedance testing")
        self.ser_write(b'Z')
      else:
        self.ser_write(b's')
    except Exception as e:
      print("Something went wrong while asking the board to stop streaming: " + str(e))
    if self.log:
      logging.warning('sent <s>: stopped streaming')

  def disconnect(self):
    if(self.streaming == True):
      self.stop()
    print("Closing BLE..")
    try:
      self.char_discon.ser_write(b' ')
    except Exception as e:
      print("Something went wrong while asking the board to disconnect: " + str(e))
    # should not try to read/write anything after that, will crash
    try:
      self.gang.disconnect()
    except Exception as e:
      print("Something went wrong while shutting down BLE link: " + str(e))
    logging.warning('BLE closed')
       

  """

      SETTINGS AND HELPERS

  """
  def warn(self, text):
    if self.log:
      #log how many packets where sent succesfully in between warnings
      if self.log_packet_count:
        logging.info('Data packets received:'+str(self.log_packet_count))
        self.log_packet_count = 0;
      logging.warning(text)
    print("Warning: %s" % text)

  def check_connection(self):
    """ Check connection quality in term of lag and number of packets drop. Reinit connection if necessary. FIXME: parameters given to the board will be lost."""
    # stop checking when we're no longer streaming
    if not self.streaming:
      return
    #check number of dropped packets and duration without new packets, deco/reco if too large
    if self.packets_dropped > self.max_packets_to_skip:
      self.warn("Too many packets dropped, attempt to reconnect")
      self.reconnect()
    elif self.timeout > 0 and timeit.default_timer() - self.time_last_packet > self.timeout:
      self.warn("Too long since got new data, attempt to reconnect")
      #if error, attempt to reconect
      self.reconnect()

  def reconnect(self):
    """ In case of poor connection, will shut down and relaunch everything. FIXME: parameters given to the board will be lost."""
    self.warn('Reconnecting')
    self.stop()
    self.disconnect()
    self.connect()
    self.init_streaming()
Example #6
0
File: pi.py Project: dhong44/HVAC
from btle import Peripheral, UUID

simblee = Peripheral('CC:9B:84:26:0F:AC', 'random')

serviceUUID = UUID('2A00')

char = simblee.getCharacteristics(uuid = serviceUUID)[0]

char.write('Simblee')

print char.read()

simblee.disconnect()
Example #7
0
    print("Connecting to:", devaddr)
    a = 's'
    while a == 's':
        try:
            conn = Peripheral(devaddr)
            while True:
                n = input("Ponga (s) para salir:")
                try:
                    conn.writeCharacteristic(0x0011, str.encode(n))
                except BTLEException as e:
                    print("write error:")
                    print(e)
                    print("Try again? (s/n)")
                    b = input()
                    if b == 's':
                        a = 's'
                        break
                else:
                    b = 'n'
                if n.strip() == 's':
                    a = 'n'
                    break
            conn.disconnect()
        except BTLEException as e:
            print("ERROR!!!!")
            print(e)
            print("desea intentarlo de nuevo (s/n)?")
            a = input()
        finally:
            print("saliendo")
Example #8
0
class LEDE:

    def __init__(self, addr):
        self.conn = Peripheral(addr)
        self.conn.discoverServices()  # To avoid bug(?) in getServiceByUUID
        self.info = None
        self.writeHnd = None

    def _read_info(self, service, characteristics_uuid):
        ch = service.getCharacteristics(characteristics_uuid)
        name = AssignedNumbers.getCommonName(ch[0].uuid)
        self.info[name] = ch[0].read().decode()

    def get_info(self):
        if self.info:
            return self.info

        self.info = {}
        svc = self.conn.getServiceByUUID('180A')  # Device Information
        self._read_info(svc, '2a24')
        self._read_info(svc, '2a26')
        self._read_info(svc, '2a27')
        self._read_info(svc, '2a29')
        return self.info

    def _random(self):
        return random.randrange(256)

    def _checksum(self, cmd):
        s = 28
        for i in cmd:
            s += i
        return s&255

    def _pack_data(self, cmd, rdcs):
        cmd = list(cmd)
        if rdcs:
            cmd.append(self._random())
            cmd.append(self._checksum(cmd))
        cmd.append(0xd)
        return binascii.a2b_hex('aa0afc3a8601' + ''.join('%02X'%x for x in cmd))

    def write(self, cmd, rdcs = True):
        if self.writeHnd is None:
            svc = self.conn.getServiceByUUID('fff0')  # Control
            self.writeHnd = svc.getCharacteristics('fff1')[0]  # Aka Handle 0x21
        self.writeHnd.write(self._pack_data(cmd, rdcs))
        time.sleep(.2)

    def disconnect(self):
        self.conn.disconnect()

    def command_on(self):
        """Switch the light on"""
        self.write((0x0a, 0x01, 0x01, 0x00, 0x28), False)
        
    def command_off(self):
        """Switch the light off"""
        self.write((0x0a, 0x01, 0x00, 0x01, 0x28), False)
        
    def command_white_reset(self):
        """Switch to White Mode"""
        self.write((0x0d, 0x06, 0x02, 0x80, 0x80, 0x80, 0x80, 0x80))

    def command_set_brightness(self, value):
        """Set Brightness (value between 0 and 9)"""
        if value >= 0 and value <= 9:
            self.write((0x0c, 0x01, value + 2))

    def command_set_cct(self, value):
        """Set Colour Temperature (value between 0 and 9)"""
        if value >= 0 and value <= 9:
            self.write((0x0e, 0x01, value + 2))

    def command_rgb(self, red, green, blue):
        """Set RGB Colour"""
        self.write((0x0d, 0x06, 0x01, red&255, green&255, blue&255, 0x80, 0x80))

    def command_preset(self, value):
        """Use Preset (value between 1 and 10)"""
        if value >= 0 and value <= 10:
            self.write((0x0b, 0x01, value))

    def command_night_mode(self):
        """Start Night Mode (20 minutes)"""
        self.write((0x10, 0x02, 0x03, 0x01))