Ejemplo n.º 1
0
    def post_init(self):
        self.devices = {}

        hid = HIDService()

        advertisement = ProvideServicesAdvertisement(hid)
        advertisement.appearance = BLE_APPEARANCE_HID_KEYBOARD
        scan_response = Advertisement()
        scan_response.complete_name = 'KMK Keyboard'

        ble = BLERadio()
        if not ble.connected:
            ble.start_advertising(advertisement, scan_response)
            while not ble.connected:
                pass

        for device in hid.devices:
            us = device.usage
            up = device.usage_page

            if up == HIDUsagePage.CONSUMER and us == HIDUsage.CONSUMER:
                self.devices[HIDReportTypes.CONSUMER] = device
                continue

            if up == HIDUsagePage.KEYBOARD and us == HIDUsage.KEYBOARD:
                self.devices[HIDReportTypes.KEYBOARD] = device
                continue

            if up == HIDUsagePage.MOUSE and us == HIDUsage.MOUSE:
                self.devices[HIDReportTypes.MOUSE] = device
                continue

            if up == HIDUsagePage.SYSCONTROL and us == HIDUsage.SYSCONTROL:
                self.devices[HIDReportTypes.SYSCONTROL] = device
                continue
Ejemplo n.º 2
0
 def __init__(self, init_ui=True):
     self.ble = BLERadio()
     ui.display_qr(self.addr_suffix)
     self.nameservice = NameService()
     self.advertisement = ProvideServicesAdvertisement(self.nameservice)
     self.scan_response = Advertisement()
     self.scan_response.complete_name = "BADGE-{}".format(self.addr_suffix)
     self.ble.start_advertising(self.advertisement, self.scan_response)
Ejemplo n.º 3
0
 def __init__(self, use_debug=False):
     self.use_debug = use_debug
     self.subscription_ids = {}
     self.subscription_messages_on_reconnect = []
     self.ble = BLERadio()
     self.uart_server = UARTService()
     self.advertisement = ProvideServicesAdvertisement(self.uart_server)
     self.chunk_size = 20  # adafruit_ble can only write in 20 byte chunks
     self.recv_msg_cache = ""
Ejemplo n.º 4
0
 def __init__(self, onConnectionStateChanged, onAdvertising=None, onWrite=None):
     self._ble = BLERadio()
     self._uart_server = UARTService()
     self._onAdvertising = onAdvertising
     self._onWrite = onWrite
     self._advertisement = ProvideServicesAdvertisement(self._uart_server)
     self._isAdvertising = False
     self._onAdvertising = onAdvertising
     self._onWrite = onWrite
     self.__oldConnectionState = False
     self._onConnectionStateChanged = onConnectionStateChanged
     self._enabled = False
Ejemplo n.º 5
0
    def __init__(self):
        # Set up watchdog timer
        self.watchdog = microcontroller.watchdog
        self.watchdog.deinit()
        self.watchdog.timeout = WATCHDOG_TIMEOUT
        self.watchdog.mode = WATCHDOG_MODE

        # Set up heartbeat output (i.e red LED)
        self._heartbeat = digitalio.DigitalInOut(HEARTBEAT_PIN)
        self._heartbeat.direction = digitalio.Direction.OUTPUT
        self._heartbeat_duration = HEARTBEAT_DURATION

        # Set up I2C bus
        i2c = busio.I2C(board.SCL, board.SDA)
        # Set up SPI bus
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        # Set up real time clock as source for time.time() or time.localtime() calls.
        print("Initialising real time clock.\n\n\n\n")
        clock = PCF8523(i2c)
        rtc.set_time_source(clock)

        print("Initialising display.\n\n\n\n")
        self.display = Display(self, DISPLAY_TIMEOUT, i2c, spi)

        print("Initialising lights.\n\n\n\n")
        self.lights = Lights(LIGHTS_ON_TIME, LIGHTS_OFF_TIME, LIGHTS_ENABLE_PIN, LIGHTS_DISABLE_PIN)

        print("Initialising feeder.\n\n\n\n")
        self.feeder = Feeder(FEEDING_TIMES, PORTIONS_PER_MEAL, FEEDER_MOTOR, FEEDER_STEPS_PER_ROTATION,
                             FEEDER_STEP_DELAY, FEEDER_STEP_STYLE, i2c)

        print("Initialising temperature sensors.\n\n\n\n")
        ow_bus = OneWireBus(OW_PIN)
        self.water_sensor = TemperatureSensor(ow_bus, WATER_SN, WATER_OFFSET)
        self.air_sensor = TemperatureSensor(ow_bus, AIR_SN, AIR_OFFSET)

        # Set up SD card
        print("Setting up logging.\n\n\n\n")
        cs = digitalio.DigitalInOut(SD_CS)
        sdcard = SDCard(spi, cs)
        vfs = storage.VfsFat(sdcard)
        storage.mount(vfs, "/sd")
        self._log_data = LOG_DATA
        self._log_interval = time_tuple_to_secs(LOG_INTERVAL)
        self._last_log = None

        print("Initialising Bluetooth.\n\n\n\n")
        self._ble = BLERadio()
        self._ble._adapter.name = BLE_NAME
        self._ble_uart = UARTService()
        self._ble_ad = ProvideServicesAdvertisement(self._ble_uart)
Ejemplo n.º 6
0
def main():
    hid = HIDService()
    advertisement = ProvideServicesAdvertisement(hid)
    advertisement.appearance = 961
    ble = adafruit_ble.BLERadio()
    if ble.connected:
        for c in ble.connections:
            c.disconnect()
    ble.start_advertising(advertisement)
    advertising = True
    ble_keyboard = Keyboard(hid.devices)

    matrix = Matrix()
    usb_keyboard = Keyboard(usb_hid.devices)

    while True:
        pressed_keys, released_keys, new_keys = matrix.scan()
        if released_keys:
            released_keycodes = list(map(lambda i: KEYMAP[i], released_keys))
            print('released keys {}'.format(released_keycodes))

            usb_keyboard.release(*released_keycodes)
            if ble.connected:
                advertising = False
                ble_keyboard.release(*released_keycodes)
        if new_keys:
            new_keycodes = list(map(lambda i: KEYMAP[i], new_keys))
            print('new keys {}'.format(new_keycodes))
            usb_keyboard.press(*new_keycodes)
            if ble.connected:
                advertising = False
                ble_keyboard.press(*new_keycodes)

        if not ble.connected and not advertising:
            ble.start_advertising(advertisement)
            advertising = True

        time.sleep(0.001)
Ejemplo n.º 7
0
    def post_init(self, ble_name='KMK Keyboard', **kwargs):
        self.devices = {}

        hid = HIDService()

        advertisement = ProvideServicesAdvertisement(hid)
        advertisement.appearance = BLE_APPEARANCE_HID_KEYBOARD

        ble = BLERadio()
        ble.name = ble_name
        # ble.tx_power = 2

        if not ble.connected:
            ble.start_advertising(advertisement)
            while not ble.connected:
                pass

        for device in hid.devices:
            us = device.usage
            up = device.usage_page

            if up == HIDUsagePage.CONSUMER and us == HIDUsage.CONSUMER:
                self.devices[HIDReportTypes.CONSUMER] = device
                continue

            if up == HIDUsagePage.KEYBOARD and us == HIDUsage.KEYBOARD:
                self.devices[HIDReportTypes.KEYBOARD] = device
                continue

            if up == HIDUsagePage.MOUSE and us == HIDUsage.MOUSE:
                self.devices[HIDReportTypes.MOUSE] = device
                continue

            if up == HIDUsagePage.SYSCONTROL and us == HIDUsage.SYSCONTROL:
                self.devices[HIDReportTypes.SYSCONTROL] = device
                continue
Ejemplo n.º 8
0
def run(cycles_per_second=30, device_name=None):
    ble = BLERadio()
    if device_name:
        ble.name = device_name
    uart = UARTService()
    advertisement = ProvideServicesAdvertisement(uart)
    expected_seconds_per_tick = 1 / cycles_per_second
    while True:
        print("waiting for bluetooth connection")
        ble.start_advertising(advertisement)
        while not ble.connected:
            _tick(expected_seconds_per_tick=expected_seconds_per_tick)
        print("connected to bluetooth")
        smartphone._set_uart(uart=uart)
        while ble.connected:
            _tick(expected_seconds_per_tick=expected_seconds_per_tick)
        print("lost bluetooth connection")
        smartphone._unset_uart()
Ejemplo n.º 9
0
    def __init__(self, pin=board.D13, sample_num=20, use_ble=False):
        # Might not want to use BLE, perhaps for testing purposes
        self.use_ble = use_ble
        self.sample_num = sample_num
        try:
            self.pulses = pulseio.PulseIn(pin, self.sample_num)
        except ValueError as e:
            raise ValueError(e)
        self.pulses.pause()

        # The samples list holds the readings that will be used in calculating the distance.  Pulse readings that
        # are determined to be way off (say 655355....) will not be included so len(samples) is <= sample_num.
        self.samples = []

        if self.use_ble:
            # Set up BLE based on Adafruit's CircuitPython libraries.
            self.ble = BLERadio()
            uart_service = UARTService()
            advertisement = ProvideServicesAdvertisement(uart_service)
            #  Advertise when not connected.
            self.ble.start_advertising(advertisement)
Ejemplo n.º 10
0
def connect():
    """Connect two boards using the first Nordic UARTService the client
       finds over Bluetooth Low Energy.
       No timeouts, will wait forever."""
    new_conn = None
    new_uart = None
    if master_device:
        # Master code
        while new_uart is None:
            d_print("Disconnected, scanning")
            for advertisement in ble.start_scan(ProvideServicesAdvertisement,
                                                timeout=BLESCAN_TIMEOUT):
                d_print(2, advertisement.address, advertisement.rssi, "dBm")
                if UARTService not in advertisement.services:
                    continue
                d_print(1, "Connecting to", advertisement.address)
                ble.connect(advertisement)
                break
            for conns in ble.connections:
                if UARTService in conns:
                    d_print("Found UARTService")
                    new_conn = conns
                    new_uart = conns[UARTService]
                    break
            ble.stop_scan()

    else:
        # Slave code
        new_uart = UARTService()
        advertisement = ProvideServicesAdvertisement(new_uart)
        d_print("Advertising")
        ble.start_advertising(advertisement)
        # Is there a conn object somewhere here??
        while not ble.connected:
            pass

    return (new_conn, new_uart)
Ejemplo n.º 11
0
 def __init__(self, *, hand):
     super().__init__(hand)
     self.usb_connected = False
     self.skp_service = SubkeypadService()
     self.advert = ProvideServicesAdvertisement(self.skp_service)
     self.connection = None
Ejemplo n.º 12
0
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

import adafruit_ble
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from adafruit_ble.services.standard.device_info import DeviceInfoService


ble = adafruit_ble.BLERadio()
ble.name = "Bluefruit-Volume-Control"
# Using default HID Descriptor.
hid = HIDService()
device_info = DeviceInfoService(software_revision=adafruit_ble.__version__,
                                manufacturer="Adafruit Industries")
advertisement = ProvideServicesAdvertisement(hid)
cc = ConsumerControl(hid.devices)

FILL_COLOR = (0, 32, 32)
UNMUTED_COLOR = (0, 128, 128)
MUTED_COLOR = (128, 0, 0)
DISCONNECTED_COLOR = (40, 40, 0)

# NeoPixel LED ring
# Ring code will auto-adjust if not 16 so change to any value!
ring = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.05, auto_write = False)
ring.fill(DISCONNECTED_COLOR)
ring.show()
dot_location = 0  # what dot is currently lit

# CPB button for Play/Pause
Ejemplo n.º 13
0
    def start_advertising(self):
        advertisement = ProvideServicesAdvertisement(self.hid)
        advertisement.appearance = BLE_APPEARANCE_HID_KEYBOARD

        self.ble.start_advertising(advertisement)
Ejemplo n.º 14
0
        buffer_size=64,
    )

    def __init__(self, service=None):
        # just steal the uuid code from MIDISerivce

        super().__init__(service=service)
        self.connectable = True
        self._rx = self._server_rx

    def read(self, nbytes=None):
        return self._rx.read(nbytes)


service = CustomUART()
ad = ProvideServicesAdvertisement(service)
drawer = Drawer(output=board.DISPLAY)

while True:
    if ble.connected:
        hexcode = service.read(6).decode('utf-8')
        print('connected!' + hexcode)

        drawer.draw(hexcode)

    else:
        print('not connected...')
        if not ble.advertising:
            ble.start_advertising(ad)
    time.sleep(1)
Ejemplo n.º 15
0
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from mylight import MyLightClient
# The color pickers will cycle through this list with buttons A and B.
color_options = [
    0x110000, 0x111100, 0x001100, 0x001111, 0x000011, 0x110011, 0x111111,
    0x221111, 0x112211, 0x111122
]
i = 0
current_value = 0
ble = BLERadio()
print("ble loaded")
light = MyLightClient()
print("mylight client init")

advertisement = ProvideServicesAdvertisement(light)
ble._adapter.name = "TestingLight"


def waitforconnect():
    print("Advertising.")
    central = False
    ble.start_advertising(advertisement)

    print("Waiting.")
    while not ble.connected:
        pass

    # We're now connected, one way or the other
    print("Stopping advertising.")
    ble.stop_advertising()
Ejemplo n.º 16
0

def remap(x, in_min, in_max, out_min, out_max, no_float=True):
    res = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
    if res < out_min:
        res = out_min
    if res > out_max:
        res = out_max
    if no_float:
        res = round(res)
    return res


MIDI_CHANNEL = 1
MIDI_SERVICE = adafruit_ble_midi.MIDIService()
BLE_AD = ProvideServicesAdvertisement(MIDI_SERVICE)
MIDI = adafruit_midi.MIDI(midi_out=MIDI_SERVICE, out_channel=MIDI_CHANNEL - 1)

BLE = adafruit_ble.BLERadio()
if BLE.connected:
    print("Remove active BLE connections")
    for c in BLE.connections:
        c.disconnect()
BLE.name = "BIAS FX CLUE BLE MIDI"
print("Advertising BLE")
BLE.start_advertising(BLE_AD)

clue_display = DisplayManager(clue)
debouncer = Debouncer(BUTTONS)
START_RANGE = 0
Ejemplo n.º 17
0
            percentage = 100
        elif percentage < 0 :
            percentage = 0
        return percentage
    else:
        return 0
        
bleHID = bleHIDService()
batteryService = BatteryService()
 
device_info = DeviceInfoService(
                                software_revision=adafruit_ble.__version__,
                                manufacturer="Adafruit Industries",
                                hardware_revision="0.0.1",
                                )
advertisement = ProvideServicesAdvertisement(device_info, bleHID, batteryService)
advertisement.appearance = 961
scan_response = Advertisement()
scan_response.complete_name = "CP Keyboard"
 
ble = adafruit_ble.BLERadio()
ble.name = "CircuitPython Keyboard"
#ble._adapter.enabled = False

np = neopixel.NeoPixel(board.NEOPIXEL,1)

def disconnectAll():
    if ble.connected:
        for connection in ble.connections:
            connection.disconnect()
Ejemplo n.º 18
0
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

import adafruit_ble
from adafruit_ble.advertising import Advertisement
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from adafruit_ble.services.standard.device_info import DeviceInfoService


# Use default HID descriptor
hid = HIDService()
device_info = DeviceInfoService(
    software_revision=adafruit_ble.__version__, manufacturer="Adafruit Industries"
)
advertisement = ProvideServicesAdvertisement(hid)
advertisement.appearance = 961
scan_response = Advertisement()

ble = adafruit_ble.BLERadio()
if ble.connected:
    for c in ble.connections:
        c.disconnect()

print("advertising")
ble.start_advertising(advertisement, scan_response)

k = Keyboard(hid.devices)
kl = KeyboardLayoutUS(k)
while True:
    while not ble.connected:
Ejemplo n.º 19
0
  #  Cellphone

# Import required libraries for light sensor, thermistor, BLE radio, and neopixels
import time
import board
import analogio
import adafruit_thermistor
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
import neopixel

# Setup the BLE radio
ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)
# Give your CPB a unique name between the quotes below
advertisement.complete_name = "AK_CPB"

# Setup the thermistor and light sensor
tmp = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950)
light = analogio.AnalogIn(board.LIGHT)

# Setup neopixels
BLUE = (0, 0, 255)
NAVY = (0,0,128)
BLACK = (0, 0, 0)
leadColor = BLUE
chaseColor = NAVY
pauseTime = 0.1
pxl = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness =0.1, auto_write = True)
Ejemplo n.º 20
0
 def advertise(self):
     self.ble.start_advertising(ProvideServicesAdvertisement(self.ble_service))
Ejemplo n.º 21
0
    def run(self):
        hid = HIDService()
        advertisement = ProvideServicesAdvertisement(hid)
        advertisement.appearance = 961
        ble = adafruit_ble.BLERadio()
        ble.name = 'Python Keyboard'
        if ble.connected:
            for c in ble.connections:
                c.disconnect()
        ble.start_advertising(advertisement)
        ble.advertising = True
        ble_keyboard = _Keyboard(hid.devices)
        usb_keyboard = _Keyboard(usb_hid.devices)

        def send(*code):
            usb_keyboard.press(*code)
            usb_keyboard.release(*code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.press(*code)
                ble_keyboard.release(*code)

        def press(*code):
            usb_keyboard.press(*code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.press(*code)

        def release(*code):
            usb_keyboard.release(*code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.release(*code)

        self.setup()
        matrix = Matrix()
        keys = [0] * matrix.size
        while True:
            n_events = matrix.scan()
            if n_events == 0:
                # print((time.monotonic_ns() - matrix.scan_time) // 1000000)
                continue

            # detecting pair keys
            if n_events == 1 and matrix[0] in self.pair_keys:
                n_events = matrix.wait(matrix.scan_time + 10000000)

            if n_events >= 2:
                pair = {matrix[0], matrix[1]}
                if pair in self.pairs:
                    pair_index = self.pairs.index(pair)
                    key1 = matrix.get()
                    key2 = matrix.get()

                    dt = matrix.pressed_t[key2] - matrix.pressed_t[key1]
                    print('pair keys {} {}, dt = {}'.format(
                        pair_index, pair, dt // 1000000))
                    # todo
                    for c in b'pair keys':
                        send(ASCII_TO_KEYCODE[c])

            while len(matrix):
                event = matrix.get()
                key = event & 0x7F
                if event & 0x80 == 0:
                    action_code = self.action_code(key)
                    keys[key] = action_code
                    print('{} \\ action_code = {}'.format(
                        key, hex(action_code)))
                    if action_code < 0xFF:
                        press(action_code)
                    else:
                        kind = action_code >> 12
                        kind = action_code >> 12
                        if kind == ACT_MODS:
                            mods = (action_code >> 8) & 0xF
                            keycodes = mods_to_keycodes(mods)
                            keycodes.append(action_code & 0xFF)
                            press(*keycodes)
                        elif kind == ACT_MODS_TAP:
                            if matrix.length == 0:
                                matrix.wait(matrix.pressed_t[key] + 500000000)
                            if matrix.length > 0 and matrix[0] == (key | 0x80):
                                print('press & release quickly')
                                keycode = action_code & 0xFF
                                keys[key] = keycode
                                press(keycode)
                                matrix.get()
                                release(keycode)
                            else:
                                mods = (action_code >> 8) & 0xF
                                keycodes = mods_to_keycodes(mods)
                                print(keycodes)
                                press(*keycodes)
                        elif kind == ACT_LAYER_TAP:
                            layer = ((action_code >> 8) & 0xF)
                            mask = 1 << layer
                            keycode = action_code & 0xFF
                            if keycode != OP_TAP_TOGGLE:
                                if matrix.length == 0:
                                    matrix.wait(matrix.pressed_t[key] +
                                                500000000)
                                if matrix.length > 0 and matrix[0] == (key
                                                                       | 0x80):
                                    print('press & release quickly')
                                    keys[key] = keycode
                                    press(keycode)
                                    matrix.get()
                                    release(keycode)
                                else:
                                    self.layer_mask |= mask
                            else:
                                print('toggle {}'.format(self.layer_mask))
                                self.layer_mask = (self.layer_mask & ~mask) | (
                                    mask & ~self.layer_mask)

                            print('layers {}'.format(self.layer_mask))
                        elif action_code == BOOTLOADER:
                            reset_into_bootloader()
                else:
                    action_code = keys[key]
                    dt = (matrix.scan_time - matrix.pressed_t[key]) // 1000000
                    print('{} / action_code = {}, dt = {}'.format(
                        key, action_code, dt))
                    if action_code < 0xFF:
                        release(action_code)
                    else:
                        kind = action_code >> 12
                        if kind == ACT_MODS:
                            mods = (action_code >> 8) & 0xF
                            keycodes = mods_to_keycodes(mods)
                            keycodes.append(action_code & 0xFF)
                            release(*keycodes)
                        elif kind == ACT_MODS_TAP:
                            mods = (action_code >> 8) & 0xF
                            keycodes = mods_to_keycodes(mods)
                            release(*keycodes)
                        elif kind == ACT_LAYER_TAP:
                            layer = ((action_code >> 8) & 0xF)
                            keycode = action_code & 0xFF
                            if keycode != OP_TAP_TOGGLE:
                                self.layer_mask &= ~(1 << layer)
                                print('layers {}'.format(self.layer_mask))
                            # if dt < 500 and keycode:
                            # send(keycode)

            if not ble.connected and not ble.advertising:
                ble.start_advertising(advertisement)
                ble.advertising = True

            print((time.monotonic_ns() - matrix.scan_time) // 1000000)
Ejemplo n.º 22
0
# NEOPIXEL_PIN = board.NEOPIXEL

# Declare a NeoPixel object on NEOPIXEL_PIN with NUM_LEDS pixels,
# no auto-write.
# Set brightness to max, we'll control it later in the code
pixels = neopixel.NeoPixel(
    NEOPIXEL_PIN,
    NUM_LEDS,
    brightness=0.5,
    auto_write=False,
    #pixel_order=(1,0,2,3) #uncomment if using RGBW NeoPixels
)

ble = BLERadio()
uart_service = UARTService()
advertisement = ProvideServicesAdvertisement(uart_service)
advertisement.complete_name = "DingDong"


class RainbowFade(Animation):
    ''' fades the entire strip through the whole spectrum '''
    _color_index = 150  # choose start color (0-255)

    def __init__(self, pixel_object, speed, name):  # define animation
        super().__init__(pixel_object, speed=speed, color=WHITE, name=name)

    def draw(self):  # draw the animation
        ''' fades the entire strip through the whole spectrum '''
        self.color = colorwheel(self._color_index + 1)
        self._color_index = (self._color_index + 1) % 256
        self.fill(self.color)
Ejemplo n.º 23
0
import time
import board
import digitalio
import adafruit_ble
from adafruit_ble.advertising import Advertisement
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode

hid = HIDService()
advertisement = ProvideServicesAdvertisement(hid)
advertisement.complete_name = 'CIRCUITPY KEYBOARD'
advertisement.appearance = 961
ble = adafruit_ble.BLERadio()
if ble.connected:
    for c in ble.connections:
        c.disconnect()
ble.start_advertising(advertisement)
advertising = True
ble_keyboard = Keyboard(hid.devices)

button = digitalio.DigitalInOut(board.USR_BTN)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP

last_value = button.value

while True:
    if last_value != button.value:
        last_value = button.value
Ejemplo n.º 24
0
from adafruit_bluefruit_connect.packet import Packet
# Only the packet classes that are imported will be known to Packet.
from adafruit_bluefruit_connect.button_packet import ButtonPacket
from adafruit_bluefruit_connect.color_packet import ColorPacket

import adafruit_fancyled.adafruit_fancyled as fancy
import adafruit_fancyled.fastled_helpers as helper
from audiopwmio import PWMAudioOut as AudioOut
from audiocore import WaveFile
import board
import time

ble = BLERadio()
uart_service = UARTService()
ble.name = "BabyYoda"
advertisement = ProvideServicesAdvertisement(uart_service)
advertisement.complete_name = "BabyYoda"

RainbowStripeColors = [
    0xFF0000, 0x000000, 0xAB5500, 0x000000, 0xABAB00, 0x000000, 0x00FF00,
    0x000000, 0x00AB55, 0x000000, 0x0000FF, 0x000000, 0x5500AB, 0x000000,
    0xAB0055, 0x000000
]

color = (0, 0, 255)

RED = (255, 0, 0)
ORANGE = (255, 50, 0)
YELLOW = (255, 165, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
Ejemplo n.º 25
0
    def run(self):
        hid = HIDService()
        advertisement = ProvideServicesAdvertisement(hid)
        advertisement.appearance = 961
        ble = adafruit_ble.BLERadio()
        if ble.connected:
            for c in ble.connections:
                c.disconnect()
        ble.start_advertising(advertisement)
        ble.advertising = True
        ble_keyboard = _Keyboard(hid.devices)
        usb_keyboard = _Keyboard(usb_hid.devices)

        def send(code):
            usb_keyboard.press(code)
            usb_keyboard.release(code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.press(code)
                ble_keyboard.release(code)

        def press(code):
            usb_keyboard.press(code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.press(code)

        def release(code):
            usb_keyboard.release(code)
            if ble.connected:
                ble.advertising = False
                ble_keyboard.release(code)

        self.setup()
        while True:
            n_events = self.scan()
            if n_events == 0:
                continue

            # detecting pair keys
            if n_events == 1 and self.pressed_count == 1:
                for mask in self.pair_keys_mask:
                    if self.pressed_mask & mask == self.pressed_mask:
                        n_events = self.wait(2, self.scan_time + 25000000)
                        break

            if n_events >= 2:
                mask = 1 << self.queue.preview(0) | 1 << self.queue.preview(1)
                if mask in self.pair_keys_mask:
                    pair_keys_index = self.pair_keys_mask.index(mask)
                    action_code = self.pair_keys_code[pair_keys_index]
                    key1 = self.queue.get()
                    key2 = self.queue.get()
                    dt = self.pressed_time[key2] - self.pressed_time[key1]
                    print('pair keys {} ({}, {}), dt = {}'.format(
                        pair_keys_index, key1, key2, dt // 1000000))

                    # only one action
                    self.keys[key1] = action_code
                    self.keys[key2] = 0

                    if action_code < 2:
                        pass
                    elif action_code < 0xFF:
                        press(action_code)
                    else:
                        kind = action_code >> 12
                        layer = ((action_code >> 8) & 0xF)
                        if kind < (ACT_MODS_TAP + 1):
                            # todo
                            mods = (action_code >> 8) & 0x1F
                        elif kind == ACT_LAYER_TAP:
                            self.layers |= 1 << layer
                            print('layers {}'.format(self.layers))

            while len(self.queue):
                event = self.queue.get()
                key = event & 0x7F
                if event & 0x80 == 0:
                    action_code = self.action_code(key)
                    self.keys[key] = action_code
                    print('{} / action_code = {}'.format(key, action_code))
                    if action_code < 2:
                        pass
                    elif action_code < 0xFF:
                        press(action_code)
                    else:
                        kind = action_code >> 12
                        layer = ((action_code >> 8) & 0xF)
                        if kind == ACT_LAYER_TAP:
                            self.layers |= 1 << layer
                            print('layers {}'.format(self.layers))
                        elif action_code == BOOTLOADER:
                            reset_into_bootloader()
                else:
                    action_code = self.keys[key]
                    dt = (self.scan_time - self.pressed_time[key]) // 1000000
                    print('{} \\ action_code = {}, dt = {}'.format(
                        key, action_code, dt))
                    if action_code < 2:
                        pass
                    elif action_code < 0xFF:
                        release(action_code)
                    else:
                        kind = action_code >> 12
                        layer = ((action_code >> 8) & 0xF)
                        if kind == ACT_LAYER_TAP:
                            self.layers &= ~(1 << layer)
                            print('layers {}'.format(self.layers))
                            keycode = action_code & 0xFF
                            if dt < 500 and keycode:
                                send(keycode)

            if not ble.connected and not ble.advertising:
                ble.start_advertising(advertisement)
                ble.advertising = True

            print((time.monotonic_ns() - self.scan_time) // 1000000)
from jisforjt_cutebot_clue import cutebot, clue


# Used to create random neopixel colors
import random

# Only the packet classes that are imported will be known to Packet.
from adafruit_bluefruit_connect.button_packet import ButtonPacket


######################################################
#   Variables
######################################################
ble = BLERadio()                                            # Turn on Bluetooth
uart_server = UARTService()                                 # Turn on UART
advertisement = ProvideServicesAdvertisement(uart_server)   # Set up notice for other devices that Clue has a Bluetooth UART connection

maxSpeed = 35

clue.sea_level_pressure = 1020                              # Set sea level pressure for Clue's Altitude sensor.

######################################################
#   Main Code
######################################################
while True:
    print("WAITING for BlueFruit device...")
    
    # Advertise when not connected.
    ble.start_advertising(advertisement)                # Tell other devices that Clue has a Bluetooth UART connection.
    while not ble.connected:                            # Check to see if another device has connected with the Clue via Bluetooth.
        if clue.button_a:
Ejemplo n.º 27
0
    (0, 13),  # Bass > Kraft Bass
    (6, 9),  # Percussion > Space Hat
]

patch_count = len(touch_patch)
patch_index = (
    patch_count - 1
)  # start on the last one so first time it is pressed it goes to first

cc_x = 0
cc_y = 0
cc_prox = 0

# Use default HID descriptor
midi_service = adafruit_ble_midi.MIDIService()
advertisement = ProvideServicesAdvertisement(midi_service)

ble = adafruit_ble.BLERadio()
if ble.connected:
    for c in ble.connections:
        c.disconnect()

midi = adafruit_midi.MIDI(midi_out=midi_service, out_channel=midi_channel - 1)

print("advertising")
ble.name = "CLUE BLE MIDI"
ble.start_advertising(advertisement)

clue.display.brightness = 1.0
clue.pixel.brightness = 0.2
screen = displayio.Group()
Ejemplo n.º 28
0
import time
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

#构建蓝牙对象
ble = BLERadio()

#定义广播名称
ble.name='01Studio'

#构建UART服务
Uart_Service = UARTService()

#广播添加UART服务
advertisement = ProvideServicesAdvertisement(Uart_Service)

while True:

    #发起广播
    ble.start_advertising(advertisement)

    #等待连接
    while not ble.connected:
        pass

    #连接蔡成功
    while ble.connected:

        # 读取128个字节数据,如果没数据,则返回 b''
        one_byte = Uart_Service.read(128)
Ejemplo n.º 29
0
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket

#构建蓝牙对象
ble = BLERadio()

#定义广播名称
ble.name = '01Studio'

#构建UART服务
uart_server = UARTService()

#广播添加UART服务
advertisement = ProvideServicesAdvertisement(uart_server)

#定义neopixel引脚,默认使用板载neopixel
pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.1)

while True:
    # 广播
    ble.start_advertising(advertisement)

    #等待连接
    while not ble.connected:
        pass

    #已连接
    while ble.connected:
SERVICE_NAME = "My UART"  # 8 chars max

# setup UART
uart = busio.UART(board.TX, board.RX)

# setup bluetooth
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
ble.name = "UART With BLE"
uart_service = UARTService()
advertisement = ProvideServicesAdvertisement(uart_service)
advertisement.short_name = SERVICE_NAME
# advertisement.complete_name = "UART BLE" # no more than 8 to not go into extended adv ?

was_connected = False
while True:
    # Advertise BLE when not connected.
    if not ble.connected:
        was_connected = False

        if not ble.advertising:
            print(f'Start advertising as "{SERVICE_NAME}"')
            ble.start_advertising(advertisement, interval=0.5, timeout=5)

        # dismiss uart buffer when not connected
        if uart.in_waiting: