Beispiel #1
0
    def get_connection_to_badge(cls, timeout_seconds=10):
        # Get the BLE provider for the current platform.
        ble = Adafruit_BluefruitLE.get_provider()

        # Initialize the BLE system.  MUST be called before other BLE calls!
        ble.initialize()

        # Clear any cached data because both bluez and CoreBluetooth have issues with
        # caching data and it going stale.
        ble.clear_cached_data()

        # Get the first available BLE network adapter and make sure it's powered on.
        adapter = ble.get_default_adapter()
        adapter.power_on()

        # Disconnect any currently connected UART devices.  Good for cleaning up and
        # starting from a fresh state.
        logger.debug('Disconnecting any connected UART devices...')
        ble.disconnect_devices([UART_SERVICE_UUID])

        # Scan for UART devices.
        logger.debug('Searching for UART device...')
        try:
            adapter.start_scan()
            device = ble.find_device(service_uuids=[UART_SERVICE_UUID],
                                     name="HDBDG",
                                     timeout_sec=timeout_seconds)
            if device is None: return None
        finally:
            # Make sure scanning is stopped before exiting.
            adapter.stop_scan()

        return cls(device)
Beispiel #2
0
def start(user_system_setup_func):  #pragma: no cover
    """
        Main entry point into running everything.

        Just pass in the async co-routine that instantiates all your hubs, and this
        function will take care of the rest.  This includes:

        - Initializing the Adafruit bluetooth interface object
        - Starting a run loop inside this bluetooth interface for executing the
          Curio event loop
        - Starting up the user async co-routines inside the Curio event loop
    """

    if USE_BLEAK:
        from .bleak_interface import Bleak
        ble = Bleak()
        # Run curio in a thread
        curry_curio_event_run = partial(_curio_event_run,
                                        ble=ble,
                                        system=user_system_setup_func)
        t = threading.Thread(target=curry_curio_event_run)
        t.start()
        print('started thread for curio')
        ble.run()
    else:
        ble = Adafruit_BluefruitLE.get_provider()
        ble.initialize()
        # run_mainloop_with call does not accept function args.  So let's curry
        # the my_run with the ble arg as curry_my_run
        curry_curio_event_run = partial(_curio_event_run,
                                        ble=ble,
                                        system=user_system_setup_func)

        ble.run_mainloop_with(curry_curio_event_run)
Beispiel #3
0
    def __init__(self):
        log( "Cannybots BLE Agent v{} starting...".format(VERSION))

        self.keepRunning = True
        self.wsService = SimpleEcho
        self.ws = SimpleWebSocketServer('', 3141, self.wsService)
        self.ble = Adafruit_BluefruitLE.get_provider()
        self.ble.initialize()
Beispiel #4
0
    def bluetoothConnect(self):
        ble = Adafruit_BluefruitLE.get_provider()

        def mainBluetooth():
            global sendCommand
            global confirmation
            # Clear any cached data
            ble.clear_cached_data()

            # Get first available adapter and make sure it is powered on
            adapter = ble.get_default_adapter()
            adapter.power_on()
            print("Using adapter: {0}".format(adapter.name))

            # Disconnect any currently connected devices
            print("Disconnecting any connected UART devices...")
            UART.disconnect_devices()

            # Scan for UART devices
            print("Searching for UART device...")
            try:
                adapter.start_scan()
                device = UART.find_device()
                if device is None:
                    raise RuntimeError("Failed to find UART device!")
            finally:
                adapter.stop_scan()

            print("Connecting to device...")
            device.connect()

            try:
                print("Discovering services...")
                UART.discover(device)

                # Create instance to interact with
                uart = UART(device)

                sendCommand = sendCommand.encode()
                uart.write(b"%b" % (sendCommand))
                received = uart.read(timeout_sec=10)
                if received is not None:
                    print("Received: {0}".format(received))
                    confirmation = "Received: " + received
                else:
                    print("Received no data!")
                    confirmation = "Received no data!"
            finally:
                device.disconnect()

        # Initialize the BLE system
        ble.initialize()

        # Start the mainloop process
        try:
            ble.run_mainloop_with(mainBluetooth)
        except:
            return
 def __init__(self, queue, data_type):
     self._connection_lock = threading.Lock()
     self._reader_thread = None
     self._queue = queue
     self._recording_lock = threading.Lock()
     self._recording = False
     self._record_file = None
     self._data_type = data_type
     # Get the BLE provider for the current  platform.
     self.ble = Adafruit_BluefruitLE.get_provider()
Beispiel #6
0
    def __init__(self):

        global ws
        global wsService

        self.keepRunning = True
        wsService = BuzzWebSocket
        ws = SimpleWebSocketServer('', 3141, wsService)
        self.ble = Adafruit_BluefruitLE.get_provider()
        self.ble.initialize()
Beispiel #7
0
 def setup_ble(self):
     self.remote = None
     self.ble = Adafruit_BluefruitLE.get_provider()
     # Initialize the BLE system.  MUST be called before other BLE calls!
     self.ble.initialize()
     # Get the first available BLE network adapter and make sure it's powered on.
     self.adapter = self.ble.get_default_adapter()
     self.adapter.power_on()
     log.info('Using adapter: {0}'.format(self.adapter.name))
     self.dexcom = None
     pass
Beispiel #8
0
 def setup_ble (self):
   self.remote = None
   self.ble = Adafruit_BluefruitLE.get_provider()
   # Initialize the BLE system.  MUST be called before other BLE calls!
   self.ble.initialize()
   # Get the first available BLE network adapter and make sure it's powered on.
   self.adapter = self.ble.get_default_adapter()
   self.adapter.power_on()
   log.info('Using adapter: {0}'.format(self.adapter.name))
   self.dexcom = None
   pass
Beispiel #9
0
def app(list_joysticks, list_bluetooth, joy, device):
    if list_joysticks:
        joystick.init()
        print('Joysticks:')
        for i in range(joystick.get_count()):
            j = joystick.Joystick(i)
            print(j.get_id(), j.get_name())

    if list_bluetooth:
        ble = Adafruit_BluefruitLE.get_provider()
        ble.initialize()
        ble.run_mainloop_with(lambda: list_bluetooth_devices(ble))

    if device is not None:
        ble = Adafruit_BluefruitLE.get_provider()
        ble.initialize()
        ble.run_mainloop_with(lambda: get_device(ble, device))
        return
        bluetooth = get_device(ble, device)
        bluetooth.connect()
        atexit.register(bluetooth.disconnect)
        UART.discover(bluetooth)
        uart = UART(bluetooth)

    if joy is not None:
        os.environ['SDL_VIDEODRIVER'] = 'dummy'
        pygame.init()
        joystick.init()
        j = joystick.Joystick(joy)
        j.init()
        print('Axes:', j.get_numaxes())
        while True:
            pygame.event.get()
            for i in range(j.get_numaxes()):
                if bluetooth and uart:
                    uart.write('{}{}\n'.format(i, j.get_axis(i)))

            print('   '.join(
                [str(j.get_axis(i)) for i in range(j.get_numaxes())]),
                  end='\r')
            time.sleep(0.05)
Beispiel #10
0
    def __init__(self):
        #   Want to catch any output while initializing
        text_catcher = io.StringIO()
        sys.stdout = text_catcher

        #   Initialize the BLE provider
        self.ble = Adafruit_BluefruitLE.get_provider()

        #   Initialize the BLE system
        self.ble.initialize()

        #   Restore printing to console
        sys.stdout = sys.__stdout__
Beispiel #11
0
  def setup_ble (self):
    # create console handler and set level to debug for diagnostics

    self.remote = None
    self.ble = Adafruit_BluefruitLE.get_provider()
    # Initialize the BLE system.  MUST be called before other BLE calls!
    self.ble.initialize()
    # Get the first available BLE network adapter and make sure it's powered on.
    self.adapter = self.ble.get_default_adapter()
    self.adapter.power_on()
    print('Using adapter: {0}'.format(self.adapter.name))
    self.dexcom = None
    pass
Beispiel #12
0
    def __init__(self,
                 scantime=None,
                 devname=None,
                 devaddr=None,
                 logfname=DEFAULT_LOGFILE,
                 pipefname=DEFAULT_PIPEFILE,
                 pidfname=DEFAULT_PIDFILE,
                 csvfname=None):
        self.adapter = None
        self.device = None
        self.found_devices = []

        self.uart = None
        self.rx = None
        self.tx = None
        self.rxbuf = []
        self.txbuf = []

        self.csvfname = csvfname
        self.csvparser = None

        self.scantime = scantime
        print("SCNTIME: \t" + repr(self.scantime))
        self.devname = devname
        print("DEVNAME: \t" + repr(self.devname))
        self.devaddr = devaddr
        print("DEVADDR: \t" + repr(self.devaddr))

        self.logfile = None  # file type opbject
        self.logfname = logfname
        print("LOGFILE: \t" + repr(self.logfname))
        self.inputpipe = None  # fdopen type object
        self.inputpipename = pipefname
        print("INPUTFL: \t" + repr(self.inputpipename))
        self.pidfilename = pidfname

        self.pid = os.getpid()
        print("python started on pid  {}".format(self.pid))
        self.writepidfile()
        self.ble = AdaBLE.get_provider()
        print("Initializing Bluetooth...")
        self.ble.initialize()
Beispiel #13
0
    def __init__(self, delegate, arguments=None):

        if arguments is None:
            parser = argparse.ArgumentParser(description='Options.')
            WWBTLEManager.setup_argument_parser(parser)
            arguments = parser.parse_args()

        self._args = arguments

        self.delegate = delegate

        self._load_HAL()

        self.robot = None

        self._sensor_queue = queue.Queue()

        # Initialize the BLE system.  MUST be called before other BLE calls!
        self.ble = Adafruit_BluefruitLE.get_provider()
        self.ble.initialize()
Beispiel #14
0
from Adafruit_I2C import Adafruit_I2C
from Adafruit_CharLCD import Adafruit_CharLCD
import smbus, sys, os, random, getopt, re, atexit
import RPi.GPIO as GPIO, time, os
import Adafruit_DHT
from Adafruit_Thermal import *
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
from Adafruit_PWM_Servo_Driver import PWM
from Adafruit_IO import Client
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import UART

print("starting up")

# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()


#time
t0=time.time()
t0_climate=0
t_climate=30

#Adafruit IO
ADAFRUIT_IO_KEY = '954a29c4a56787437186d8c39c57a61d6c079867'
aio = Client(ADAFRUIT_IO_KEY)
data = aio.receive('Omnibot')

GPIO.setmode(GPIO.BCM)

#Thermal Printer
Beispiel #15
0
 def runTest(self):
     self.runTest_startUART()
     # AdaFruit has this really handy helper function, but we should probably write our own, so that
     # we don't have to propogate the AdaFruit dependency everywhere.
     Adafruit_BluefruitLE.get_provider().run_mainloop_with(
         self.runTest_MainLoop)
Beispiel #16
0
 def launch(self):
     self.ble = Adafruit_BluefruitLE.get_provider()
     self.ble.initialize()
     self.ble.run_mainloop_with(self.mainloop)
Beispiel #17
0
 def setup(self):
     super().setup()
     self.ble = Adafruit_BluefruitLE.get_provider()
     self.ble.initialize()
     self.ble.run_mainloop_with(self.__setup_thread)
Beispiel #18
0
 def get_provider(cls):
     provider = Adafruit_BluefruitLE.get_provider()
     provider.initialize()
     return provider
Beispiel #19
0
def main():
    # Process command line arguments.
    parser = argparse.ArgumentParser(
        description='TXJS: XMODEM over UART over BLE')
    parser.add_argument('file', metavar='FILE', help='script file to upload')

    args = parser.parse_args()

    # Get the BLE provider for the current platform and initialize BLE system.
    ble = BLE.get_provider()
    ble.initialize()

    # To be executed in a background thread while OS main loop processes async
    # BLE events
    def ble_main():
        # Do everything in a try/except to ensure that we can get a proper
        # backtrace in case of an error. (The BLE main loop implementation can
        # conceal it.)
        try:
            # Clear any cached data because all providers have issues with
            # caching data and it going stale.
            ble.clear_cached_data()

            # Get the first available BLE network adapter and make sure it's
            # powered on.
            adapter = ble.get_default_adapter()
            adapter.power_on()
            print('Using adapter {0}'.format(adapter.name))

            # Disconnect any currently connected UART devices for cleaning up
            # and starting from a fresh state.
            print('Disconnecting any connected UART devices...')
            UART.disconnect_devices()

            # Scan for devices.
            print('Searching for a device with UART service...')
            try:
                adapter.start_scan()
                # Search for the first UART device found (will time out after
                # 60 seconds).
                device = UART.find_device()
                if device is None:
                    raise RuntimeError('Failed to find device!')
            finally:
                # Make sure scanning is stopped before exiting.
                adapter.stop_scan()

            print('Connecting to device {0} [{1}]...'.format(
                device.name, device.id))
            # Will time out after 60 seconds.
            device.connect()

            # Once connected do everything else in a try/finally to make sure
            # the device is disconnected when done.
            try:
                # Wait for service discoveries to complete. Each will time out
                # after 60 seconds.
                print('Discovering services...')
                UART.discover(device)
                CurrentTimeService.discover(device)

                # Once service discovery is complete, create instances of the
                # services and start interacting with them.
                uart = UART(device)
                cts = CurrentTimeService(device)

                # Setting current time should come first because it seems that
                # after the UART transfer the disconnect happens too fast and
                # the write to current time characteristic cannot finish.
                print('Resetting RTC...')

                print('RTC was {0:%a, %d %b %Y %H:%M:%S GMT}'.format(
                    cts.current_time))
                now = datetime.datetime.utcnow()
                cts.current_time = now
                print('RTC reset to {0:%a, %d %b %Y %H:%M:%S GMT}'.format(now))

                # Now transfer the file with XMODEM over UART.
                print('Transfering file {0} with XMODEM...'.format(args.file))

                # Write file content to the TX characteristic in 20 bytes
                # chunks. Note that this implementation ignores the timeout.
                def send_bytes(data, timeout=1):
                    size = len(data)

                    while data:
                        chunk = data[:20]
                        data = data[20:]
                        uart.write(chunk)

                        print('.', end='')
                        sys.stdout.flush()

                    print('o', end='')
                    sys.stdout.flush()

                    return size

                # Note that this ignores the size.
                def recv_bytes(size, timeout=1):
                    return uart.read(timeout_sec=timeout) or None

                # logging.basicConfig(format='%(message)s')
                # logging.getLogger('xmodem.XMODEM').setLevel('DEBUG')

                modem = XMODEM(recv_bytes, send_bytes)
                with open(args.file, 'rb') as f:
                    status = modem.send(f)
                    print()
                    print('Transfer {0}'.format(
                        'successful' if status else 'failed'))

            finally:
                # Make sure device is disconnected on exit.
                device.disconnect()

        except:
            traceback.print_exc()
            raise

    # Start the OS main loop to process BLE events, and run ble_main in a
    # background thread.
    ble.run_mainloop_with(ble_main)
    % python bluefruit_osc_bridge.py

"""

import heapq
import signal
import time

import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import UART

import OSC

# Get the BLE PROVIDER for the current platform.
PROVIDER = Adafruit_BluefruitLE.get_provider()
BASE_PORT = 8000  # First device will be port 8000, next 8001, etc.

interrupted = False  # pylint: disable=invalid-name


class DeviceTracker(object):
    """ Keeps track of all known bluetooth devices """

    devices = set({})
    connections = []
    available_indices = []
    max_index = 0
    adapter = None

    def start(self):
Beispiel #21
0
import asyncio
import json
import logging
import Adafruit_BluefruitLE

from .timer import TimerService
from hbmqtt.client import MQTTClient
from hbmqtt.mqtt.constants import QOS_1

ble = Adafruit_BluefruitLE.get_provider(
)  # Get the BLE provider for the current platform.


class TimerMqttService:
    """MQTT Service for Bluetooth LE Aqua Systems water timer

    """

    COMMAND_TOPIC = '$SYS/broker/aquatimer/command'
    INFO_TOPIC = '$SYS/broker/aquatimer/info'
    BATTERY_TOPIC = '$SYS/broker/aquatimer/battery'

    # Dictionary for any attribute specific topics
    ATTR_TOPICS = {'battery': BATTERY_TOPIC}

    device_connect_timeout = 10  # seconds
    battery_notify_interval = 1  # minutes

    def __init__(self, mqtt_url, device_name):

        self.logger = logging.getLogger(__name__)
Beispiel #22
0
 def ble_process(self):
     self.ble = Adafruit_BluefruitLE.get_provider()
     self.ble.initialize()
     self.ble.run_mainloop_with(self.ble_main)
                def run(self):
                    while not self.stoprequest.isSet():
                        self.ble = Adafruit_BluefruitLE.get_provider()
                        self.ble.initialize()

                        # Clear any cached data because both bluez and CoreBluetooth have issues with
                        # caching data and it going stale.
                        self.ble.clear_cached_data()

                        # Get the first available BLE network adapter and make sure it's powered on.
                        adapter = self.ble.get_default_adapter()
                        adapter.power_on()
                        print('Using adapter: {0}'.format(adapter.name))
                        # Disconnect any currently connected UART devices.  Good for cleaning up and
                        # starting from a fresh state.
                        print('Disconnecting any connected UART devices...')
                        UART.disconnect_devices()

                        # Scan for UART devices.
                        print('Searching for UART device...')
                        try:
                            adapter.start_scan()
                            # Search for the first UART device found (will time out after 60 seconds
                            # but you can specify an optional timeout_sec parameter to change it).
                            self.device = UART.find_device()
                            if self.device is None:
                                raise RuntimeError(
                                    'Failed to find UART device!')
                        finally:
                            # Make sure scanning is stopped before exiting.
                            adapter.stop_scan()

                        print('Connecting to ', self.device.name)
                        self.device.connect(
                        )  # Will time out after 60 seconds, specify timeout_sec parameter
                        # to change the timeout.
                        # Once connected do everything else in a try/finally to make sure the device
                        # is disconnected when done.
                        try:
                            # Wait for service discovery to complete for the UART service.  Will
                            # time out after 60 seconds (specify timeout_sec parameter to override).
                            print('Discovering services...')
                            UART.discover(self.device)

                            # Once service discovery is complete create an instance of the service
                            # and start interacting with it.
                            uart = UART(self.device)

                            # return uart, device
                            # dis = DeviceInformation(device)
                            # Write a string to the TX characteristic.
                            # uart.write('Hello world!\r\n')
                            # print("Sent 'Hello world!' to the device.")
                            # print (dir(device))
                            def handle_line(data):

                                b = data.decode()  # change it to a string
                                if 'magnitudes' in b:
                                    print('packet start')
                                    self.get_line_lock = 1

                                # with self._recording_lock:
                                #     if self._recording:
                                #         logger.info("this is within handle line serialhandler._recording")
                                #         self._record_file.write(line + "\n")

                                if self.get_line_lock == 1:
                                    self.ble_line = self.ble_line + b

                                    # parse line based on different input data types.
                                    if self._data_type == 'a':
                                        res = parse_timeseries(self.ble_line)
                                    elif self._data_type == 'b':
                                        res = parse_bis_line(self.ble_line)
                                    else:
                                        res = parse_ble_line(self.ble_line)

                                    if res is not None:
                                        self.ble_line = ''
                                        self._queue.put(res)

                            while self.device.is_connected:
                                # Now wait up to one minute to receive data from the device.
                                newdata = uart.read(timeout_sec=1)
                                if newdata is not None:
                                    handle_line(newdata)
                                else:
                                    break

                        finally:
                            logger.info('device disconnecting')
                            try:
                                self.device.disconnect()
                                # Make sure device is disconnected on exit.
                                UART.disconnect_devices()
                            except:
                                print('p disconnecting')
Beispiel #24
0
import logging
import time
import uuid

import Adafruit_BluefruitLE

from scipy.io.wavfile import write
import numpy as np

# BASED ON EXAMPLE FROM Adafruit_BluefruitLE https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/master/examples/low_level.py

SERVICE_ID = uuid.UUID('67aa4562-ba79-46a3-a86b-91675642a359')
PDM_CHAR_ID = uuid.UUID('917649A1-D98E-11E5-9EEC-0002A5D5C511')
SHORT_SAMPLE_CAPTURED_ID = uuid.UUID('917649A1-D98E-11E5-9EEC-0002A5D5C51B')

ble = Adafruit_BluefruitLE.get_provider()

PDM_COLLECTED = bytearray()

samples = 0


def writeWav(data, ssa):
    print(data)
    write("samples/example_{}.wav".format(ssa), 16000, data)


def main():
    ble.clear_cached_data()

    adapter = ble.get_default_adapter()
Beispiel #25
0
def find():
    Adafruit_BluefruitLE.get_provider()
    print(QBluetoothDeviceDiscoveryAgent().discoveredDevices())