def _on_hour(self,
                 hour,
                 minute,
                 second,
                 silent_night=False,
                 day_hours_range=(7, 22)):
        day_hour_min, day_hour_max = day_hours_range

        if minute == second == 0:
            print("\n[Clock: now is {} o'clock]\n".format(hour))

            if (silent_night is False) or (day_hour_min <= hour <=
                                           day_hour_max):

                times_to_signal = hour % 12
                if times_to_signal == 0:
                    times_to_signal = 12

                led.blink(self.buzzer,
                          times=times_to_signal - 1,
                          on_seconds=0.1,
                          off_seconds=0.9,
                          high_is_on=self.led_high_is_on)
                led.blink(self.buzzer,
                          times=1,
                          on_seconds=0.5,
                          off_seconds=0.5,
                          high_is_on=self.led_high_is_on)
Exemple #2
0
def ledOn(x, blink=False):
    '''to contrl led on or blink for 1 second, x should be within [0,8]'''
    byte = led.translate_led_to_byte(x)
    if blink:
        led.blink(byte)
    else:
        led.turn_on(byte)
Exemple #3
0
def initialize():
    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."

    serial_ok = False

    if os.path.exists("/log/.factory") or os.path.exists(
            "/log/updates/FACTORYRESET") or os.path.exists(
                "/log/updates/UPDATE") or os.path.exists(
                    "/log/updates/RESETSETTINGS"):
        os.system("rm -f /log/.factory")
    else:
        serial_ok = checkArduCopter()

        # if we're in factory reset, just reset parameters and exit
        if recoveryCheck() and serial_ok:
            resetParameters()
        else:
            # find and load ArduCopter FW
            if doFirmware():
                serial_ok = checkArduCopter()

            # reset ArduCopter parameters if tagged
            if os.path.exists("/firmware/resetParams") and serial_ok:
                resetParameters()
                os.remove("/firmware/resetParams")

    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Exemple #4
0
def _connect_wifi(netdb, timeout):
    # lazy import to avoid initializing the network if we don't want it
    import network
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    if sta_if.isconnected():
        print('wlan already connected')
        print('network config:', sta_if.ifconfig())
        return

    print('Scanning for available Wi-Fi networks...')
    blink(1)
    found_ssids = [tup[0] for tup in sta_if.scan()]
    print(len(found_ssids), 'networks found:')
    for name in found_ssids:
        print('   ', name.decode('latin1'))
    print()
    #
    ssid, password = query_ssid(netdb, found_ssids)
    if not ssid:
        print('Cannot find any known SSID')
        return
    #
    print('SSID %s found in wifi.ini, connecting...' % ssid.decode('latin1'))
    sta_if.connect(ssid, password)
    if timeout > 0 and _wait_for_connection(sta_if, ssid, timeout):
        print('network config:', sta_if.ifconfig())
Exemple #5
0
def main():
    reset_lights()
    count = 0  #slows down the loop
    pin = 0  #pin number of LED to light
    old_pin = 0
    idle()
    while True:
        count += 1

        #start the game sequence
        if is_button_pressed() == 0:
            print(game_state)
            if game_state == "idle":
                game()
                sound("game")

            #check results of game
            elif game_state == "game":
                end_game(pin)
            time.sleep(.5)

        #Game blinks at higher rate
        if count == 25 or count == 50 or count == 75:
            if game_state == "game":
                old_pin = pin
                pin = non_repeating_random(pin)
                #print("blink "+str(pin))
                led.blink(old_pin, pin)

        if count > 100:
            count = 0

            #once ambient sound complete and state is idle pick another song
            if pygame.mixer.music.get_busy() == 0:
                if game_state == "idle":
                    music()
                elif game_state == "game":
                    end_game(pin)

            #depending on state blink lights
            if game_state == "game":
                old_pin = pin
                pin = non_repeating_random(pin)
                #print("blink "+ str(pin))
                led.blink(old_pin, pin)
            elif game_state == "idle":
                pin = non_repeating_random(pin)
                #print("fade "+str(pin))
                led.on(pin)
                led.fade(pin)
        time.sleep(.01)  #slow loop down a bit
Exemple #6
0
def led_machine(state, dur):
    if state == 1:
        led_off()
        led_persist()
    elif state == 2:
        led_off()
        time.sleep(0.1)
        for i in range(dur):
            blink()
    elif state == 3:
        led_off()
        time.sleep(0.1)
        for i in range(dur):
            fade()
    else:
        led_off()
Exemple #7
0
    def handle_read(self):
        try:
            data = self.recv(1024)
            if not data:
                return

            lf_char_index = data.find('\n')

            if lf_char_index == -1:
                # No new line character in data, so we append all.
                self.data += data
            else:
                # We see a new line character in data, so append rest and handle.
                self.data += data[:lf_char_index]

                if self.data == "blink":
                    print "blink start"
                    led.blink(led_pin, 1, 1, 5)
                    print "blink end"

                elif self.data == "turn LED on":
                    print "turning on LED"
                    self.send("turning on LED")
                    led.on(led_pin)

                elif self.data == "turn LED off":
                    print "turning off LED"
                    self.send("turning off LED")
                    led.off(led_pin)

                elif self.data == "read adc":
                    read_value = adc.read0()
                    print "ADC 0 value read: " + str(read_value)
                    self.send(str(read_value) + '\n')

                else:
                    print "received [%s]" % self.data
                    self.send(self.data + '\n')

                # Clear the buffer
                self.data = ""
        except Exception as e:
            BTError.print_error(handler=self, error=BTError.ERR_READ, error_message=repr(e))
            self.data = ""
            self.handle_close()
Exemple #8
0
    def _on_hour(self, hour, minute, second):

        if minute == second == 0:
            print("\n[Clock: now is {} o'clock]\n".format(hour))

            times_to_signal = hour % 12
            if times_to_signal == 0: times_to_signal = 12

            led.blink(self.buzzer,
                      times=times_to_signal - 1,
                      on_seconds=0.1,
                      off_seconds=0.9,
                      high_is_on=self.led_high_is_on)
            led.blink(self.buzzer,
                      times=1,
                      on_seconds=0.5,
                      off_seconds=0.5,
                      high_is_on=self.led_high_is_on)
Exemple #9
0
def _wait_for_connection(sta_if, ssid, timeout):
    import time
    blink(2)
    timeout *= 1000  # convert from seconds to ms
    start_time = time.ticks_ms()
    next_print = start_time
    i = 0
    while not sta_if.isconnected():
        # this sleep seems to be necessary on my sonoff device. On the other
        # hand, on the wemos D1 it connected even without it, no clue why
        time.sleep_ms(10)
        cur_time = time.ticks_ms()
        if time.ticks_diff(cur_time, start_time) >= timeout:
            print('connection timed out, giving up')
            sta_if.disconnect()
            return False
        if time.ticks_diff(cur_time, next_print) >= 0:
            i += 1
            next_print = time.ticks_add(cur_time, 1000)
            print('connecting to %s... [%d]' % (ssid, i))
    return True
Exemple #10
0
def message_handler(message):
  
    #if chk.if_digit(message[2]):
  #print('start message handler')
  if message[2] == '/temp':
      led.blink()
      tem = str(dht22.dhtTemp())
      telegram.send(message[0], 'dht22 temp =>' + tem)
      print(message[2])
  else: 
    if message[2] == '/hum':
      led.blink()
      tem = str(dht22.dhtHum())
      telegram.send(message[0], 'dht22 hum =>' + tem)
      print(message[2])
    else:
      if message[2] == '/out':
        led.blink()
        tem = str(ds18.ds18Temp())
        telegram.send(message[0], 'ds18 temp =>' + tem)
        print(message[2])
      else:
        if message[2] == '/press':
          led.blink()
          tem = str(pressure.getPresure())
          telegram.send(message[0], 'pressure =>' + tem)
          print(message[2])
        else:
          if message[2] == '/co2':
            led.blink()
            tem = str(co2.getCO2())
            telegram.send(message[0], 'co2 =>' + tem)
            print(message[2])
          else:
            led.blink()
            telegram.send(message[0], 'received  text => ' + message[2] + ' /temp /hum /out /press /co2')
            print(message[2])
        

  gc.collect()
Exemple #11
0
import RPi.GPIO as GPIO
import led as Led

led = 17
delay = 1


def setup():

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(led, GPIO.OUT)


setup()

try:

    while True:

        Led.blink(led, delay)

except KeyboardInterrupt:

    GPIO.cleanup()
Exemple #12
0
import led

#HTML to send to browsers
html = """<!DOCTYPE html>
<html>
<head> <title>ESP8266 LED ON/OFF</title> </head>

<form>
LED0: 
<button name="LED" value="ON0" type="submit">LED ON</button>
<button name="LED" value="OFF0" type="submit">LED OFF</button><br><br>

</form>
</html>
"""
led.blink()
#Setup PINS
LED0 = machine.Pin(4, machine.Pin.OUT)

#Setup Socket WebServer
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
    conn, addr = s.accept()
    print("Got a connection from %s" % str(addr))
    request = conn.recv(1024)
    print("Content = %s" % str(request))
    request = str(request)
    LEDON0 = request.find('/?LED=ON0')
    LEDOFF0 = request.find('/?LED=OFF0')
Exemple #13
0
    client = connect_mqtt()
    client.subscribe(topic_device_control)
    client.on_message = on_message
    client.on_connect = on_connect
    thread = threading.Thread(target=client.loop_forever)
    thread.start()
    sleep(1)
    while True:
        led.turn_off_all()
        print("Hold a tag near the reader")
        id, text = reader.read()
        print(id, text)
        client_id = 'tag-' + str(id)
        if (text == ''):
            print("TAG NOT READ!! TRY AGAIN")
            led.blink('blue', 3)
        message = {
            'sensor_id': client_id,
            'type_sensor': 'rfid',
            'type_value': 'fundsSource',
            'value': text.rstrip("\n")
        }
        publish(client, topic_device, json.dumps(message))
        sleep(5)

finally:
    print('error occured!!')
    GPIO.cleanup()

# try:
#         text = input('New data:')
Exemple #14
0
def initialize():
    global cube_version
    firmware_path = None
    paramsAfterLoad = False

    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."
    baud = get_baud()
    if baud == None:
        print "pixhawk: ERROR checking baud"
        logger.error("finding baud")
        logger.error("pixhawk status: no response")
        # pixhawk might be stuck in bootloader

    # If we're in a factory reset, we just need to reset the pixhawk.
    # If we've just completed the clean install, load the appropriate ArduCopter FW and reset the pixhawk
    # Otherwise, just look in /firmware and load whatever is there.
    if recoveryCheck():
        resetParameters()
        rebootPixhawk()
    else:
        if (os.path.isdir("/firmware/3dr")
                or os.path.isdir("/firmware/green")) and checkPixhawkVersion():
            # This must be a clean install if the initial FW directories are here.
            paramsAfterLoad = True
            if cube_version == 'cube_20':
                (firmware_path,
                 firmware_version) = find_firmware(firmware_root_3dr)
            elif cube_version == 'cube_21':
                (firmware_path,
                 firmware_version) = find_firmware(firmware_root_green)
        else:
            # Not a clean install, look for FW in the normal location
            (firmware_path, firmware_version) = find_firmware(firmware_root)

    if firmware_path is None:
        logger.info("no new firmware file")
    elif os.path.exists("/log/.factory") and (baud
                                              is not None) and verify_usb():
        logger.info("pixhawk: factory - not loading firmware")
    else:
        print "pixhawk: loading firmware"
        logger.info("%s:", firmware_path)
        for v in firmware_version:
            logger.info("%-20s %s", v, firmware_version[v])
        if load(firmware_path):
            move_firmware(firmware_path)
            os.system("rm -rf /firmware/3dr")
            os.system("rm -rf /firmware/green")
            os.system("rm -rf /firmware/wipe")
            if paramsAfterLoad:
                logger.info("Executing post-install parameter reset...")
                resetParameters()
                rebootPixhawk()
                logger.info("...Reset complete")
        else:
            print "pixhawk: ERROR loading firmware"
            logger.error("pixhawk status: can't load")

    os.system("rm -f /log/.factory")

    running_version = get_version()
    logger.info(running_version)

    logger.info("now running:")
    for component in [
            "build_version", "ardupilot_git_hash", "px4_git_hash",
            "nuttx_git_hash"
    ]:
        if component in running_version:
            version = running_version[component]
        else:
            version = "unknown"
        logger.info("%-20s %s", component, version)
    write_version_file(running_version)
    if "build_version" in running_version \
        and running_version["build_version"] != "unknown":
        logger.info("pixhawk status: ready")
        print "pixhawk: running %s" % running_version["build_version"]
    else:
        print "pixhawk: ERROR checking version"
    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Exemple #15
0
import sys
import getopt

import webserver
import seriallog
import upload
import settings
import nfc
import led

import ultraduo
import imaxb6
import charger

led.init()
led.blink()


c = ultraduo.UltraDuo()
p = '/dev/ttyUSB0'

#for charger in settings.chargers:
_thread.start_new_thread( seriallog.serial_server, (p, c) )
_thread.start_new_thread( upload.upload_server, (c, ) )
_thread.start_new_thread( webserver.start_webserver, (c, ) )
_thread.start_new_thread( nfc.nfc_server, () )

while True:
  if c.channels[0].newdata > 0:
    led.toggle(led.RED)
    c.channels[0].newdata = 0
Exemple #16
0
def initialize():
    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."
    baud = get_baud()
    if baud == None:
        print "pixhawk: ERROR checking baud"
        logger.error("finding baud")
        logger.error("pixhawk status: no response")
        # pixhawk might be stuck in bootloader

    # try to load if we have firmware, whether we found the baud or not

    (firmware_path, firmware_version) = find_firmware()
    if firmware_path is None:
        logger.info("no new firmware file")
        # Another backup would be to look in /firmware/loaded and load
        # whatever's there if we did not get a heartbeat. Getting stuck in
        # the bootloader has so far only been observed to happen when a
        # programming is interrupted, in which case the firmware we were
        # loading is still in /firmware.
    elif os.path.exists("/log/.factory") and \
         (baud is not None) and \
         verify_usb():
        logger.info("pixhawk: factory - not loading firmware")
        move_firmware(firmware_path)
    else:
        print "pixhawk: loading firmware"
        logger.info("%s:", firmware_path)
        for v in firmware_version:
            logger.info("%-20s %s", v, firmware_version[v])
        if load(firmware_path):
            move_firmware(firmware_path)
        else:
            print "pixhawk: ERROR loading firmware"
            logger.error("pixhawk status: can't load")

    # If .factory exists, we either found a baud, passed USB, and skipped
    # loading pixhawk, or either did not find a baud or USB heartbeat, and
    # loaded pixhawk.
    os.system("rm -f /log/.factory")

    # We have followed some combination of these to get here:
    #   * found baud | did not find baud
    #   * no firmware | firmware and flashed it | firmware and error flashing
    #
    # The cases that are known to happen:
    #   Normal cases
    #   * Found baud, there was no new firmware
    #   * Found baud, there was new firmware, flashed it
    #   Error cases
    #   * Did not find baud, there was new firmware, flashed it
    #
    # Other cases should "never" happen (and have not been observed):
    #   * Did not find baud, there was no new firmware
    #       The only known way to not find the baud is if pixhawk is stuck in
    #       its bootloader, which happens because flashing was interrupted,
    #       which means there is new firmware available.
    #   * Found baud, there was new firmware, error flashing it
    #   * Did not find baud, there was new firmware, error flashing it
    #       Should "never" fail to flash pixhawk when we try to.

    # This should work for any of the three known-to-happen cases. For the
    # error cases, running_version will be set to an empty dictionary, and
    # write_version_file will write "unknown" for all the versions.
    # get_version() can return None if the configuration is corrupt, but in
    # that case we have far deeper problems (an md5 has just succeeded).
    running_version = get_version()

    logger.info("now running:")
    for component in [
            "build_version", "ardupilot_git_hash", "px4_git_hash",
            "nuttx_git_hash"
    ]:
        if component in running_version:
            version = running_version[component]
        else:
            version = "unknown"
        logger.info("%-20s %s", component, version)
    write_version_file(running_version)
    if "build_version" in running_version \
        and running_version["build_version"] != "unknown":
        logger.info("pixhawk status: ready")
        print "pixhawk: running %s" % running_version["build_version"]
    else:
        print "pixhawk: ERROR checking version"
    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Exemple #17
0
                #show the index of the site, +1 offset to make it more readable
                SAKS.digital_display.show("%04d" % (i + 1))
                #use num of leds to show the delay level measured in ms
                if delay is not None:
                    if delay <= 250:  #(<250ms)
                        ledOn(1)
                    elif delay <= 500:  #(<500ms)
                        ledOn(2)
                    elif delay <= 1000:
                        ledOn(3)
                    elif delay <= 1500:
                        ledOn(4)
                    elif delay <= 2000:
                        ledOn(5)
                    else:
                        ledOn(6)
                else:
                    #alarm with a beep and blink all light
                    if (beep_flag):
                        beeper.beep = True
                    led.blink(0xf0)
    except Exception, e:
        traceback.print_exc()
    except KeyboardInterrupt:
        pass
    finally:
        beeper.stop = True
        beeper.join()
        SAKS.digital_display.off()  #digital display off
        led.turn_on(0x00)
Exemple #18
0
def connect_wifi(netdb, timeout=10):
    try:
        _connect_wifi(netdb, timeout)
    finally:
        blink(0)