Beispiel #1
0
def update_rfid_card(player):
    print("Writing to player RFID")
    print player.get_rfid_data()
    while not puzzle_rfid.write_player_data(player.get_rfid_data()):
        lcd_i2c.lcd_string("Please verify", lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string("your amulet", lcd_i2c.LCD_LINE_2)
        gevent.sleep(0.1)
Beispiel #2
0
def play(keyboard_obj):

    rfid_data = gevent.spawn(wait_for_rfid).get()
    player = gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, lookup_player,
                                 rfid_data)

    if (player):
        gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, play_video_for_user,
                            player)
        lcd_i2c.display_on()
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, check_win_condition,
                            player)
    else:
        gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT,
                            play_video_for_new_user)
        lcd_i2c.display_on()
        name = gevent.with_timeout(BASE_STATION_TASK_TIMEOUT,
                                   get_keyboard_entry, keyboard_obj,
                                   "Enter your name:", 15)
        initial_choice_past = gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT,
                                                  get_initial_choice,
                                                  keyboard_obj)
        player = Player(name=name,
                        uid=rfid_data["uid"],
                        initial_choice_past=initial_choice_past)
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, update_rfid_card,
                            player)
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, add_or_update_player,
                            player)
        lcd_i2c.lcd_string("Refer to map to", lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string("continue journey", lcd_i2c.LCD_LINE_2)
        gevent.sleep(5)

    lcd_i2c.display_off()
Beispiel #3
0
def update_rfid_card(player):
    print("Writing to player RFID")
    print player.get_rfid_data()
    while not puzzle_rfid.write_player_data(player.get_rfid_data()):
        lcd_i2c.lcd_string("Please verify", lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string("your amulet", lcd_i2c.LCD_LINE_2)
        gevent.sleep(0.1)
Beispiel #4
0
def button_release(channel):
    global service
    global name_count
    global RANGE_NAME
    global row

    start_time = time.time()

    while GPIO.input("P8_12") == 0:
        pass

    button_time = time.time() - start_time
    print(button_time)

    if button_time >= 2 and row != '':
        # callback to flash LED
        update(service)
    elif button_time < 2:
        name_string = names[name_count]
        lcd_i2c.lcd_string(name_string, lcd_i2c.LCD_LINE_1)
        RANGE_NAME = column[name_count] + row
        if name_count < 15:
            name_count += 1
        else:
            name_count = 0
        print("Button pressed ")
Beispiel #5
0
def pump_on_lcd(
):  # The LCD for pump on indefinately, started as a thread in pump_on
    while True:
        Pumptime = datetime.now() - TimeOn
        lcd_string("RAINMAKER  " + datetime.now().strftime('%H:%M'),
                   LCD_LINE_1)
        lcd_string("Pomp aan   " + str(format_timedelta(Pumptime)), LCD_LINE_2)
        if stop_threads:
            break
def print_number_of_nodes():
    ret = k_v1.list_node(watch=False)
    nodes_ready = 0
    nodes_total = len(ret.items)

    for node in ret.items:
        for condition in node.status.conditions:
            if condition.type == 'Ready' and condition.status == 'True':
                nodes_ready += 1

    lcd.lcd_string('k3s nodes:', lcd.LCD_LINE_1)
    lcd.lcd_string(str(nodes_ready) + ' / ' + str(nodes_total), lcd.LCD_LINE_2)
Beispiel #7
0
def loop():
    global power_state
    global led

    while True:
        # lcd초기화
        lcd.lcd_init()
        # 먼지센서 동작
        ser = serial.Serial(SERIAL_PORT, Speed, timeout=1)
        buffer = ser.read(1024)

        if (dustlib.protocol_chk(buffer)):
            data = dustlib.unpack_data(buffer)

            global pm1
            global pm25
            global pm10
            pm1 = int(data[dustlib.DUST_PM1_0_ATM])
            pm25 = int(data[dustlib.DUST_PM2_5_ATM])
            pm10 = int(data[dustlib.DUST_PM10_0_ATM])
            print("PMS 7003 dust data")
            print("PM 1.0 : %d" % (pm1))
            print("PM 2.5 : %d" % (pm25))
            print("PM 10.0 : %d" % (pm10))
        else:
            print("data read Err")

        # 전원 상태에 따른 동작

        if power_state == 0:
            print("전원꺼짐")
            fan_power(OFF)
            lcd.LCD_BACKLIGHT = 0x00
            lcd.lcd_string("   Power Off   ", lcd.LCD_LINE_1)
            lcd.lcd_string("", lcd.LCD_LINE_2)
            led.off()
        if power_state == 1:
            print("전원켜짐")
            fan_power(ON)
            display_dust(pm1, pm25, pm10)
        if power_state == 2:
            print("자동모드")
            if pm10 <= 30 and (pm1 + pm25) <= 15:
                fan_power(OFF)
            else:
                fan_power(ON)

            display_dust(pm1, pm25, pm10)
        # powersw.wait_for_press(timeout=2)
        time.sleep(1)
Beispiel #8
0
def get_initial_choice(keyboard_obj):
    lines = [
        ################
        ["Read passage", "and answer"],
        ["wisely, as your", "choices may"],
        ["change your", "destiny."]
    ]
    for line in lines:
        lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
        gevent.sleep(4)
    pass

    while (True):
        lines = [
            ################
            ["Do you burn", "the receipt?"],
            ["1. Burn receipt", "2. Keep receipt"]
        ]

        for line in lines:
            lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
            lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
            gevent.sleep(4)
        pass
        gevent.sleep(3)
        choice = get_keyboard_entry(keyboard_obj, "Enter choice:", 1)

        if (choice == '1'):
            return False  #present choice
        elif (choice == '2'):
            return True  #past choice
Beispiel #9
0
def scroll_button():
    global service
    global name_count
    global RANGE_NAME
    global row
    global lcd_call

    name_string = names[name_count]
    lcd_i2c.lcd_string(name_string, lcd_i2c.LCD_LINE_1)
    lcd_call += 1
    RANGE_NAME = column[name_count] + row
    if name_count < 15:
        name_count += 1
    else:
        name_count = 0
    logging.debug('Scroll press')
    print("Button pressed ")
Beispiel #10
0
def main():
    # Main program block

    # Initialise display
    lcd_i2c.lcd_init()

    while True:
        temp = bme280.temperature
        humidity = bme280.humidity

        # Send to LCD
        lcd_i2c.lcd_string("Temperature: " + "{:.1f}".format(temp) + " C",
                           lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string("Humidity: " + "{:.1f}".format(humidity) + " %",
                           lcd_i2c.LCD_LINE_2)

        time.sleep(3)
Beispiel #11
0
def main():

    # First line
    response = feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "@mail.google.com/gmail/feed/atom")
    unread_count = int(response["feed"]["fullcount"])

    # result = datetime.datetime.today().strftime("%d.%m/%H:%M") + " "
    result_1 = datetime.datetime.today().strftime("%H:%M") + " "
    result_1 += "G:" + str(unread_count) + " "
    observation = owm.weather_at_place('Zmigrod,pl')
    w = observation.get_weather()
    result_1 += "T:" + str(int(w.get_temperature('celsius')['temp'])) + "/"
    # result_1 += "W:" + str(int(w.get_wind()['speed'])) + " "
    # result_1 += "P:" + str(w.get_pressure()['press'])
    # result_1 += str(w.get_clouds()) + " "
    result_1 += str(w.get_humidity())

    # Second line

    # Kudos count
    kudos_count = 0
    for activity in client.get_activities():
        # print("{0.name} {0.moving_time} {0.distance}".format(activity))
        kudos_count += activity.kudos_count
    result_2 = "K:" + str(kudos_count) + " "

    # Followers count
    result_2 += "F:" + str(athlete.follower_count) + " "

    # Distance in this week
    today = datetime.date.today()
    monday = str(today - datetime.timedelta(days=today.weekday()))
    monday += "T00:00:00Z"
    distance = 0
    for activity in client.get_activities(after = monday,  limit=15):
        # print("{0.name} {0.moving_time} {0.distance}".format(activity))
        distance += float(activity.distance)
    distance /= 1000
    distance = round(distance, 1)
    result_2 += str(distance) + "km"

    lcd_i2c.lcd_init()
    lcd_i2c.lcd_string(result_1, lcd_i2c.LCD_LINE_1)
    lcd_i2c.lcd_string(result_2, lcd_i2c.LCD_LINE_2)
Beispiel #12
0
def input():
    logging.debug('Input started')
    GPIO.output(GreenLed, GPIO.HIGH)
    GPIO.output(RedLed, GPIO.LOW)
    global TimeOn
    global TimeOff
    lcd_string("Pomp standby..", LCD_LINE_2)
    while True:
        lcd_string("RAINMAKER  " + datetime.now().strftime('%H:%M'),
                   LCD_LINE_1)
        if GPIO.input(A):
            logging.debug('Input A')
            logging.info('Pump turned on remotely')
            TimeOn = datetime.now()
            pump_on()
            break
        elif GPIO.input(C):
            logging.debug('Input C')
            TimeOn = datetime.now()
            TimeOff = datetime.now() + timedelta(minutes=60)
            logging.info('Pump turned on remotely, timeOff set at: %s',
                         TimeOff)
            pump_on_timer()
            break
        elif GPIO.input(D):
            logging.debug('Input D')
            TimeOn = datetime.now()
            TimeOff = datetime.now() + timedelta(minutes=120)
            logging.info('Pump turned on remotely, timeOff set at: %s',
                         TimeOff)
            pump_on_timer()
            break
        elif GPIO.input(SW) == False:
            logging.debug('Input SW(rotenc)')
            time.sleep(0.1)
            timer_menu()
            break
        elif GPIO.input(GreenButton):
            logging.debug('Input GreenButton')
            logging.info('Pump turned on locally')
            TimeOn = datetime.now()
            pump_on()
            break
Beispiel #13
0
def timer_menu_end():
    logging.debug('Timer menu end started')
    global TimeOff
    TimeOff = TimeOn + timedelta(minutes=30)
    clkLastState = GPIO.input(clk)
    lcd_string("Start time " + TimeOn.strftime("%H:%M"), LCD_LINE_1)
    lcd_string("End time   " + TimeOff.strftime("%H:%M"), LCD_LINE_2)
    while True:
        clkState = GPIO.input(clk)
        dtState = GPIO.input(dt)
        if clkState != clkLastState:
            time.sleep(0.02)
            if dtState != clkState:
                TimeOff += timedelta(minutes=15)
            else:
                TimeOff -= timedelta(minutes=15)
            lcd_string("End time   " + TimeOff.strftime("%H:%M"), LCD_LINE_2)
            print("End time = " + TimeOff.strftime("%H:%M"))
            clkLastState = clkState
            time.sleep(0.02)
        elif GPIO.input(SW) == False:
            time.sleep(0.1)
            logging.debug('Input SW')
            logging.info('End time set at ' + TimeOff.strftime("%H:%M"))
            stop.set()
            t1.join()
            pump_on_timer()
            break  # Removed break to see if RAINMAKER wouldn't appear ater pushing button while nothing else was configured
        elif GPIO.input(RedButton):
            logging.debug('Input RedButton')
            logging.info('Timer menu closed without setting a timer')
            stop.set()
            t1.join()
            input()
            break
Beispiel #14
0
def play(keyboard_obj):

    rfid_data = gevent.spawn(wait_for_rfid).get()
    player = gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, lookup_player, rfid_data)

    if(player):
        gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, play_video_for_user, player)
        lcd_i2c.display_on()
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, check_win_condition, player)
    else:
        gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, play_video_for_new_user)
        lcd_i2c.display_on()
        name = gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, get_keyboard_entry, keyboard_obj, "Enter your name:", 15)
        initial_choice_past = gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, get_initial_choice, keyboard_obj)
        player = Player(name=name, uid=rfid_data["uid"], initial_choice_past=initial_choice_past)
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, update_rfid_card, player)
        gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, add_or_update_player, player)
        lcd_i2c.lcd_string("Refer to map to", lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string("continue journey", lcd_i2c.LCD_LINE_2)
        gevent.sleep(5)


    lcd_i2c.display_off()
Beispiel #15
0
def pump_on_timer_lcd(
):  # The LCD for pump on timer, started as a thread in pump_on_timer
    while True:
        lcd_string("RAINMAKER  " + datetime.now().strftime('%H:%M'),
                   LCD_LINE_1)
        if datetime.now() < TimeOn:
            lcd_string("Pomp aan:  " + TimeOn.strftime('%H:%M'), LCD_LINE_2)
            time.sleep(2)
            lcd_string("Pomp uit:  " + TimeOff.strftime('%H:%M'), LCD_LINE_2)
            time.sleep(2)
            if stop_threads:
                break
        elif datetime.now() >= TimeOn:
            lcd_string("Pomp uit:  " + TimeOff.strftime('%H:%M'), LCD_LINE_2)
            time.sleep(0.5)
            if stop_threads:
                break
Beispiel #16
0
def get_initial_choice(keyboard_obj):
    lines = [
        ################
        ["Read passage",
         "and answer"],
        ["wisely, as your",
         "choices may"],
        ["change your",
         "destiny."]
    ]
    for line in lines:
        lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
        lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
        gevent.sleep(4)
    pass;
    
    while(True):
        lines = [
            ################
            ["Do you burn",
             "the receipt?"],
            ["1. Burn receipt",
             "2. Keep receipt"]
        ]

        for line in lines:
            lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
            lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
            gevent.sleep(4)
        pass;
        gevent.sleep(3)
        choice = get_keyboard_entry(keyboard_obj, "Enter choice:", 1)

        if(choice == '1'):
            return False #present choice
        elif(choice == '2'):
            return True #past choice
Beispiel #17
0
def get_keyboard_entry(keyboard_obj, prompt, max_len):
    lcd_i2c.lcd_string(prompt, lcd_i2c.LCD_LINE_1)
    key = None
    name = ''
    lcd_i2c.lcd_string(name, lcd_i2c.LCD_LINE_2)
    while key != 'CRLF':
        key = keyboard.keyboard_check_updates(keyboard_obj)
        if (key):
            if key == 'BKSP':
                name = name[:-1]
            elif key in keyboard.nonprintable:
                pass
            else:
                if len(name) < max_len:
                    name += key
            lcd_i2c.lcd_string(name, lcd_i2c.LCD_LINE_2)
        gevent.sleep(0.01)
    return name
Beispiel #18
0
def get_keyboard_entry(keyboard_obj, prompt, max_len):
    lcd_i2c.lcd_string(prompt, lcd_i2c.LCD_LINE_1)
    key = None
    name = ''
    lcd_i2c.lcd_string(name, lcd_i2c.LCD_LINE_2)
    while key != 'CRLF':
        key = keyboard.keyboard_check_updates(keyboard_obj)
        if(key):
            if key == 'BKSP':
                name = name[:-1]
            elif key in keyboard.nonprintable:
                pass
            else:
                if len(name) < max_len:
                    name += key
            lcd_i2c.lcd_string(name, lcd_i2c.LCD_LINE_2)
        gevent.sleep(0.01)
    return name
Beispiel #19
0
def timer_menu():
    logging.debug('Timer menu started')
    global stop
    stop = threading.Event()
    global t1
    t1 = threading.Thread(target=timer_menu_led, args=(stop, ))
    t1.start()
    now = datetime.now()
    global TimeOn
    TimeOn = now + timedelta(minutes=-now.minute,
                             seconds=-now.second,
                             microseconds=-now.microsecond) + timedelta(
                                 minutes=(int(now.minute / 15) * 15) + 15)
    clkLastState = GPIO.input(clk)
    lcd_string("RAINMAKER  " + datetime.now().strftime('%H:%M'), LCD_LINE_1)
    lcd_string("Start time " + TimeOn.strftime("%H:%M"), LCD_LINE_2)
    while True:
        clkState = GPIO.input(clk)
        dtState = GPIO.input(dt)
        if clkState != clkLastState:
            time.sleep(0.02)
            if dtState != clkState:
                TimeOn += timedelta(minutes=15)
            else:
                TimeOn -= timedelta(minutes=15)
            lcd_string("Start time " + TimeOn.strftime("%H:%M"), LCD_LINE_2)
            print("Start time = " + TimeOn.strftime("%H:%M"))
            clkLastState = clkState
            time.sleep(0.02)
        elif GPIO.input(SW) == False:
            time.sleep(0.1)
            logging.debug('Input SW')
            logging.info('Start Time set at ' + TimeOn.strftime("%H:%M"))
            timer_menu_end()
            break
        elif GPIO.input(RedButton):
            logging.debug('Input RedButton')
            logging.info('Timer menu closed without setting a timer')
            stop.set()
            t1.join()
            input()
            break
Beispiel #20
0
def main():
    # Accepted arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("gpio", help="Pin num of DHT22 sensor", type=int)
    parser.add_argument("--led", help="Pin num of LED", type=int)
    parser.add_argument("--max_temp",
                        help="Maximum acceptable temp, default 70F",
                        type=float)
    parser.add_argument("--min_temp",
                        help="Minimum acceptable temp, default 32F",
                        type=float)
    parser.add_argument("--max_rh",
                        help="Maximum acceptable humidity, default 50",
                        type=float)
    parser.add_argument("--min_rh",
                        help="Minimum acceptable humidity, default 30",
                        type=float)
    parser.add_argument("--email", help="Email destination for warnings")
    parser.add_argument("--gsheets",
                        help="Turn on Google Sheets logging, must configure",
                        action='store_true')
    args = parser.parse_args()

    try:
        # get lcd ready
        lcd.lcd_init()
        lcd.lcd_string("Starting monitor", lcd.LCD_LINE_1)
        lcd.lcd_string("script...", lcd.LCD_LINE_2)
        time.sleep(2)
        lcd.lcd_string(time.strftime("%x"), lcd.LCD_LINE_1)
        lcd.lcd_string(time.strftime("%I:%M:%S %p"), lcd.LCD_LINE_2)
        time.sleep(2)

        # get led gpio pin ready and flash it
        if args.led:
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(args.led, GPIO.OUT)
            GPIO.output(args.led, True)
            time.sleep(.4)
            GPIO.output(args.led, False)

        # Get temp/humidity reading
        humidity, temp_c = dht.read_retry(dht.DHT22, args.gpio)
        fahr = 9.0 / 5.0 * temp_c + 32

        # Send reading to LCD
        lcd.lcd_string("Temp={0:0.2f}'F".format(fahr), lcd.LCD_LINE_1)
        lcd.lcd_string("Humidity={0:0.2f}%".format(humidity), lcd.LCD_LINE_2)

        # Check reading for alarm conditions if email is on:
        warned = warning_condition(fahr,
                                   humidity,
                                   email=args.email,
                                   max_temp=args.max_temp or 70.00,
                                   min_temp=args.min_temp or 32.00,
                                   max_rh=args.max_rh or 50.00,
                                   min_rh=args.min_rh or 30.00)

        # Write data to file
        with open("/home/pi/pem-pi/data/temperature_humidity.txt",
                  "a") as myfile:
            myfile.write(dt.now().strftime('%Y-%m-%d %H:%M') + "\t" +
                         "{0:.2f}".format(fahr) + "\t" +
                         "{0:.2f}".format(humidity))
            myfile.write("\n")
            # optionally, send data to google sheets
            if args.gsheets:
                write_spreadsheet([
                    dt.now().strftime('%Y-%m-%d %H:%M'),
                    "{0:.2f}".format(fahr), "{0:.2f}".format(humidity)
                ])

    except KeyboardInterrupt:
        print "Quitting..."
        lcd.lcd_byte(0x01, lcd.LCD_CMD)
    finally:
        # clean up
        GPIO.cleanup()
Beispiel #21
0
def print_cluster_info():
    lcd.lcd_string('k3s OpenFaaS RPi', lcd.LCD_LINE_1)
    lcd.lcd_string('running! :-)', lcd.LCD_LINE_2)
line2 = "User String 2asdfasdf"
scrollDelay = 1  # 1 second per refresh

# Padding the strings
stringLength = max(len(line1), len(line2))
if (stringLength > 16):
    stringLength += 8  #add some additional spaces to either side

line1 = line1.center(stringLength)
line2 = line2.center(stringLength)

print("Press CTRL+c to quit")
try:
    lcd_i2c.lcd_init()
    i = 0
    while True:
        if (stringLength <= 16):
            lcd_i2c.lcd_string(line1, lcd_i2c.LCD_LINE_1)
            lcd_i2c.lcd_string(line2, lcd_i2c.LCD_LINE_2)
        else:
            lcd_i2c.lcd_string(line1[i:i + 16], lcd_i2c.LCD_LINE_1)
            lcd_i2c.lcd_string(line2[i:i + 16], lcd_i2c.LCD_LINE_2)
            if i + 16 >= stringLength:
                i = 0
            else:
                i += 1
        time.sleep(scrollDelay)
finally:
    print("Cleaning up...")
    lcd_i2c.lcd_byte(0x01, lcd_i2c.LCD_CMD)
Beispiel #23
0
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('IoT_Logger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                               maxBytes=5 * 1024 * 1024,
                                               backupCount=2)

my_logger.addHandler(handler)

sock = socket.socket()
sock.bind(('', 8888))
sock.listen(2)
lcd.lcd_init()
lcd.lcd_string("Ah, shit", LCD_LINE_1)
lcd.lcd_string("Here we go again", LCD_LINE_2)


class device(object):
    def __init__(self, number, temperature, humidity):
        self.t_range = [25.0, 25.0, 25.0, 25.0, 25.0]
        self.h_range = [28.0, 28.0, 28.0, 28.0, 28.0]
        self.number = number
        self.t_range[0] = temperature
        self.t_range[0] = humidity
        self.t_avg = sum(self.t_range) / len(self.t_range)
        self.h_avg = sum(self.h_range) / len(self.h_range)
        self.curr_indication = 1

    def update(self, temperature, humidity):
def drawMenu(menuList, infoRow2=""):
    # drawMenu proc
    global redrawFlag
    global curMenuItem
    global diplayRows
    global shiftCnt
    global shiftForward

    if redrawFlag:
        #  need redraw ?

        redrawFlag = False

        # length of menu list
        if subMenuFlag:
            tmpLen = len(menuList[curMenuItem[0]][1])  # lenght of submenu list
        else:
            tmpLen = len(menuList)  # lenght of main menu list

        if tmpLen > 0:
            # Slice display menu items

            if subMenuFlag:
                tmpList = menuList[curMenuItem[0]][1]
                tmpList = tmpList[curMenuItem[1]:curMenuItem[1] + diplayRows]
            else:
                tmpList = [x[0] for x in menuList][curMenuItem[1]:]
                tmpList = tmpList[:diplayRows]

            rowCnt = 0  # lcd display row counter

            # info mode, display mode command result
            if dispShowInfoState:

                LcdRow = '[' + shiftText(tmpList[0], 12) + ']'
                LcdRow = os.path.basename(LcdRow)
                LcdRow = LcdRow[0:13]
                LcdRow = LcdRow.ljust(13) + ' ' + str(curMenuItem[1])
                lcd_i2c.lcd_string(LcdRow, lcd_i2c.LCD_LINE_1)

                tmpInfoState = shiftText(infoStateStr, 15)

                lcd_i2c.lcd_string(tmpInfoState, lcd_i2c.LCD_LINE_2)
            else:
                # menu mode
                for ii in tmpList:

                    if subMenuFlag:
                        LcdRow = ii
                    else:
                        LcdRow = os.path.basename(ii)[2:]

                    if rowCnt % 2 == 0:
                        # even lines of the display (0,2,4...)
                        if curMenuItem[1] == curMenuItem[1] + rowCnt:
                            LcdRow = shiftText(LcdRow, 10)
                            LcdRow = '[' + LcdRow + ']'

                        LcdRow = LcdRow.ljust(13)

                        LcdRow = LcdRow + ' ' + str(tmpLen)
                        lcd_i2c.lcd_string(LcdRow, lcd_i2c.LCD_LINE_1)
                    else:
                        # odd lines of the display (0,2,4...)
                        LcdRow = LcdRow[0:12]
                        LcdRow = LcdRow.ljust(13)

                        LcdRow = LcdRow + ' ' + str(curMenuItem[1] + 1)
                        lcd_i2c.lcd_string(LcdRow, lcd_i2c.LCD_LINE_2)
                    rowCnt += 1

                # if the second line of the display is empty
                if rowCnt < 2:
                    lcd_i2c.lcd_string(
                        '              ' + str(curMenuItem[1] + 1),
                        lcd_i2c.LCD_LINE_2)
Beispiel #25
0
config.read('/etc/uecs/config.ini')

lcd.lcd_init()
prevsec = 0
itv = 0
ip = HOST

while (True):
    a = datetime.datetime.now()
    d = "{0:2d}{1:02d}{2:02d}".format(a.year - 2000, a.month, a.day)
    t = int("{0:2d}{1:02d}{2:02d}".format(a.hour, a.minute, a.second))
    s = "{0:6s} {1:6d}".format(d, t)
    if (prevsec > a.second):
        l = lcd.LCD_LINE_2
        u = "U:{0}".format(s)
        lcd.lcd_string(u, l)
        tn = "Time"
        send_UECSdata(tn,config[tn]['room'],config[tn]['region'],\
                      config[tn]['order'],config[tn]['priority'],t,HOST)
        tn = "Date"
        send_UECSdata(tn,config[tn]['room'],config[tn]['region'],\
                      config[tn]['order'],config[tn]['priority'],d,HOST)
    l = lcd.LCD_LINE_1
    lcd.lcd_string(s, l)
    if (a.second > 50):
        lcd.lcd_string(ip, lcd.LCD_LINE_2)
    elif (a.second > 40):
        msg = "UECS todtalker.."
        lcd.lcd_string(msg, lcd.LCD_LINE_2)
    elif (a.second > 30):
        lcd.lcd_string(ip, lcd.LCD_LINE_2)
Beispiel #26
0
def default_display():
    lcd_string(" Michelob Ultra ",LCD_LINE_1)
    #display beer percentage
    lcd_string("               ",LCD_LINE_2)
Beispiel #27
0
 # If we have the UID, continue
 if status == MIFAREReader.MI_OK:
     #convert uid to standard string representation
     str_uid = str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])
     #lcd_string(str_uid,LCD_LINE_2)
     #if user is already logged in, log them out 
     if str_uid == current_uid:
         logout()
         continue
     else:
         current_uid=str_uid
         # login to the database
         current_name = dbaccessor.getName(current_uid)
         current_balance = dbaccessor.getBalance(current_uid)
         #display name and balance on screen
         lcd_string(current_name,LCD_LINE_1)
         lcd_string(str(current_balance),LCD_LINE_2)
         login_counter = LOGIN_COUNTER_START
         safety_counter = SAFETY_COUNTER_START
 
 if current_balance > 0:
     VALVE_OUT_VALUE=True
     while GPIO.input(BUTTON_IN):
         GPIO.output(VALVE_OUT,VALVE_OUT_VALUE)
         if current_balance <=0:
             VALVE_OUT_VALUE = False
             GPIO.output(VALVE_OUT,VALVE_OUT_VALUE)
             break
         time.sleep(.5)
         current_balance -= DELTA_BALANCE
         lcd_string(str(current_balance),LCD_LINE_2)
Beispiel #28
0
import serial
import urllib.parse
import urllib.request
import lcd_i2c as lcd


url = 'http://agri-eye.bpes.kyushu-u.ac.jp/sss/api/insert_data.php'

try:
    s = serial.Serial('/dev/ttyUSB0',115200,timeout=1)
except serial.serialutil.SerialException:
    print("NO Serial ttyUSB0")
    quit()

s.readline()
lcd.lcd_string("ssdata A-OK",lcd.LCD_LINE_1)
while(True):
    a = s.readline().decode().rstrip()
    b = a.split(',')
    if (b[0]=='DT'):
        devid = 1
        gisval = {}
        gisval = {'T':'SSS','ID':devid,'CNT':b[1],'DWX':b[2],'DWY':b[3],'DWZ':b[4],'WX':b[5],'WY':b[6],'WZ':b[7]}
        params  = urllib.parse.urlencode(gisval)
        # print(params)
        urlreq = urllib.request.Request('{}?{}'.format(url,params))
        with urllib.request.urlopen(urlreq) as urlresponse:
            the_page = urlresponse.read()
            x = "SEND {0:>9}".format(b[1])
            lcd.lcd_string(x,lcd.LCD_LINE_1)
            time.sleep(1.0)
Beispiel #29
0
def print_pods_in_openfaas():
    ret = k_v1.list_namespaced_pod("openfaas-fn", watch=False)
    lcd.lcd_string('OpenFaaS pods:', lcd.LCD_LINE_1)
    lcd.lcd_string(str(len(ret.items)), lcd.LCD_LINE_2)
import lcd_i2c as lcd

lcd.lcd_init()
lcd.lcd_string('Good night!', lcd.LCD_LINE_1)
lcd.lcd_string('(-_-)zzz', lcd.LCD_LINE_2)

Beispiel #31
0
#! /usr/bin/env python3
#coding: utf-8
#
import sys
import lcd_i2c as lcd

s = sys.argv[1]
y = sys.argv[2]
x = sys.argv[3]

if (x=="i"):
    lcd.lcd_init()
if (y=="2"):
    l = lcd.LCD_LINE_2
else:
    l = lcd.LCD_LINE_1

lcd.lcd_string(s,l)
Beispiel #32
0
def print_ip():
    lcd.lcd_string('eth1:', lcd.LCD_LINE_1)
    try:
        lcd.lcd_string(get_ip_address('eth1'), lcd.LCD_LINE_2)
    except:
        lcd.lcd_string('Not connected', lcd.LCD_LINE_2)
Beispiel #33
0
            sleep(0.5)

    except KeyboardInterrupt:
        servo_motor.stop()
        GPIO.cleanup()


dev_id = 0
try:
    lcd.lcd_init()
    sock = bluez.hci_open_dev(dev_id)
    print "ble thread started"

except:
    print "error accessing bluetooth device..."
    sys.exit(1)

blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)

while True:
    returned_list = blescan.parse_events(sock, 5)
    len_returnedList = len(returned_list)

    if (len_returnedList > 0):
        servo_mortor_control()

    print "----------"
    lcd.lcd_string("", lcd.LCD_LINE_1)
    sleep(0.1)
Beispiel #34
0
 def printMessage(self, text, line=0):
     #        print(text)
     lcd_i2c.lcd_string(text, line_addr[line])
Beispiel #35
0
def servo_mortor_control():
    try:
        Distance = 0
        accuracy = 0
        sample_count = 0
        while True:
            returned_list = blescan.parse_events(sock, 5)

            if len(returned_list) == 0:
                sample_count = 0
                break

            for beacon in returned_list:
                if '74278bdab64445208f0c720eaf059935' in beacon:
                    sample_count = sample_count + 1
                    #GPIO.output(18, True)
                    rssi = int(beacon.split(",")[5])
                    txPower = float(beacon.split(",")[4])
                    rssi_feedback = -int(beacon.split(",")[3])
                    print "TxPower = ", txPower
                    print beacon
                    #Broadcasting beacon
                    #GPIO.output(16, True)
                    cid = '1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D2 AE 08 A9 61'
                    aid = 30  # -> '00 00'
                    uid = rssi  # -> '00 00'
                    power = -59  # -> 'CA'
                    #Initialize iBeacon
                    ib = iBeacon(cid, aid, uid, power)
                    #Start broadcasting
                    ib.startBeacon()

                    if sample_count == 1:
                        RSSI1 = rssi
                        print "RSSI1 = ", RSSI1
                        RSSI_FB1 = rssi_feedback
                        print RSSI_FB1
                    elif sample_count == 2:
                        RSSI2 = rssi
                        print "RSSI2 = ", RSSI2
                        RSSI_FB2 = rssi
                        print RSSI_FB2
                    elif sample_count == 3:
                        RSSI3 = rssi
                        print "RSSI3 = ", RSSI3
                        RSSI_FB3 = rssi
                        print RSSI_FB3
                    elif sample_count == 4:
                        RSSI4 = rssi
                        print "RSSI4 = ", RSSI4
                        RSSI_FB4 = rssi
                        print RSSI_FB4
                    elif sample_count == 5:
                        RSSI5 = rssi
                        print "RSSI5 = ", RSSI5
                        RSSI_FB5 = rssi
                        print RSSI_FB5
                    elif sample_count == 6:
                        RSSI6 = rssi
                        print "RSSI6 = ", RSSI6
                        RSSI_FB6 = rssi
                        print RSSI_FB6
                    elif sample_count == 7:
                        RSSI7 = rssi
                        print "RSSI7 = ", RSSI7
                        RSSI_FB7 = rssi
                        print RSSI_FB7
                    elif sample_count == 8:
                        RSSI8 = rssi
                        print "RSSI8 = ", RSSI8
                        RSSI_FB8 = rssi
                        print RSSI_FB8
                    elif sample_count == 9:
                        RSSI9 = rssi
                        print "RSSI9 = ", RSSI9
                        RSSI_FB9 = rssi
                        print RSSI_FB9
                    elif sample_count == 10:
                        RSSI10 = rssi
                        print "RSSI10 = ", RSSI10
                        RSSI_FB10 = rssi
                        print RSSI_FB10
                    elif sample_count == 11:
                        RSSI11 = rssi
                        print "RSSI11 = ", RSSI11
                        RSSI_FB11 = rssi
                        print RSSI_FB11
                    elif sample_count == 12:
                        RSSI12 = rssi
                        print "RSSI12 = ", RSSI12
                        RSSI_FB12 = rssi
                        print RSSI_FB12
                    elif sample_count == 13:
                        RSSI13 = rssi
                        print "RSSI13 = ", RSSI13
                        RSSI_FB13 = rssi
                        print RSSI_FB3
                    elif sample_count == 14:
                        RSSI14 = rssi
                        print "RSSI14 = ", RSSI14
                        RSSI_FB14 = rssi
                        print RSSI_FB14
                    elif sample_count == 15:
                        RSSI15 = rssi
                        print "RSSI15 = ", RSSI15
                        RSSI_FB15 = rssi
                        print RSSI_FB15
                    elif sample_count == 16:
                        RSSI16 = rssi
                        print "RSSI16 = ", RSSI16
                        RSSI_FB16 = rssi
                        print RSSI_FB16
                    elif sample_count == 17:
                        RSSI17 = rssi
                        print "RSSI17 = ", RSSI17
                        RSSI_FB17 = rssi
                        print RSSI_FB17
                    elif sample_count == 18:
                        RSSI18 = rssi
                        print "RSSI18 = ", RSSI18
                        RSSI_FB18 = rssi
                        print RSSI_FB18
                    elif sample_count == 19:
                        RSSI19 = rssi
                        print "RSSI19 = ", RSSI19
                        RSSI_FB19 = rssi
                        print RSSI_FB19
                    elif sample_count == 20:
                        RSSI20 = rssi
                        print "RSSI20 = ", RSSI20
                        RSSI_FB20 = rssi
                        print RSSI_FB20

                    if sample_count == 20:
                        RSSI_AVG = (RSSI1 + RSSI2 + RSSI3 + RSSI4 + RSSI5 +
                                    RSSI6 + RSSI7 + RSSI8 + RSSI9 + RSSI10 +
                                    RSSI11 + RSSI12 + RSSI13 + RSSI14 +
                                    RSSI15 + RSSI16 + RSSI17 + RSSI18 +
                                    RSSI19 + RSSI20) / 20.0
                        RSSI_FBAVG = (RSSI_FB1 + RSSI_FB2 + RSSI_FB3 +
                                      RSSI_FB4 + RSSI_FB5 + RSSI_FB6 +
                                      RSSI_FB7 + RSSI_FB8 + RSSI_FB9 +
                                      RSSI_FB10 + RSSI_FB11 + RSSI_FB12 +
                                      RSSI_FB13 + RSSI_FB14 + RSSI_FB15 +
                                      RSSI_FB16 + RSSI_FB17 + RSSI_FB18 +
                                      RSSI_FB19 + RSSI_FB20) / 20.0
                        print "-----BEFORE FILTERING-----"
                        print "Average = ", RSSI_AVG
                        print "FB Average = ", RSSI_FBAVG
                        ratio = float(RSSI_AVG) * 1.0 / (txPower)
                        print "Ratio = ", ratio
                        if (ratio < 1.0):
                            Distance = math.pow(ratio, 10)
                            print "distance = ", Distance
                        else:
                            accuracy = (0.89976) * math.pow(ratio,
                                                            7.7095) + 0.111
                            print "Accuracy = ", accuracy

                        #Kalman Filter
                        print "-----AFTER FILTERING-----"
                        # intial parameters
                        n_iter = 40
                        sz = (n_iter, )  # size of array
                        z = [
                            RSSI1, RSSI_FB1, RSSI2, RSSI_FB2, RSSI3, RSSI_FB3,
                            RSSI4, RSSI_FB4, RSSI5, RSSI_FB5, RSSI6, RSSI_FB6,
                            RSSI7, RSSI_FB7, RSSI8, RSSI_FB8, RSSI9, RSSI_FB9,
                            RSSI10, RSSI_FB10, RSSI11, RSSI_FB11, RSSI12,
                            RSSI_FB12, RSSI13, RSSI_FB13, RSSI14, RSSI_FB14,
                            RSSI15, RSSI_FB15, RSSI16, RSSI_FB16, RSSI17,
                            RSSI_FB17, RSSI18, RSSI_FB18, RSSI19, RSSI_FB19,
                            RSSI20, RSSI_FB20
                        ]  # observations (normal about x, sigma=0.1)
                        print z
                        Q = 1e-5  # process variance

                        # allocate space for arrays?
                        xhat = np.zeros(sz)  # a posteri estimate of x
                        P = np.zeros(sz)  # a posteri error estimate
                        xhatminus = np.zeros(sz)  # a priori estimate of x
                        Pminus = np.zeros(sz)  # a priori error estimate
                        K = np.zeros(sz)  # gain or blending factor

                        R = 0.1**2  # estimate of measurement variance, change to see effect

                        # intial guesses
                        xhat[0] = -28.0
                        P[0] = 5.0

                        for k in range(1, n_iter):
                            # time update
                            xhatminus[k] = xhat[k - 1]
                            Pminus[k] = P[k - 1] + Q

                            # measurement update
                            K[k] = Pminus[k] / (Pminus[k] + R)
                            xhat[k] = xhatminus[k] + K[k] * (z[k] -
                                                             xhatminus[k])
                            P[k] = (1 - K[k]) * Pminus[k]
                        #test_s

                        xhat_AVG = 0

                        for k in range(1, n_iter):
                            xhat_AVG += xhat[k]

                        xhat_AVG = xhat_AVG / 40.0
                        print xhat_AVG

                        ratio = float(xhat_AVG) * 1.0 / (txPower)

                        print ratio

                        Distance = 0
                        accuracy = 0

                        if (ratio < 1.0):
                            Distance = math.pow(ratio, 10)
                            print "predicted distance :", Distance
                        else:
                            accuracy = (0.89976) * math.pow(ratio,
                                                            7.7095) + 0.111
                            print "Accuracy = ", accuracy

                        #Broadcasting beacon
                        #GPIO.output(16, True)
                        cid = '1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D2 AE 08 A9 61'
                        aid = 30  # -> '00 00'
                        uid = int(RSSI_AVG)  # -> '00 00'
                        power = -59  # -> 'CA'
                        #Initialize iBeacon
                        ib = iBeacon(cid, aid, uid, power)
                        #Start broadcasting
                        ib.startBeacon()
            if sample_count == 20:
                break
        time.sleep(1)
        if (GPIO.input(button) == 0 and Distance <= 1.5 and accuracy <= 1.5):
            servo_motor.ChangeDutyCycle(left_angle)
            print("Button Pressed")
            print accuracy, Distance
            lcd.lcd_string("Door is open", lcd.LCD_LINE_1)
            GPIO.output(led, 1)
            sleep(5)
            servo_motor.ChangeDutyCycle(right_angle)
            print("Button Released")
            lcd.lcd_string("Door is closed", lcd.LCD_LINE_1)
            GPIO.output(led, 0)
            sleep(0.5)

    except KeyboardInterrupt:
        servo_motor.stop()
        GPIO.cleanup()
Beispiel #36
0
def main():

    #Bring in constants
    global DEVICE
    global SMBUSID
    global INTERVAL
    global THINGSPEAKKEY
    global THINGSPEAKURL
    global errors
    global I2C_ADDR
    global LCD_WIDTH
    global pwm_live

    #Setup
    errors = 0  #exception counter
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)  #Use BCM numbering for pins
    GPIO.setup(18, GPIO.OUT)  #GPIO 18 => Output
    bus = smbus.SMBus(SMBUSID)
    pwm = GPIO.PWM(18, 25000)  #GPIO 18 PWM @ 25kHz
    pwm.start(0)  #set duty cycle to 0
    lcd_i2c.lcd_init()

    while True:
        try:
            #pull data from BME
            lcd_i2c.lcd_string("      UPDATING      ",
                               LCD_LINE_1)  #display "updtn in top right
            (temperature, pressure, humidity) = bme280.readBME280All(DEVICE)
            temperatureF = temperature * (9) / (5) + 32
            chirp_moist = chirp.moist
            chirp_moistPercent = chirp.moist_percent
            chirp_temp = chirp.temp
            #send to thingspeak server
            sendData(THINGSPEAKURL, THINGSPEAKKEY, 'field1', 'field2',
                     'field3', 'field4', 'field5', 'field6', 'field7',
                     temperature, pressure, humidity, temperatureF,
                     chirp_moist, chirp_moistPercent, chirp_temp)
            sys.stdout.flush()

            # DO THINGS HERE while Waiting for next ThingsSpeak update
            for i in range(0, INTERVAL * 6):

                # Trigger the sensors and take measurements.
                chirp.trigger()
                chirp_moist = chirp.moist
                chirp_temp = chirp.temp
                chirp_moistPercent = chirp.moist_percent
                chirp_light = chirp.light
                output = '{:d} {:4.1f}% | {:3.1f}°F | {:d}'
                output = output.format(chirp_moist, chirp_moistPercent,
                                       chirp_temp, chirp_light)
                (temperature, pressure,
                 humidity) = bme280.readBME280All(DEVICE)
                temperatureF = temperature * (9) / (5) + 32
                print(output)

                #Fan  Speed Control Loop
                templog = "Temp = {:.2f} F".format(temperatureF) + " | "
                if temperatureF > 82:
                    pwm.ChangeDutyCycle(100)  # MAX fan speed
                    templog = templog + "PWM = 100"
                    pwm_live = 100
                    print templog
                elif temperatureF > 80:
                    pwm.ChangeDutyCycle(75)
                    templog = templog + "PWM = 75"
                    pwm_live = 75
                    print templog
                elif temperatureF > 76:
                    pwm.ChangeDutyCycle(30)
                    templog = templog + "PWM = 30"
                    pwm_live = 30
                    print templog
                elif temperatureF > 72:
                    pwm.ChangeDutyCycle(15)
                    templog = templog + "PWM = 15"
                    pwm_live = 15
                    print templog
                else:
                    pwm.ChangeDutyCycle(0)  # MIN fan speed
                    templog = templog + "PWM =0"
                    pwm_live = 0
                    print templog
                #Pirnt all data to LCD screen
                lcd_i2c.lcd_string("PWM  = {:.0f}  [{}]".format(
                    pwm_live, time.strftime("%H:%M")),
                                   LCD_LINE_1)  #update the time
                lcd_i2c.lcd_string(
                    "Soil = {:d}   | {:3.1f}%".format(chirp_moist,
                                                      chirp_moistPercent),
                    LCD_LINE_2)
                lcd_i2c.lcd_string(
                    "Temp = {:.2f} | {:.2f}".format(temperatureF, chirp_temp),
                    LCD_LINE_3)
                lcd_i2c.lcd_string(
                    "Hum  = {:.2f}%| {:d}".format(humidity, chirp_light),
                    LCD_LINE_4)
                time.sleep(10)
        #Error Handling
        except:
            errors += 1
            print "err cnt: {:d}  , delay 5s -> try again".format(errors)
            #lcd_i2c.lcd_string("   err = {:d}   ERROR".format(errors),LCD_LINE_1)   #display that an error occured
            time.sleep(5)
            continue
Beispiel #37
0
def check_win_condition(player):
    if(player.get_puzzle_count() >= config["puzzle_win_treshold"]):
        print "Removing player from database!"
        player.clear_uid()
        add_or_update_player(player)
        if(player.past_choice_count >= player.present_choice_count):
            lines = [
                ################
                ["Go to ",
                 "Kaleidoscope"],
                ["Coffeeshop ",
                 "when open"],
                ["and ask",
                 "barista:"],
                ["\"Do you feel the",
                 "mirrors today?\""]
            ]
            for line in lines:
                lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
                lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
                gevent.sleep(4)
        else:
            lines = [
                ################
                ["Go to 4:30 & B",
                 "and climb tower"]
            ]
            for line in lines:
                lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
                lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
                gevent.sleep(8)
            pass;
    else:
        if(player.get_puzzle_count() >= 0):
            lines = [
                ################
                ["Come back when",
                 "you have"],
                ["completed",
                 "more quests."]
            ]
            for line in lines:
                lcd_i2c.lcd_string(line[0], lcd_i2c.LCD_LINE_1)
                lcd_i2c.lcd_string(line[1], lcd_i2c.LCD_LINE_2)
                gevent.sleep(4)
            pass;