예제 #1
0
for y in range(8):
    for x in range(8):
        trellis.activate_key(x, y, NeoTrellis.EDGE_RISING)
        trellis.activate_key(x, y, NeoTrellis.EDGE_FALLING)
        trellis.set_callback(x, y, buttonEvent)


def tick(cmd=None):
    toy.tick(cmd)
    trellis.sync()
    time.sleep(0.02)


while True:
    print('Toy offline.')
    ble.start_advertising(advertisement)
    while not ble.connected:
        tick()
    print('Connected yay.')
    ble.stop_advertising()
    while ble.connected:
        if uart.in_waiting > 0:
            print('UART has data', end='')
            # there's data
            cmd = uart.readline().decode('ascii').strip()
            print(':', cmd)
            tick(cmd)
        else:
            tick()
예제 #2
0
    ble.start_advertising(advertisement)

    #if the bluetooth is not connected the red light will be ON
    #it is also a good way to check if the program is running
    led.value = True

    while not ble.connected:
        led.value = True

    # Now we're connected

    while ble.connected:
            #if the bluetooth is connected the LED will be OFF
            led.value = False
            try:
                streamMessage = uart_service.readline()
                data_string = ''.join([chr(b) for b in streamMessage])
                if data_string == "START":
                    print('START')
                    # Initialise all the motors with the lowest PWM
                    motor1 = pulseio.PWMOut(board.A1, duty_cycle= 65534, frequency=50000)
                    motor2 = pulseio.PWMOut(board.A2, duty_cycle= 65534, frequency=50000)
                    motor3 = pulseio.PWMOut(board.A3, duty_cycle= 65534, frequency=50000)
                    motor4 = pulseio.PWMOut(board.A4, duty_cycle= 65534, frequency=50000)
                    motor5 = pulseio.PWMOut(board.A6, duty_cycle= 65534, frequency=50000)
                    # Call the start method, if a new message from the bluetooth is captured
                    # inside of the start method, it will be returned
                    data_string = start()
                if data_string == "STOP":
                    print('STOP')
                    stop()
예제 #3
0
     if not buttons[0] and _buttons[0]:
         print('Button A pressed!')
     if not buttons[1] and _buttons[1]:
         print('Button B pressed!')
     if not buttons[2] and _buttons[2]:
         print('Button C pressed!')
     if not buttons[3] and _buttons[3]:
         print('Button D pressed!')
     if ble.connected:
         display_image('/bluetooth.bmp')
 else:
     # **** Connected Behavior ****
     # If any data has been sent to us, read it
     # NOTE: this assumes line-terminated messages!
     if uart.in_waiting:
         s = uart.readline()
         if s:
             s = s.strip().decode()
             print(s)
             if s == 'ok':
                 display_image('/ok.bmp')
             if s == 'cancel':
                 display_image('/cancel.bmp')
             if s == 'bluetooth':
                 display_image('/bluetooth.bmp')
             if s == 'green':
                 group = displayio.Group()
                 group.append(Rect(0, 0, 240, 240, fill=0x00FF00))
                 display.show(group)
             if s == 'red':
                 group = displayio.Group()
예제 #4
0
파일: code.py 프로젝트: ECE492CHDS1/CHDS
    # blue LED is on when connected
    blue_led.value = True
    pixel.fill(color.BLUE)
    pixel.show()
    print("Connected")

    # for connection in ble.connections:
    #     if connection.connected:
    #         if not connection.paired:
    #             #  pairs to phone
    #             connection.pair(bond=True)
    #             print("Paired")

    while ble.connected:
        if uart_service.in_waiting:
            line = uart_service.readline()
            command = line.strip().decode('utf-8')
            print("Command: " + command)

            if command == 'alert':
                pixel.fill(color.CYAN)
                pixel.show()
                vibrate(1, 0.5, 0)

            pixel.fill(color.BLUE)
            pixel.show()

            uart_service.write(line)

    # if BLE becomes disconnected then blue LED turns off
    # and BLE begins advertising again to reconnect
예제 #5
0
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    # Connected
    ble.stop_advertising()
    print("CONNECTED")

    # Loop and read packets
    while ble.connected:
        if uart_server.in_waiting:
            # Requires a newline character at the end (the Adafruit Bluefruit LE Connect app can be set to add this automatically)
            # If transmitted text-strings are expected to be very long, use
            # the uart_server.readinto(enter_buffername_here) method instead
            raw_bytes = uart_server.readline()
            text = raw_bytes.decode().strip()
            num_lines = len(text) // char_line
            if ((len(text) % char_line) > 0):
                num_lines += 1
            print("text =", text)

            # auto-wraps, -scrolls and displays the received text-string
            for line in range(0, num_lines, 1):
                start = line * char_line
                if (line == (num_lines - 1)):
                    end = start + (len(text) % char_line)
                else:
                    end = start + char_line

                display.text(string=text[start:end],
예제 #6
0
class Aquarium:
    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)

    def heartbeat(self):
        self.watchdog.feed()
        self._heartbeat.value = True
        time.sleep(self._heartbeat_duration)
        self._heartbeat.value = False

    def update_temps(self):
        self.water_temp = self.water_sensor.temperature
        self.air_temp = self.air_sensor.temperature

    def update_log(self):
        if not self._log_data:
            return

        if self._last_log:
            last_log_secs = time_struct_to_secs(self._last_log)
            current_secs = time_struct_to_secs(self._now)
            if current_secs - last_log_secs < self._log_interval:
                return

        print("Updating log:")
        datestamp, timestamp, log_line = self._get_status_strings()
        filename = datestamp + ".log"
        print(filename)
        print(log_line)
        with open("/sd/scales_logs/" + filename, mode="at", buffering=1) as logfile:
            logfile.write(log_line + "\n")
        self._last_log = self._now
        self._last_log = self._now
        print("Done.\n")

    def blelele(self):
        if not self._ble.connected:
            # Not connected, so make sure we're advertising for connections.
            try:
                self._ble.start_advertising(self._ble_ad)
            except BluetoothError:
                # Already advertising. Probably.
                pass
            return

        if self._ble_uart.in_waiting:
            # There's a command waiting.
            ble_command = self._ble_uart.readline()
            if ble_command:
                # First echo command, then respond.
                self._ble_uart.write(ble_command + b'\n')
                self._ble_respond(ble_command)

    def run_once(self):
        self.heartbeat()
        self._now = time.localtime()
        self.lights.update()
        self.feeder.update()
        self.update_temps()
        self.display.update()
        self.update_log()
        self.blelele()
        time.sleep(1)

    def run(self):
        while True:
            self.run_once()

    def _ble_respond(self, ble_command):
        if ble_command == b"v?":
            response = bytes(f"{BLE_NAME} v{__version__}\n", 'ascii')
        elif ble_command == b"s?":
            _, _, response = self._get_status_strings()
            response = bytes(response, 'ascii')
        elif ble_command == b"f?":
            response = f"{self.feeder.feeding_times}, {self.feeder.portions_per_meal}"
            response = bytes(response, 'ascii')
        elif ble_command == b"ff":
            self.feeder.feed()
            response = bytes("Fed 1 portion.", 'ascii')
        elif len(ble_command) > 2 and ble_command[:2] == b"fp":
            portions = int(str(ble_command[2:], 'ascii'))
            self.feeder.portions_per_meal = portions
            response = bytes(f"Set portions per meal to {portions}.", 'ascii')
        else:
            command = str(ble_command, 'ascii')
            response = bytes("ERROR: Invalid command '{}'\n".format(command), 'ascii')

        self._ble_uart.write(response)

    def _get_status_strings(self):
        datestamp = "{:04d}-{:02d}-{:02d}".format(self._now.tm_year, self._now.tm_mon, self._now.tm_mday)
        timestamp = datestamp + "T{:02d}:{:02d}:{:02d}".format(self._now.tm_hour, self._now.tm_min, self._now.tm_sec)
        status = "{}, {:d}, {:7.4f}, {:7.4f}".format(timestamp, self.lights.is_enabled, self.water_temp, self.air_temp)
        return datestamp, timestamp, status