Exemplo n.º 1
0
    def __init__(self):
        self.deploy_button = Button(DEPLOY_BUTTON_PORT, self.deploy)
        self.select_repo_next_button = Button(
            REPO_BUTTON_NEXT_PORT,
            lambda on: self.select_change('repo next', on))
        self.select_repo_prev_button = Button(
            REPO_BUTTON_PREV_PORT,
            lambda on: self.select_change('repo prev', on))
        self.select_pr_next_button = Button(
            PR_BUTTON_NEXT_PORT, lambda on: self.select_change('pr next', on))
        self.select_pr_prev_button = Button(
            PR_BUTTON_PREV_PORT, lambda on: self.select_change('pr prev', on))
        self.lcd = LCD()
        self.button_matchers = [
            NetworkInfo(self.lcd, LOG_IN_MESSAGE),
            RestartApp(self.lcd)
        ]

        self.selected_repo_index = 0
        self.selected_pr_index = 0
        self.repo_list = []
        self.pull_requests = []

        self.rfid = RFID(self.startup)
        self.listen_for_rfid()
Exemplo n.º 2
0
def read():

    rfid = RFID()

    tag_id, tag_text = rfid.read_no_block()

    return {
        'id': str(tag_id),
        'text': tag_text.strip() if tag_text else tag_text
    }
Exemplo n.º 3
0
 def __init__(self, input):
     # input is JSON that comes with POST request
     self.request_data = input.get('data')
     self.set_timeout()
     # sets the rfid interface
     self.rfid = RFID(self.timeout)
     self.id = input.get('id', '1')
     if self.id is None:
         self.result_error("No id provided")
     else:
         self.request_scan()
Exemplo n.º 4
0
def write():

    status = False
    text = request.json.get('text')

    tag_id = None
    tag_text = None

    if text is not None:

        status = True

        rfid = RFID()
        tag_id, tag_text = rfid.write(text=text)

    return {
        'id': str(tag_id),
        'text': tag_text.strip() if tag_text else tag_text,
        'status': status
    }
Exemplo n.º 5
0
 def attachRFID(self):
     if self.replyLog is None:
         self.rfid = RFID()
         name = timeName("logs/src_rfid_", "log")
         if self.metaLog:
             self.metaLog.write("RFIDLOG:\t" + name + "\n")
             self.metaLog.flush()
         self.registerDataSource('rfid',
                                 SourceLogger(self.rfid.data, name).get)
     else:
         self.rfid = DummyGPS()  # just start
         if self.metaLog:
             rfidSrcLog = self.metaLogName("RFIDLOG:")
         else:
             rfidSrcLog = self.replyLog[:-18] + "src_rfid_" + self.replyLog[
                 -17:]
         print "RFIDLOG:", rfidSrcLog
         self.registerDataSource('rfid', SourceLogger(None, rfidSrcLog).get)
     self.rfidData = None
     self.rfidDataRaw = None
     self.addExtension(rfidDataExtension)
Exemplo n.º 6
0
class RFIDAdapter(Adapter):
    DEFAULT_TIMEOUT = 20
    VIRTUAL = True # flag to set when not using a real hardware backend
    VIRTUAL_UIDS = ["F6F8622E", "DEADBEEF", "12345678"]

    def __init__(self, input):
        Adapter.__init__(self, input)
        # sets the rfid interface
        if not self.VIRTUAL:
            self.set_timeout()
            self.rfid = RFID(self.timeout)

    def set_timeout(self):
        # try to get the timeout param
        if self.request_data:
            timeout = self.request_data.get("timeout")
            if timeout is not None:
                self.timeout = timeout
                return
        # otherwise set default
        self.timeout = self.DEFAULT_TIMEOUT

    def request_data(self):
        if not self.VIRTUAL:
            try:
                # runs the rfid scanner
                res = self.rfid.run_scanner()
                if res:
                    # means there was a scan
                    self.result_success({"uid": res})
                else:
                    self.result_error("Timeout")
            except:
                res = self.result_error('No scanner found')
        else:
            # if virtual, just return an arbitrary UID
            self.result_success({"uid": random.choice(self.VIRTUAL_UIDS)})
Exemplo n.º 7
0
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import time

from rfid import RFID expovariate

BROKER_URL = 'test.mosquitto.org'
CLIENT_ID = 'pi-mfrc522'
RC522_READ_TOPIC = '{}/read'.format(CLIENT_ID)


client = mqtt.Client(CLIENT_ID)
print('connected to: ', BROKER_URL)
client.connect(BROKER_URL, 80, 60)
client.loop_start()

rfid = RFID()


while True:
	tag_id = rfid.reader.read_id_no_block()
	print(tag_id)
	client.publish(RC522_READ_TOPIC, tag_id)
	time.sleep(3)
Exemplo n.º 8
0
class Coordinator:

    ########## Constructor ##########

    def __init__(self):
        self.ac_on = False

        self._init_logger()
        self._init_neopixel()
        self._init_ir()

        self._init_mqtt()
        self._init_lock()
        self._init_rfid()
        self._initialise_volume_control()
        self._initialise_ac()
        self._initialise_brightness_control()
        self._init_buttons()

        self._mqtt_client.send_message("boot", "started")
        self.strip.set_mode(Effects.RGB)

########## Logger ##########

    def _init_logger(self):
        self.formatter = logging.Formatter(
            fmt='%(asctime)s %(levelname)-8s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        self.handler = RotatingFileHandler(
            filename='/home/pi/app/coffee_table.log',
            mode='a',
            maxBytes=20 * 1024 * 1024,
            backupCount=2,
            encoding=None,
            delay=0)
        self.handler.setFormatter(self.formatter)
        self.logger = logging.getLogger("coffee_table")
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(self.handler)
        self.logger.debug("Starting coordinator Service")

########## Lock ##########

    def _init_lock(self):
        self.lock = OutputDevice(HAL.LOCK)
        self.lock.off()

    def open_lock(self, time_s):
        self.strip.pause()
        self.lock.on()
        threading.Timer(time_s, self.close_lock).start()

    def close_lock(self):
        self.lock.off()
        self.strip.unpause()

########## RFID Reader ##########

    def _init_rfid(self):
        self._reader = RFID(self.logger)
        self._reader.on_tag = lambda sender, tag: self._mqtt_client.send_message(
            "tags", tag)
        self._reader.start()

########## IR ##########

    def _init_ir(self):
        self.comms = Comms()
        self.device_state_tv = False
        self.device_state_amp = False
        self.remote = Remote(1, Config.REMOTE_AMP, self.logger, self.comms)

    def turn_on_devices(self):
        if not self.device_state_tv:
            self.remote.press_button(Key.TV_POWER, 1)
            self.device_state_tv = not self.device_state_tv
        if not self.device_state_amp:
            self.remote.press_button(Key.AMP_POWER, 1)
            self.device_state_amp = not self.device_state_amp

########## Room Lights ##########

    def _initialise_brightness_control(self):
        self.lights_held = False
        self.sine = Sine()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_are_on = True
        self.brightness = 0xFF
        self.rgb_long = 0x00FFFFFF
        self.brightness_control = RotaryEncoder(HAL.LIGHTS_A,
                                                HAL.LIGHTS_B,
                                                maximum=255,
                                                minimum=0,
                                                initial=255,
                                                step_size=5)
        self.brightness_control.on_clockwise = self.brightness_up
        self.brightness_control.on_counter_clockwise = self.brightness_down
        self._mqtt_client.on_rgb = self.on_rgb_message

        self.btn_lights = Button(HAL.LIGHTS_C, pull_up=True)
        self.btn_lights.hold_time = Config.BTN_HOLD_TIME
        self.btn_lights.when_held = self.enter_rgb_mode
        self.btn_lights.when_released = self.toggle_lights
        self.rgb_angle = 0

    def brightness_up(self):
        self.strip.set_temperature(self.brightness_control.percent())
        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_tx_timer.start()

    def brightness_down(self):
        self.strip.set_temperature(self.brightness_control.percent())
        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_tx_timer.start()

    def rgb_angle_changed(self):
        self.rgb_angle = self.brightness_control.value
        self.colour_picker = self.sine.get_triangle(self.rgb_angle *
                                                    Config.DEGREES_PER_CLICK)
        self.strip.pixels.fill(self.colour_picker)
        self.strip.pixels.show()

        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_rgb)
        self.lights_tx_timer.start()

        self.rgb_mode_timer.cancel()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.rgb_mode_timer.start()

    def lights_send_brightness(self):
        print("Updating Brightness")
        self._mqtt_client.send_message("lights/brightness",
                                       format(self.brightness_control.value))

    def lights_send_rgb(self):
        string = ",".join(str(x) for x in self.colour_picker)
        print("Updating RGB")
        self._mqtt_client.send_message("lights/rgb", string)

    def enter_rgb_mode(self):
        self.lights_held = True
        self.strip.set_mode(Effects.RGB)
        self.strip.blink(0, 0, 255)
        self.rgb_mode_timer.cancel()
        print("RGB Mode")
        self.strip.set_brightness(1)
        self.brightness_control.loop = True
        self.brightness_control.maximum = round(
            360 / Config.DEGREES_PER_CLICK) - 1
        self.brightness_control.step = 1
        self.brightness_control.value = self.rgb_angle
        self.brightness_control.on_clockwise = None
        self.brightness_control.on_counter_clockwise = None
        self.brightness_control.on_value_change = self.rgb_angle_changed
        self.rgb_mode_timer.cancel()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.rgb_mode_timer.start()

    def leave_rgb_mode(self):
        self.rgb_mode_timer.cancel()
        print("Normal Mode")
        self.brightness_control.loop = False
        self.brightness_control.maximum = 255
        self.brightness_control.step = 5
        self.brightness_control.value = 255
        self.brightness_control.on_clockwise = self.brightness_up
        self.brightness_control.on_counter_clockwise = self.brightness_down
        self.brightness_control.on_value_change = None
        self.rgb_mode_timer.cancel()
        self.strip.restore()

    def toggle_lights(self):
        if (self.lights_held):
            self.lights_held = False
            return
        self._mqtt_client.send_message("lights/brightness", "toggle")

    def on_rgb_message(self, r, g, b):
        self.strip.set_colour(r, g, b, transient=False, dim_after=5)

########## Neopixel ##########

    def _init_neopixel(self):
        self.strip = Indicator(HAL.WS2812B_DATA, 55)
        self.strip.set_mode(Effects.CYLON)
        self.effect = 1

    def cycle_effect(self):

        if self.effect == 0:
            self.strip.set_mode(Effects.RGB)

        if self.effect == 1:
            self.strip.set_mode(Effects.FIRE)

        if self.effect == 2:
            self.strip.set_mode(Effects.METEOR)

        if self.effect == 3:
            self.strip.set_mode(Effects.CYLON)

        if self.effect == 4:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(40, 0, 0, False)

        if self.effect == 5:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 40, 0, False)

        if self.effect == 6:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 0, 40, False)
            self.effect = -1

        self.effect += 1

########## Volume ##########

    def _initialise_volume_control(self):
        self.receiver = eiscp.eISCP('192.168.1.31')
        self.source = 1
        self.tv_mode = False
        self.volume_power_held = False

        self.button_amp_power = Button(HAL.VOL_C, pull_up=True)
        self.button_amp_power.hold_time = Config.BTN_HOLD_TIME
        self.button_amp_power.when_held = self.btn_volume_held
        self.button_amp_power.when_released = self.btn_volume_release

        self.volume_control = RotaryEncoder(HAL.VOL_A,
                                            HAL.VOL_B,
                                            maximum=60,
                                            minimum=0,
                                            initial=30,
                                            step_size=1)
        self.volume_control.on_clockwise = self.volume_up
        self.volume_control.on_counter_clockwise = self.volume_down
        self.btnvol_was_held = False

    def btn_volume_held(self):
        self.btnvol_was_held = True
        self.strip.blink(0, 0, 255)

    def btn_volume_release(self):
        if not self.btnvol_was_held:
            self._mqtt_client.send_message("amp", "short")
        else:
            self._mqtt_client.send_message("amp", "long")
        self.btnvol_was_held = False

    def switch_mode(self):
        self.tv_mode = not self.tv_mode

    def volume_up(self):
        self.strip.set_temperature(self.volume_control.percent())
        self.receiver.send('MVLUP')

    def volume_down(self):
        self.strip.set_temperature(self.volume_control.percent())
        self.receiver.send('MVLDOWN')

########## Aircon ##########

    def _initialise_ac(self):
        self.ac_power = Button(HAL.AC_C, pull_up=True)
        self.ac_control = RotaryEncoder(HAL.AC_A,
                                        HAL.AC_B,
                                        maximum=30,
                                        minimum=16,
                                        initial=24,
                                        step_size=1,
                                        can_zero=False)
        self.ac_control.on_value_change = self.set_ac
        self.ac_power.when_released = self.toggle_ac
        self.ac_timer = threading.Timer(Config.AIRCON_DELAY_TO_SEND,
                                        self.send_ac_temp)
        self._mqtt_client.on_ac_temp = self.update_temp

    def update_temp(self, temp):
        self.ac_control.value = int(temp)
        self.strip.set_temperature(self.ac_control.percent())

    def set_ac(self):
        self.strip.set_temperature(self.ac_control.percent())
        self.ac_timer.cancel()
        self.ac_timer = threading.Timer(Config.AIRCON_DELAY_TO_SEND,
                                        self.send_ac_temp)
        self.ac_timer.start()

    def send_ac_temp(self):
        self._mqtt_client.send_message("ac/set_temp",
                                       format(self.ac_control.value))

    def toggle_ac(self):
        self._mqtt_client.send_message("btnAC", "click")

########## Buttons ##########

    def _init_buttons(self):
        self.btn1 = Button(HAL.BTN1, pull_up=True)
        self.btn1.when_held = self.btn1_held
        self.btn1.when_released = self.btn1_release
        self.btn1_was_held = False
        self.btn2 = Button(HAL.BTN2, pull_up=True)
        self.btn2.when_held = self.btn2_held
        self.btn2.when_released = self.btn2_release
        self.btn2_was_held = False
        self.btn3 = Button(HAL.BTN3, pull_up=True)
        self.btn3.when_held = self.btn3_held
        self.btn3.when_released = self.btn3_release
        self.btn3_was_held = False
        self.btn4 = Button(HAL.BTN4, pull_up=True)
        self.btn4.when_held = self.btn4_held
        self.btn4.when_released = self.btn4_release
        self.btn4_was_held = False
        self.btn5 = Button(HAL.BTN5, pull_up=True)
        self.btn5.when_held = self.btn5_held
        self.btn5.when_released = self.btn5_release
        self.btn5_was_held = False
        self.btn6 = Button(HAL.BTN6, pull_up=True)
        self.btn6.when_held = self.btn6_held
        self.btn6.when_released = self.btn6_release
        self.btn6_was_held = False

    # LED Fun
    def btn1_held(self):
        self.btn1_was_held = True
        self._mqtt_client.send_message("btn1", "hold")
        self.strip.blink(0, 0, 255)

    def btn1_release(self):
        if not self.btn1_was_held:
            self._mqtt_client.send_message("btn1", "click")
            self.cycle_effect()
        self.btn1_was_held = False

    # Button 2
    def btn2_held(self):
        self.btn2_was_held = True
        self._mqtt_client.send_message("btn2", "hold")
        self.strip.blink(0, 0, 255)

    def btn2_release(self):
        if not self.btn2_was_held:
            self._mqtt_client.send_message("btn2", "click")
            print("Btn2 released")
        self.btn2_was_held = False

    def btn3_held(self):
        self.btn3_was_held = True
        self._mqtt_client.send_message("btn3", "hold")
        self.strip.blink(0, 0, 255)

    def btn3_release(self):
        if not self.btn3_was_held:
            self._mqtt_client.send_message("btn3", "click")
            print("Btn3 released")
        self.btn3_was_held = False

    def btn4_held(self):
        self.btn4_was_held = True
        self._mqtt_client.send_message("btn4", "hold")
        self.strip.blink(0, 0, 255)

    def btn4_release(self):
        if not self.btn4_was_held:
            self._mqtt_client.send_message("btn4", "click")
            print("Btn4 released")
        self.btn4_was_held = False

    #Play/Pause TV
    def btn5_held(self):
        self.btn5_was_held = True
        self._mqtt_client.send_message("btn5", "hold")
        self.strip.blink(0, 0, 255)

    def btn5_release(self):
        if not self.btn5_was_held:
            self._mqtt_client.send_message("btn5", "click")
            print("Btn5 released")
        self.btn5_was_held = False

    # PC On/Off
    def btn6_held(self):
        self.btn6_was_held = True
        self._mqtt_client.send_message("btn6", "hold")
        self.strip.blink(0, 0, 255)

    def btn6_release(self):
        if not self.btn6_was_held:
            self._mqtt_client.send_message("btn6", "click")
            print("Btn6 released")
        self.btn6_was_held = False

########## Command Handler ##########

    def handle_command(self, command):
        if command == "unlock":
            self.open_lock(Config.OPEN_LOCK_TIME)
        elif command == "lock":
            self.lock.off()
        elif command == "fire":
            self.strip.set_mode(Effects.FIRE)
        elif command == "cylon":
            self.strip.set_mode(Effects.CYLON)
        elif command == "stop_rgb":
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 10, 0, False)
        elif command == "devices_on":
            self.turn_on_devices()
        elif command == "source_cd":
            self.remote.press_button(Key.AMP_CD, 1)
            self.source = 2
        elif command == "source_video1":
            self.remote.press_button(Key.AMP_VIDEO1, 1)
            self.source = 3
        elif command == "source_video2":
            self.remote.press_button(Key.AMP_VIDEO2, 1)
            self.source = 4
        elif command == "source_aux":
            self.remote.press_button(Key.AMP_AUX, 1)
            self.source = 1
        elif command == "amp_power":
            self.remote.press_button(Key.AMP_POWER, 1)
        elif command == "tv_power":
            self.remote.press_button(Key.TV_POWER, 1)
        elif command == "pause":
            self.remote.press_button(Key.TV_PAUSE, 1)
        elif command == "play":
            self.remote.press_button(Key.TV_PLAY, 1)
        else:
            self.logger.debug("unrecognized command: " + command)

########## MQTT ##########

    def _init_mqtt(self):
        self._mqtt_client = MQTT(secrets.mqtt_broker, secrets.mqtt_port,
                                 secrets.mqtt_user, secrets.mqtt_pass,
                                 self.logger)
        self._mqtt_client.start()

        while self._mqtt_client.connected != True:
            time.sleep(0.1)

        self._mqtt_client.send_message("buttons", "Running")
        self._mqtt_client.send_message("lights/lounge", "update")
        self._mqtt_client.on_command = self.handle_command


########## Main ##########

    def run(self):
        try:
            pause()

        except KeyboardInterrupt:
            self._reader.stop()
            self._mqtt_client.stop()

            self.logger.info("App closing")
Exemplo n.º 9
0
        })
}

channels['main'].createZones([
    #{
    #    'delay': 500,
    #    'type': 'SUPPLY',
    #    'team': 0,
    #},
    #{
    #    'delay': 500,
    #    'type': 'CONTESTED',
    #},
])

totems = {'holster': RFID(channels['holster'].setTotemId)}


def onReconnected():
    for channel in channels:
        channels[channel].requestChannelUpdate()


def runCommandOnChannel(command, channel):
    type = command['type']

    if type == 'START_GAME':
        print("GAME START - COUNDOWN")
        channel.startGame(
            command['gameId'],
            command['countDownSec'],
Exemplo n.º 10
0
 def _init_rfid(self):
     self._reader = RFID(self.logger)
     self._reader.on_tag = lambda sender, tag: self._mqtt_client.send_message(
         "tags", tag)
     self._reader.start()
Exemplo n.º 11
0
class DeployModule(object):
    bob_api = None
    deployed = False
    logout_time = None

    def __init__(self):
        self.deploy_button = Button(DEPLOY_BUTTON_PORT, self.deploy)
        self.select_repo_next_button = Button(
            REPO_BUTTON_NEXT_PORT,
            lambda on: self.select_change('repo next', on))
        self.select_repo_prev_button = Button(
            REPO_BUTTON_PREV_PORT,
            lambda on: self.select_change('repo prev', on))
        self.select_pr_next_button = Button(
            PR_BUTTON_NEXT_PORT, lambda on: self.select_change('pr next', on))
        self.select_pr_prev_button = Button(
            PR_BUTTON_PREV_PORT, lambda on: self.select_change('pr prev', on))
        self.lcd = LCD()
        self.button_matchers = [
            NetworkInfo(self.lcd, LOG_IN_MESSAGE),
            RestartApp(self.lcd)
        ]

        self.selected_repo_index = 0
        self.selected_pr_index = 0
        self.repo_list = []
        self.pull_requests = []

        self.rfid = RFID(self.startup)
        self.listen_for_rfid()

    def listen_for_rfid(self):
        self.bob_api = None
        print(LOG_IN_MESSAGE)
        self.lcd.clear()
        self.lcd.write(LOG_IN_MESSAGE, 0)

    def startup(self, tag):
        print('Got tag ' + tag)
        [button_matcher.reset() for button_matcher in self.button_matchers]
        self.bob_api = BobApi(tag)
        self.refresh_repos(show_welcome=True)
        if self.repo_list:
            self.bump_logout_time()
        else:
            self.listen_for_rfid()

    def is_logged_in(self):
        return self.bob_api is not None

    def bump_logout_time(self):
        self.logout_time = datetime.now() + timedelta(
            minutes=LOGOUT_IN_MINUTES)

    def logout_time_expired(self):
        return self.logout_time < datetime.now()

    def logout(self):
        self.logout_time = None
        self.listen_for_rfid()

    def refresh_repos(self, show_welcome=False):
        self.lcd.clear()
        self.lcd.write('Loading...', 0)
        self.fetch_repos(show_welcome)
        self.update_repo()

    def fetch_repos(self, show_welcome):
        try:
            data = self.bob_api.get_repos_and_user_name()

            if data.get('user') and show_welcome:
                self.lcd.write('Welcome {name}!'.format(name=data.get('user')),
                               0)
                sleep(2)

            self.repo_list = data.get('repos')
            if self.repo_list and len(self.repo_list) is 0:
                self.repo_list = [
                    {
                        'display_name': '-- No repos found'
                    },
                ]
        except Exception:
            self.lcd.write('Repo loading err', 0)
            self.lcd.write('Please try again', 1)
            sleep(2)

    def fetch_pull_requests(self):
        self.pull_requests = self.bob_api.get_pull_requests(
            self.repo_list[self.selected_repo_index]['id'])
        self.selected_pr_index = 0

        if len(self.pull_requests) is 0:
            self.pull_requests = [
                {
                    'id': 0,
                    'title': '-- No PRs'
                },
            ]

    def update_repo(self):
        if self.repo_list:
            self.lcd.write(
                self.repo_list[self.selected_repo_index]['display_name'], 0)
            self.lcd.write('Loading...', 1)
            self.fetch_pull_requests()
            self.update_pr()

    def update_pr(self):
        self.lcd.write(self.pull_requests[self.selected_pr_index]['title'], 1)

    def handle_after_deploy_input(self):
        self.bump_logout_time()
        self.deployed = False
        self.refresh_repos()

    def deploy(self, pressed_down):
        if self.is_logged_in() and pressed_down:
            if self.deployed:
                self.handle_after_deploy_input()
            elif len(self.pull_requests
                     ) and not self.pull_requests[0]['id'] == 0:
                self.bump_logout_time()
                pr = self.pull_requests[self.selected_pr_index]
                print('Deploying ' + pr['title'])
                self.lcd.clear()
                self.lcd.write('Deploying...', 0)
                response = self.bob_api.deploy(
                    self.repo_list[self.selected_repo_index]['id'], pr['id'])
                self.lcd.write(response['message'], 1)
                self.deployed = True

    def create_select_change_handler(self, type):
        def handler(on):
            self.select_change(type, on)

        return handler

    def select_change(self, type, on):
        if on:
            if not self.is_logged_in():
                [
                    button_matcher.button_changed(type)
                    for button_matcher in self.button_matchers
                ]
            elif self.deployed:
                self.handle_after_deploy_input()
            else:
                self.bump_logout_time()
                if type == 'repo prev':
                    if self.selected_repo_index is 0:
                        self.selected_repo_index = len(self.repo_list) - 1
                    else:
                        self.selected_repo_index -= 1
                elif type == 'repo next':
                    if self.selected_repo_index is len(self.repo_list) - 1:
                        self.selected_repo_index = 0
                    else:
                        self.selected_repo_index += 1
                elif type == 'pr prev':
                    if self.selected_pr_index is 0:
                        self.selected_pr_index = len(self.pull_requests) - 1
                    else:
                        self.selected_pr_index -= 1
                elif type == 'pr next':
                    if self.selected_pr_index is len(self.pull_requests) - 1:
                        self.selected_pr_index = 0
                    else:
                        self.selected_pr_index += 1

                if 'repo' in type:
                    self.update_repo()
                elif 'pr' in type:
                    self.update_pr()

    def process(self):
        self.deploy_button.read_input()
        self.select_repo_next_button.read_input()
        self.select_repo_prev_button.read_input()
        self.select_pr_next_button.read_input()
        self.select_pr_prev_button.read_input()
        if (not self.is_logged_in()) and int(time() % 1 * 100) == 0:
            self.rfid.read()
        elif self.is_logged_in() and self.logout_time_expired():
            self.logout()

    def destroy(self):
        self.lcd.clear()
        self.lcd.write('Shutdown', 0)
        self.lcd.destroy()
Exemplo n.º 12
0
lcd = LCD()

led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT


def get_ip_address():
    ip_address = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip_address = s.getsockname()[0]
    s.close()
    return ip_address


rfid = RFID()

host_ip = get_ip_address()

while True:

    tag_id, tag_text = rfid.read_no_block()

    print(tag_id)

    lcd.clear()

    if tag_id is None:
        lcd.write(host_ip)
        led.value = False
    else:
Exemplo n.º 13
0
    def poll_loop(self):
        """
        Poll for presence of tag, read data, until stop() is called.
        """

        # initialize music mixer
        pygame.mixer.init()

        # set default volume
        util.set_volume(settings.DEFAULT_VOLUME)

        while not self.do_stop:
            with self.mutex:

                # initialize tag state
                self.uid[0] = None
                self.data[0] = None

                # always create a new RFID interface instance, to clear any errors from previous operations
                rdr = RFID()

                # check for presence of tag
                err, _ = rdr.request()

                if not err:
                    logger.debug("RFIDHandler poll_loop: Tag is present")

                    # tag is present, get UID
                    err, uid = rdr.anticoll()

                    if not err:
                        logger.debug(f"RFIDHandler poll_loop: Read UID: {uid}")

                        # read data
                        err, data = rdr.read(self.page)

                        if not err:
                            logger.debug(
                                f"RFIDHandler poll_loop: Read tag data: {data}"
                            )

                            # all good, store data to shared mem
                            for i in range(5):
                                self.uid[i] = uid[i]
                            for i in range(16):
                                self.data[i] = data[i]

                        else:
                            logger.debug(
                                "RFIDHandler poll_loop: Error returned from read()"
                            )

                    else:
                        logger.debug(
                            "RFIDHandler poll_loop: Error returned from anticoll()"
                        )

                # clean up
                rdr.cleanup()

                # act on data
                self.action()

            # wait a bit (this is in while loop, NOT in mutex env)
            time.sleep(self.sleep)
Exemplo n.º 14
0
class Adapter:
    DEFAULT_TIMEOUT = 20

    def __init__(self, input):
        # input is JSON that comes with POST request
        self.request_data = input.get('data')
        self.set_timeout()
        # sets the rfid interface
        self.rfid = RFID(self.timeout)
        self.id = input.get('id', '1')
        if self.id is None:
            self.result_error("No id provided")
        else:
            self.request_scan()
        

    def set_timeout(self):
        # try to get the timeout param
        if self.request_data:
            timeout = self.request_data.get("timeout")
            if timeout is not None:
                self.timeout = timeout
                return
        # otherwise set default
        self.timeout = self.DEFAULT_TIMEOUT

    def request_scan(self):
        try:
            # runs the rfid scanner
            res = self.rfid.run_scanner()
            if res:
                # means there was a scan
                self.result_success({"uid": res})
            else:
                self.result_timeout()
        except:
            res = self.result_error('No scanner found')

    """
    Status code key:
    200 --> successful scan, json response will have data
    300 --> timeout
    400 --> no id / POST request error
    """

    def result_success(self, data):
        self.result = {
            'jobRunID': self.id,
            'data': data,
            'status': 'success',
            'statusCode': 200,
        }

    def result_timeout(self):
        self.result = {
            'jobRunID': self.id,
            'status': 'timeout',
            'statusCode': 300,
        }

    def result_error(self, error):
        # self.result = {
        #     'jobRunID': self.id,
        #     'error': f'There was an error: {error}',
        #     'status': 'errored',
        #     'statusCode': 400,
        # }
        self.result = {
            'jobRunID': self.id,
            'data': {
                "uid": "F6F8B4F8"
            },
            'status': 'success',
            'statusCode': 200,
        }
Exemplo n.º 15
0
from rfid import RFID

NAME_BLOCK = 4
PRICE_BLOCK = 12
rdr = RFID()


# input a string return a list of number(ascii code)
def str_to_ascii(tar):
    ascii = []
    for t in tar:
        ascii.append(ord(t))
    ascii.append(3)
    return ascii


# input a list of number(ascii code) return a string
def ascii_to_str(tar):
    string = ''
    for t in tar:
        if t == 3:
            return string
        string = string + chr(t)


# input a string and write to rfid tag
def write_to_rfif(target, block):
    target = str_to_ascii(target)
    count = 0
    while len(target) > 0:
        if len(target) > 16:
Exemplo n.º 16
0
from rfid import RFID
from cartData import cartData
from buttons import Buttons
from player import Player
import rfidGlobals as g
import subprocess

g.init()

reader = RFID()
cartData = cartData()
b = Buttons(7, 11, 13, 15)
player = Player()

running = True  # If main program is running
regState = False  # If program is in registration state.
active = False  # If we are playing or not
ignition = False  # If we have loaded the playlist but haven't started play yet

playindID = []  # an array of strings for the UID
playlist = "0"  # playlist string from the database.csv

reader.start()

player.load("startup")
player.start()
while player.playing():
    pass
print("ready")

while running:
Exemplo n.º 17
0
 def __init__(self, input):
     Adapter.__init__(self, input)
     # sets the rfid interface
     if not self.VIRTUAL:
         self.set_timeout()
         self.rfid = RFID(self.timeout)
Exemplo n.º 18
0
    def write(self, data):
        """
        Write a 16-byte string of data to the tag
        """

        if len(data) != 16:
            logger.debug(f"Illegal data length, expected 16, got {len(data)}")
            return False

        with self.mutex:
            rdr = RFID()

            success = False

            # check for presence of tag
            err, _ = rdr.request()

            if not err:
                logger.debug("RFIDHandler write: Tag is present")

                # tag is present, get UID
                err, uid = rdr.anticoll()

                if not err:
                    logger.debug("RFIDHandler write: Read UID: " + str(uid))

                    # write data: RFID lib writes 16 bytes at a time, but for NTAG213
                    # only the first four are actually written
                    err = False
                    for i in range(4):
                        page = self.page + i
                        page_data = [ord(c)
                                     for c in data[4 * i:4 * i + 4]] + [0] * 12

                        # read data once (necessary for successful writing?)
                        err_read, _ = rdr.read(page)

                        if err:
                            logger.debug(
                                "Error signaled on reading page {:d} before writing"
                                .format(page))

                        # write data
                        err |= rdr.write(page, page_data)

                        if err:
                            logger.debug(
                                f'Error signaled on writing page {page:d} with data {page_data:s}'
                            )

                    if not err:
                        logger.debug(
                            "RFIDHandler write: successfully wrote tag data")

                        success = True

                    else:
                        logger.debug(
                            "RFIDHandler write: Error returned from write()")

                else:
                    logger.debug(
                        "RFIDHandler write: Error returned from anticoll()")

            # clean up
            rdr.cleanup()

            return success
Exemplo n.º 19
0
import tkinter as tk
from tkinter import font, simpledialog, messagebox, ttk
import threading
from multiprocessing import Process
import time
import socket
import json

import Adafruit_BBIO.GPIO as GPIO
from rfid import RFID

BUZZER = 'P8_10'
DEF_BLOCK = 12
NAME_BLOCK = 13
PRICE_BLOCK = 14
rdr = RFID()
state = 'READ'

window = tk.Tk()
tree = ttk.Treeview(window)
member_name = tk.Label(window, text='None', font=('Times', 14), bg='white')


def buzzer():
    GPIO.setup(BUZZER, GPIO.OUT)
    GPIO.output(BUZZER, GPIO.HIGH)
    time.sleep(0.3)
    GPIO.output(BUZZER, GPIO.LOW)

def read_product():
	global state