Exemplo n.º 1
0
def osmcprefs(whodat, key=None, value=None, *args):

    db = DBInterface()
    whodat = whodat.lower()

    if whodat.endswith('osmc_getprefs'):

        if key is None:
            return '\n'.join(_get_all_settings(db=db))

        else:
            return str(_get_setting(key, db=db))

    elif whodat.endswith('osmc_setprefs'):

        if key is None or value is None:
            return 'Error, no params provided\Example: osmc_setprefs key value'

        else:
            if value.lower() in ['true', 'false']:
                db.setsetting(key, bool(value), bool)
            else:
                try:
                    db.setsetting(key, int(value), int)
                except ValueError:
                    try:
                        db.setsetting(key, float(value), float)
                    except ValueError:
                        try:
                            db.setsetting(key, value)
                        except:  # pragma: no cover
                            return 'Failed to set value'

            return 'Set "%s" to "%s"' % (key, value)
Exemplo n.º 2
0
 def __init__(self, **kwargs):
     global_idmap.update({'kivysurvey': self})
     self.db_interface = DBInterface(self)
     super(KivySurvey, self).__init__(**kwargs)
     self.transition = SlideTransition()
     json = JsonStore(construct_target_file_name('survey.json', __file__))
     for each in json:
         print(each)
     self.survey = Survey(json)
     try:
         gps.configure(on_location=self.receive_gps)
     except:
         pass
     Clock.schedule_once(self.start_gps)
Exemplo n.º 3
0
 def __init__(self, folders_to_track, start_sync_at, pyfile, **kwargs):
     super(DriveMainThread, self).__init__(**kwargs)
     self.drive_data = DBInterface(
         os.path.dirname(os.path.abspath(pyfile)) + '/drive_data/',
         'drive_files')
     base_path = os.path.dirname(os.path.abspath(pyfile)) + '/'
     self.updated_folders = set()
     self.start_sync_at = start_sync_at
     self.folders_to_track = folders_to_track
     self.setup_drive()
     self.update_queue = Queue.Queue()
     self.get_tracked_folder_ids(
         folders_to_track,
         os.path.dirname(os.path.abspath(pyfile)) + '/')
     self.tracked_widgets = {}
     self.folders_to_track = [
         base_path + path + '/' for path in folders_to_track
     ]
Exemplo n.º 4
0
 def __init__(self, log_path, **kwargs):
     super(LogManager, self).__init__(**kwargs)
     self.log_path = log_path
     self.log_interface = log_interface = DBInterface(log_path,
                                                      'log',
                                                      do_date=True,
                                                      do_hour=True)
     touch_id = log_interface.get_entry('touches', 'last_touch_id', 'value')
     if touch_id is None:
         touch_id = 0
     self.touch_id = touch_id
Exemplo n.º 5
0
 def __init__(self, **kwargs):
     global_idmap.update({'kivysurvey': self})
     self.db_interface = DBInterface(self)
     super(KivySurvey, self).__init__(**kwargs)
     self.transition = SlideTransition()
     json = JsonStore(construct_target_file_name('survey.json', __file__))
     for each in json:
         print(each)
     self.survey = Survey(json)
     try:
         gps.configure(on_location=self.receive_gps)
     except:
         pass
     Clock.schedule_once(self.start_gps)
Exemplo n.º 6
0
 def __init__(self, folders_to_track, start_sync_at, pyfile, **kwargs):
     super(DriveMainThread, self).__init__(**kwargs)
     self.drive_data = DBInterface(os.path.dirname(
         os.path.abspath(pyfile))+'/drive_data/', 'drive_files')
     base_path = os.path.dirname(os.path.abspath(pyfile))+'/'
     self.updated_folders = set()
     self.start_sync_at = start_sync_at
     self.folders_to_track = folders_to_track
     self.setup_drive()
     self.update_queue = Queue.Queue()
     self.get_tracked_folder_ids( 
         folders_to_track, os.path.dirname(
         os.path.abspath(pyfile))+'/')
     self.tracked_widgets = {}
     self.folders_to_track = [
         base_path+path+'/' for path in folders_to_track]
Exemplo n.º 7
0
    def __init__(self, **kwargs):
        self.files_being_tracked = {}
        self.pyfile = pyfile = kwargs.get('pyfile', __file__)
        self.drive_data = DBInterface(
            os.path.dirname(os.path.abspath(pyfile)) + '/drive_data/',
            'drive_files')
        super(DriveCarousel, self).__init__(**kwargs)
        folders_to_track = kwargs.get('folders_to_track',
                                      self.folders_to_track)
        self.set_folders_to_track(folders_to_track)

        self.folder_observers = {}
        self.popup = popup = Popup()
        self.progress_tracker = progress_tracker = DriveProgressTracker()

        #Clock.schedule_interval(self.retrieve_all_changes, 30.)
        #Clock.schedule_interval(self.notify_folder_observers, 15.)
        self.schedule_change(0.)
        Clock.schedule_interval(self.update_carousel, 5.)
        Clock.schedule_interval(self.schedule_change, 30.)
Exemplo n.º 8
0
    def __init__(self, **kwargs):
        self.theme_manager = ThemeManager()
        self.setup_font_ramps()
        self.get_color = get_rgba_color
        self.get_icon = get_icon_char
        self.get_style = get_style
        self.get_ramp_group = get_font_ramp_group
        super(FlatApp, self).__init__(**kwargs)
        self.setup_themes()
        self.numpads = numpads = {}
        numpads['decimal'] = DecimalNumPad()
        numpads['regular'] = NumPad()
        if self.do_device_id:
            log_behavior = LogBehavior()
            self.log_manager = log_manager = log_behavior.log_manager
            self.settings_interface = settings_interface = DBInterface(
                construct_target_file_name('', __file__), 'settings')
            self.device_id = device_id = settings_interface.get_entry(
                'settings', 'device_id', 'value')

            self.bind(device_id=log_manager.setter('device_id'))
            if device_id is None:
                Clock.schedule_once(self.register_device_id)
Exemplo n.º 9
0
class KivySurvey(ScreenManager):
    current_page = ObjectProperty(None, allownone=True)
    current_subjects = ListProperty(None, allownone=True)
    db_interface = ObjectProperty(None)
    current_subjects = ListProperty(None, allownone=True)
    subject_id = NumericProperty(None, allownone=True)
    previous_subject_ids = ListProperty(None, allownone=True)
    current_page = ObjectProperty(None, allownone=True)
    current_subjects_page = ObjectProperty(None, allownone=True)
    next_page = StringProperty(None, allownone=True)
    prev_page = StringProperty(None, allownone=True)
    survey = ObjectProperty(None)
    current_location = DictProperty({})
    gps_loc_interval = NumericProperty(30.0)
    questionnaire = StringProperty(None, allownone=True)
    top_level_questionnaire = StringProperty(None, allownone=True)
    root = ObjectProperty(None)

    def __init__(self, **kwargs):
        global_idmap.update({'kivysurvey': self})
        self.db_interface = DBInterface(self)
        super(KivySurvey, self).__init__(**kwargs)
        self.transition = SlideTransition()
        json = JsonStore(construct_target_file_name('survey.json', __file__))
        for each in json:
            print(each)
        self.survey = Survey(json)
        try:
            gps.configure(on_location=self.receive_gps)
        except:
            pass
        Clock.schedule_once(self.start_gps)

    def on_subject_id(self, instance, value):
        self.load_subjects(value, self.questionnaire)

    def create_subject(self):
        db_interface = self.db_interface
        uid = db_interface.get_unique_id()
        prev_id = self.previous_subject_ids[-1]
        db_interface.add_subject(prev_id, self.questionnaire, uid)
        return uid

    def pop_subjects(self):
        previous_subject_ids = self.previous_subject_ids
        if len(previous_subject_ids) > 0:
            self.subject_id = self.previous_subject_ids.pop()
        else:
            self.subject_id = None

    def on_questionnaire(self, instance, value):
        self.load_subjects(self.subject_id, value)
        self.current_subjects_page.allow_add_subject = (
            self.survey.get_allow_add_subjects(value))

    def load_subjects(self, subject_id, questionnaire):
        self.current_subjects = self.db_interface.get_subjects(
            subject_id, questionnaire)

    def get_header_lines(self):
        return self.survey.get_header_definitions(self.questionnaire)

    def set_next_page(self):
        survey = self.survey
        next_page = survey.get_next_page(self.questionnaire,
                                         self.current_page.page)

        if next_page is None:
            return False
        else:
            self.next_page = None
            self.next_page = next_page
            return True

    def add_member(self):
        self.transition.direction = 'left'
        self.previous_subject_ids.append(self.subject_id)
        self.subject_id = None
        self.reset_questionnaire()

    def open_member(self, member_id, instance):
        self.transition.direction = 'left'
        self.previous_subject_ids.append(self.subject_id)
        self.subject_id = member_id
        self.reset_questionnaire()
        current_page = self.current_page.ids.questions
        current_page.load_page_data()

    def reset_questionnaire(self):
        self.current_page.page = None
        self.set_next_page()
        self.swap_pages()
        self.current_page.ids.questions.clear_questions()

    def set_prev_page(self):
        survey = self.survey
        prev_page = survey.get_prev_page(self.questionnaire,
                                         self.current_page.page)
        if prev_page is None:
            return False
        else:
            self.prev_page = prev_page
            return True

    def swap_subjects(self):
        subjects1 = self.ids.subjects1
        subjects2 = self.ids.subjects2
        current_subjects_page = self.current_subjects_page
        if current_subjects_page is subjects1:
            self.current = 'subjects2'
            self.current_subjects_page = subjects2
        elif current_subjects_page is subjects2:
            self.current = 'subjects1'
            self.current_subjects_page = subjects1
        self.current_subjects_page.allow_add_subject = (
            self.survey.get_allow_add_subjects(self.questionnaire))
        self.current_page.ids.scrollview.scroll_to_top()

    def swap_pages(self):

        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            self.current = 'questions2'
            self.current_page = questions2
            questions1.page = None
        elif current_page is questions2:
            self.current = 'questions1'
            self.current_page = questions1
            questions2.page = None
        self.current_page.ids.scrollview.scroll_to_top()

    def on_next_page(self, instance, value):
        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            questions2.page = value
        elif current_page is questions2:
            questions1.page = value

    def on_prev_page(self, instance, value):
        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            questions2.page = value
        elif current_page is questions2:
            questions1.page = value

    def start_questionnaire(self, questionnaire):
        self.current_page.page = None
        self.swap_subjects()
        self.questionnaire = questionnaire
        self.set_next_page()

    def save_page(self):
        current_page = self.current_page.ids.questions
        current_page.save_page_data()

    def go_back(self):
        does_page_exist = self.set_prev_page()
        survey = self.survey
        questionnaire = self.questionnaire
        prev_questionnaire = survey.get_previous_questionnaire()
        self.transition.direction = 'right'
        if self.current in ['subjects1', 'subjects2']:
            if prev_questionnaire is None:
                self.app.root.change_screen('cluster', go_back=True)
                return
            else:
                if survey.get_allow_add_subjects(questionnaire):
                    self.pop_subjects()
                self.start_questionnaire(survey.pop_previous_questionnaire())
        elif does_page_exist:
            self.swap_pages()
        else:
            if self.subject_id is None:
                self.pop_subjects()
                self.swap_subjects()
            else:
                self.pop_subjects()
                self.swap_subjects()

    def go_forward(self):
        does_page_exist = self.set_next_page()
        survey = self.survey
        questionnaire = self.questionnaire
        next_questionnaire = survey.get_next_questionnaire(questionnaire)
        self.transition.direction = 'left'
        if self.current in ['subjects1', 'subjects2']:
            if next_questionnaire is None:
                if survey.get_allow_add_subjects(questionnaire):
                    self.pop_subjects()
                prev_questionnaire = survey.pop_previous_questionnaire()
                self.start_questionnaire(prev_questionnaire)
            else:
                if survey.get_allow_forward(questionnaire):
                    survey.store_current_questionnaire(questionnaire)
                    self.start_questionnaire(next_questionnaire)
        elif does_page_exist:
            self.save_page()
            self.swap_pages()
        else:
            is_creating_subject = False
            if survey.get_allow_add_subjects(questionnaire) and (
                    self.subject_id is None):
                self.subject_id = self.create_subject()
            self.save_page()
            if next_questionnaire is None:
                self.pop_subjects()
                prev_questionnaire = survey.pop_previous_questionnaire()
                self.start_questionnaire(prev_questionnaire)
            elif survey.get_allow_add_subjects(next_questionnaire):
                survey.store_current_questionnaire(questionnaire)
                self.start_questionnaire(next_questionnaire)
            else:
                self.pop_subjects()
                self.swap_subjects()

    def start_gps(self, dt):
        try:
            gps.start()
        except:
            pass

    def receive_gps(self, **kwargs):
        if kwargs is not {}:
            self.current_location = kwargs
            gps.stop()
            Clock.schedule_once(self.start_gps, self.gps_loc_interval)

    def raise_error(self, error_title, error_text):
        self.app.raise_error(error_title, error_text)

    def raise_option_dialogue(self, option_title, option_text, options,
                              callback):
        self.app.raise_option_dialogue(option_title, option_text, options,
                                       callback)

    def raise_numpad(self,
                     numpad_title,
                     callback,
                     units=None,
                     minimum=None,
                     maximum=None,
                     do_decimal=False):
        self.app.raise_numpad(numpad_title, callback, units, minimum, maximum,
                              do_decimal)
Exemplo n.º 10
0
# -*- coding:utf-8 -*-

import re
import csv
import datetime
import jwt
from io import StringIO
from flask import Flask, jsonify, url_for, make_response, abort, request
from werkzeug.security import generate_password_hash, check_password_hash
from dbinterface import DBInterface
from utils import API_ROUTE, API_USERS_ROUTE, API_USERS_PORT, SECRET_KEY, token_required

api = Flask(__name__)
api.config['SECRET_KEY'] = SECRET_KEY

users = DBInterface('users', ['username', 'password', 'status', 'admin'])

# Funções auxiliares


def make_public_user(user):
    '''
	Altera a forma de exibição de um elemento do cadastro.
	Ao invés de mostrar o ID do elemento, mostra a URI do mesmo,
	  tornando assim mais fácil a requisição do mesmo via API.
	'''
    new_user = {}
    for field in user:
        if field == 'id':
            new_user['uri'] = url_for('get_user',
                                      user_id=user['id'],
Exemplo n.º 11
0
 def __init__(self, server_address, logger=None):
   # Member variables
   self.running = True
   self.server_address = server_address
   self.db = DBInterface()
   self.logger = logger or logging.getLogger(__name__)
Exemplo n.º 12
0
class NFCInterface:
  def __init__(self, logger=None):
    # Member variables
    self.running = False
    self.writing = False
    self.write_data = [0] # 16bytes
    self.nfc = Pn532_i2c()
    self.db = None
    self.logger = logger or logging.getLogger(__name__)

    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(12,GPIO.OUT, initial=0) # Red
    GPIO.setup(15,GPIO.OUT, initial=0) # Green
    # GPIO.cleanup()

    # Initiate the PN532 module

    self.logger.info('Initializing PN532 ...')
    # Send a FirmwareVersion command
    frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_GETFIRMWAREVERSION]))
    self.nfc.send_command_check_ack(frame)
    response = self.nfc.read_response()

    # Ensure the SAM (Security Access Module) is basically off
    self.nfc.SAMconfigure()

  def red(self, state):
    GPIO.output(12,state)

  def green(self, state):
    GPIO.output(15,state)

  def blink(self, id, number, initial=0):
    for x in range(0,number):
      GPIO.output(id, initial)
      sleep(0.2)
      GPIO.output(id, not initial)
      sleep(0.2)

  def start(self):
    self.logger.info('Starting NFCInterface ...')
    self.db = DBInterface(self.logger)
    self.running = True
    while (self.running):
      # Block waiting for a swipe
      uuid = self.get_uuid()

      # What we really want here is a callback interface, to abstract away the 
      # specifics of this particular project. For now, we make it work. 

      if (self.writing):
        # If we're in writing mode
        self.logger.info('In writing mode')
        success = 1

        # Populate the database with the UUID, if it's not already available,
        #  so at least this card is registered.
        card_id = self.db.register_card(uuid)
        if card_id is None:
          success = 0

        # Authenticate for reading/writing
        self.mifare_auth(uuid, 0x04)
        ids = [self.write_data[0], card_id, 0,0,
               0,0,0,0,  0,0,0,0,  0,0,0,0]
        self.mifare_write(0x04, ids)

        self.mifare_auth(uuid, 0x05)
        md5hash = self.write_data[2:]
        self.mifare_write(0x05, md5hash)

        #binprint.print_r_t(self.write_data, "Data to be written")

        # Need a check here to determine if the card has written correctly,
        # then we can trust the success check below.

        if (success):
          self.db.update_card(card_id, self.write_data[0])
          self.writing = False
          self.logger.info('Success beep.')
          self.red(0)
          self.blink(15,3,0)

        else:
          self.logger.info("Failure beep.")
          self.green(0)
          self.blink(12,3,0)
  
      else:
        # If we're not in writing mode, we're in default reading mode
        self.mifare_auth(uuid, 0x04)
        response_A = self.mifare_read(0x04)

        self.mifare_auth(uuid, 0x04)
        response_B = self.mifare_read(0x05)

        user_id = self.db.check_hash(uuid, response_A, response_B)
        if (user_id):
          logged_in = self.db.toggle_status(user_id) # 1 in, 0 out
          if (logged_in):
            self.logger.info("Success in beep.")
            self.green(1)
          else:
            self.logger.info("Success out beep.")
            self.blink(15,2,1)
        else:
          self.logger.info("Failure beep.")
          self.red(1)

      sleep(0.5)
      self.logger.info("LED reset")
      self.green(0)
      self.red(0)

      # Delay the loop reset for a bit of time
      # to prevent someone from leaning on the
      # login/logout button.
      sleep(3)

  def stop(self):
    self.logger.info('Stopping NFCInterface ...')
    self.running = False
    self.nfc.stop()

  def set_writing(self, write_data):
    self.logger.info('Received data to write')
    self.red(1)
    self.green(1)
    #binprint.print_r_t(write_data, "Received: ")
    self.writing = True
    self.write_data = write_data

  def get_uuid(self):
    uuid_frame = self.nfc.read_mifare()
    if uuid_frame is None:
      return
    else:
      return uuid_frame.get_data()[-4:]

  def mifare_auth(self, uuid, block):
    if uuid is None:
      return
    # Apparently, before we can do anything at all, we must authenticate against the block.
    # Arduino calls MifareAuthenticate, which wraps the command PN532_COMMAND_INDATAEXCHANGE
    # (0x40) issued to pn532 with payload MIFARE_CMD_AUTH_A (0x60) on block.
    auth_data =  bytearray([0x40,0x01,0x60,block]) # PN532 + MiFare command
    auth_data += bytearray([0xff,0xff,0xff,0xff,0xff,0xff]) # default auth KeyA
    auth_data += uuid
    frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=auth_data)
    self.nfc.send_command_check_ack(frame)

  def mifare_read(self, block):
    # Let's try and read a particular block, shall we?
    # So, the Arduino code uses MifareReadBlock, which is a wrapper around the command
    # PN532_COMMAND_INDATAEXCHANGE (0x40) issued to the pn532 controller logical relevant
    # target 0x01, with the payload of MIFARE_CMD_READ (0x30) on block.
    # Build the frame
    frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([0x40,0x01,0x30,block]))
    # Issue the command
    self.nfc.send_command_check_ack(frame)
    response = self.nfc.read_response()
    return response.get_data()

  def mifare_write(self, block, data):
    # Write write write! What a risk.
    # Arduino uses MifareWriteBlock; a wrapper around PN532_COMMAND_INDATAEXCHANGE (0x40)
    # issued to pn532, logical relevant target 0x01, with a payload of MIFARE_CMD_WRITE
    # (0xA0) on block.
    # Then you've got 16 bytes you can fill with stuff and/or things.
    write_data =  bytearray([0x40,0x01,0xA0,block])
    write_data += bytearray(data)
    frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=write_data)
    self.nfc.send_command_check_ack(frame)
# -*- coding:utf-8 -*-

import re
import csv
from io import StringIO
from flask import Flask, jsonify, url_for, make_response, abort, request
from werkzeug.utils import secure_filename
from dbinterface import DBInterface
from utils import API_MEDICINES_ROUTE, API_MEDICINES_PORT, token_required

api = Flask(__name__)

medicines = DBInterface(
    'medicines', ['name', 'type', 'dosage', 'price', 'manufacturer', 'sales'])

# Funções auxiliares


def make_public_medicine(medicine):
    '''
	Altera a forma de exibição de um elemento do cadastro.
	Ao invés de mostrar o ID do elemento, mostra a URI do mesmo,
	  tornando assim mais fácil a requisição do mesmo via API.
	'''
    new_medicine = {}
    for field in medicine:
        if field == 'id':
            new_medicine['uri'] = url_for('get_medicine',
                                          medicine_id=medicine['id'],
                                          _external=True)
Exemplo n.º 14
0
class DriveMainThread(Thread):
    def __init__(self, folders_to_track, start_sync_at, pyfile, **kwargs):
        super(DriveMainThread, self).__init__(**kwargs)
        self.drive_data = DBInterface(
            os.path.dirname(os.path.abspath(pyfile)) + '/drive_data/',
            'drive_files')
        base_path = os.path.dirname(os.path.abspath(pyfile)) + '/'
        self.updated_folders = set()
        self.start_sync_at = start_sync_at
        self.folders_to_track = folders_to_track
        self.setup_drive()
        self.update_queue = Queue.Queue()
        self.get_tracked_folder_ids(
            folders_to_track,
            os.path.dirname(os.path.abspath(pyfile)) + '/')
        self.tracked_widgets = {}
        self.folders_to_track = [
            base_path + path + '/' for path in folders_to_track
        ]

    def add_drive_widget(self, widget, folder_to_track):
        assert (folder_to_track in self.folders_to_track)
        tracked_widgets = self.tracked_widgets
        if folder_to_track not in tracked_widgets:
            tracked_widgets[folder_to_track] = [widget]
        else:
            tracked_widgets[folder_to_track].append(widget)

    def setup_drive(self):
        credentials = storage.get()
        self.queue = queue = Queue.Queue()
        if credentials is None:
            flow = OAuth2WebServerFlow(CLIENT_ID,
                                       CLIENT_SECRET,
                                       OAUTH_SCOPE,
                                       redirect_uri=REDIRECT_URI)
            authorize_url = flow.step1_get_authorize_url()
            print 'Go to the following link in your browser: ' + authorize_url
            code = raw_input('Enter verification code: ').strip()
            credentials = flow.step2_exchange(code)
            storage.put(credentials)
        http = httplib2.Http()
        http = credentials.authorize(http)
        self.drive_service = drive_service = build('drive', 'v2', http=http)
        self.thread_pool = thread_pool = DriveThreadPool(1, queue, credentials)

    def get_tracked_folder_ids(self, folders_to_track, address):
        drive_data = self.drive_data
        for folder_name in self.folders_to_track:
            q = "title = '{}'".format(folder_name)
            data = self.drive_service.children().list(folderId='root',
                                                      q=q).execute()
            folder_add = address + folder_name + '/'
            self.ensure_dir(folder_add)
            #self.add_folder_observer(self.get_callback, unicode(folder_add))
            for dat in data[u'items']:
                item_id = dat[u'id']
                drive_data.set_entry('folders', item_id, 'file_add',
                                     folder_add)
                drive_data.set_entry('tracked_items', item_id, 'file_add',
                                     folder_add)

    def check_file_in_tracked_folders(self, file_data):
        parents = file_data[u'parents']
        folders = self.drive_data.get_table('folders')

        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                return True
        return False

    def run(self):
        while True:
            query_download = self.update_queue.get()
            if query_download:
                self.retrieve_all_changes()
                self.update_queue.task_done()

    def download_folder(self, file_id, file_data):
        parents = file_data[u'parents']
        drive_data = self.drive_data
        #save_data = self.save_data
        folders = drive_data.get_table('folders')
        get_entry = drive_data.get_entry
        append_entry = drive_data.append_entry
        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                address = get_entry('folders', parent_id, 'file_add')
                folder_name = file_data[u'title']
                folder_add = address + folder_name + '/'
                self.ensure_dir(folder_add)
                append_entry('folders', file_id, 'file_add', folder_add)
                append_entry('tracked_items', file_id, 'file_add', folder_add)

    def place_address_in_queue(self, address, file_name, file_id,
                               time_since_epoch, download_url):
        drive_data = self.drive_data
        self.ensure_dir(address)
        file_add = address + file_name
        drive_data.append_entry('tracked_items', file_id, 'file_add', file_add)
        do_download = False
        try:
            mod_time = os.stat(file_add).st_mtime
            if time_since_epoch > mod_time:
                do_download = True
            else:
                do_download = False
        except:
            do_download = True
        if do_download:
            self.queue.put(
                (self._download, [download_url, file_add,
                                  time_since_epoch], {}))

    def download_file(self, file_id, file_data):
        mod_date = file_data[u'modifiedDate']
        parents = file_data[u'parents']
        time_since_epoch = self.calculate_time_since_epoch(mod_date)
        drive_data = self.drive_data
        folders = drive_data.get_table('folders')
        get_entry = drive_data.get_entry
        download_url = file_data[u'downloadUrl']
        file_name = file_data[u'title']
        place_address_in_queue = self.place_address_in_queue
        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                address = get_entry('folders', parent_id, 'file_add')
                if isinstance(address, list):
                    for add in address:
                        place_address_in_queue(add, file_name, file_id,
                                               time_since_epoch, download_url)
                else:
                    place_address_in_queue(address, file_name, file_id,
                                           time_since_epoch, download_url)

    def retrieve_all_changes(self):
        result = []
        page_token = None
        drive_data = self.drive_data
        largest_change = int(self.get_largest_change_id())
        try:
            start_change_id = str(
                int(drive_data.get_entry('changes', 'last_change', 'id')) + 1)
        except:
            start_change_id = str(int(self.start_sync_at))
        # if self.progress_tracker.start_change_id is None:
        #     self.progress_tracker.start_change_id = int(start_change_id)
        # self.progress_tracker.last_change_id = int(start_change_id)
        if largest_change >= int(start_change_id):
            print('we should parse')
            # Clock.schedule_once(partial(self.retrieve_page_of_changes, None,
            #     start_change_id))
            while True:
                param = {}
                print('grabbing changes')
                if start_change_id is not None:
                    param['startChangeId'] = start_change_id
                if page_token is not None:
                    param['pageToken'] = page_token
                changes = self.drive_service.changes().list(**param).execute()
                self.parse_changes(changes)
                #self.sync()
                page_token = changes.get('nextPageToken')
                if not page_token:
                    print('done breaking')
                    break

    def parse_changes(self, changes):
        drive_data = self.drive_data
        download_folder = self.download_folder
        download_file = self.download_file
        remove_file = self.remove_file
        tracked_items = drive_data.get_table('tracked_items')
        check_file_in_tracked_folders = self.check_file_in_tracked_folders
        get_is_folder = self.get_is_folder
        set_entry = drive_data.set_entry
        get_file = self.get_file
        if len(changes['items']) == 0:
            return None
        for change in changes['items']:
            file_id = change[u'fileId']
            change_id = change[u'id']
            file_data = get_file(file_id)
            is_deleted = change[u'deleted']
            if is_deleted and file_id in tracked_items:
                self.handle_remove_callback(file_id)
                remove_file(file_id)
            if file_data != None:
                if check_file_in_tracked_folders(file_data):
                    if get_is_folder(file_data):
                        download_folder(file_id, file_data)
                    else:
                        download_file(file_id, file_data)
            set_entry('changes', 'last_change', 'id', change_id)
        return change_id

    def handle_remove_callback(self, file_id):
        file_adds = self.drive_data.get_entry('tracked_items', file_id,
                                              'file_add')
        tracked_widgets = self.tracked_widgets
        if file_adds is not None:
            if isinstance(file_adds, list):
                for file_add in file_adds:
                    widgets_for_removal = []
                    widgets_a = widgets_for_removal.append
                    dir_name = str(dirname(file_add) + '/')
                    for wid in tracked_widgets[dir_name]:
                        r_wid = wid()
                        if r_wid is not None:
                            file_callback = r_wid.file_callback
                            Clock.schedule_once(
                                partial(file_callback, file_add, True))
                        else:
                            widgets_a(wid)
                    for wid_ref in widgets_for_removal:
                        tracked_widgets[file_adds].remove(wid_ref)

    def remove_file(self, file_id):
        drive_data = self.drive_data
        to_remove = []
        to_remove_a = to_remove.append
        remove_entry = drive_data.remove_entry
        file_adds = drive_data.get_entry('tracked_items', file_id, 'file_add')
        if file_adds is not None:
            for file_add in file_adds:
                try:
                    os.remove(file_add)
                    to_remove_a(file_add)
                except:
                    continue
            for add in to_remove:
                remove_entry('tracked_items', file_id, 'file_add', add)

    def ensure_dir(self, f):
        d = os.path.dirname(f)
        if not os.path.exists(d):
            os.makedirs(d)

    def calculate_time_since_epoch(self, drive_time):
        date, current_time = drive_time.split('T')
        year, month, day = date.split('-')
        hours, minutes, seconds = current_time.split(':')
        seconds = seconds.split('.')[0]
        py_date = datetime.datetime(int(year),
                                    int(month),
                                    int(day),
                                    hour=int(hours),
                                    minute=int(minutes),
                                    second=int(seconds))
        return time.mktime(py_date.timetuple())

    def get_is_folder(self, file_data):
        return file_data[u'mimeType'] == u'application/vnd.google-apps.folder'

    def get_file(self, fid):
        try:
            return self.drive_service.files().get(fileId=fid).execute()
        except:
            return None

    def list_folder_content(self, fid):
        return self.drive_service.children().list(folderId=fid).execute()

    def get_about_data(self):
        return self.drive_service.about().get().execute()

    def get_largest_change_id(self):
        return self.get_about_data()[u'largestChangeId']

    def get_content_title(self, fid):
        return self.drive_service.files().get(fileId=fid).execute()[u'title']

    def _download(self, queue, drive_service, download_url, name, time):
        if download_url:
            try:
                resp, content = drive_service._http.request(download_url)
            except:
                print 'An error occurred: '
                return
            if resp.status == 200:
                with open(name, 'w') as save_file:
                    save_file.write(content)
                os.utime(name, (os.stat(name).st_atime, time))
                folder_name = os.path.dirname(name) + '/'
                tracked_widgets = self.tracked_widgets
                widgets_for_removal = []
                widget_a = widgets_for_removal.append
                if folder_name in tracked_widgets:
                    for wid in tracked_widgets[folder_name]:
                        r_wid = wid()
                        if r_wid is not None:
                            Clock.schedule_once(
                                partial(r_wid.file_callback, name, False), 15.)
                        else:
                            widget_a(wid)
                    for wid_ref in widgets_for_removal:
                        tracked_widgets[folder_name].remove(wid_ref)
                queue.task_done()
            else:
                print 'An error occurred: %s' % resp
Exemplo n.º 15
0
  def start(self):
    self.logger.info('Starting NFCInterface ...')
    self.db = DBInterface(self.logger)
    self.running = True
    while (self.running):
      # Block waiting for a swipe
      uuid = self.get_uuid()

      # What we really want here is a callback interface, to abstract away the 
      # specifics of this particular project. For now, we make it work. 

      if (self.writing):
        # If we're in writing mode
        self.logger.info('In writing mode')
        success = 1

        # Populate the database with the UUID, if it's not already available,
        #  so at least this card is registered.
        card_id = self.db.register_card(uuid)
        if card_id is None:
          success = 0

        # Authenticate for reading/writing
        self.mifare_auth(uuid, 0x04)
        ids = [self.write_data[0], card_id, 0,0,
               0,0,0,0,  0,0,0,0,  0,0,0,0]
        self.mifare_write(0x04, ids)

        self.mifare_auth(uuid, 0x05)
        md5hash = self.write_data[2:]
        self.mifare_write(0x05, md5hash)

        #binprint.print_r_t(self.write_data, "Data to be written")

        # Need a check here to determine if the card has written correctly,
        # then we can trust the success check below.

        if (success):
          self.db.update_card(card_id, self.write_data[0])
          self.writing = False
          self.logger.info('Success beep.')
          self.red(0)
          self.blink(15,3,0)

        else:
          self.logger.info("Failure beep.")
          self.green(0)
          self.blink(12,3,0)
  
      else:
        # If we're not in writing mode, we're in default reading mode
        self.mifare_auth(uuid, 0x04)
        response_A = self.mifare_read(0x04)

        self.mifare_auth(uuid, 0x04)
        response_B = self.mifare_read(0x05)

        user_id = self.db.check_hash(uuid, response_A, response_B)
        if (user_id):
          logged_in = self.db.toggle_status(user_id) # 1 in, 0 out
          if (logged_in):
            self.logger.info("Success in beep.")
            self.green(1)
          else:
            self.logger.info("Success out beep.")
            self.blink(15,2,1)
        else:
          self.logger.info("Failure beep.")
          self.red(1)

      sleep(0.5)
      self.logger.info("LED reset")
      self.green(0)
      self.red(0)

      # Delay the loop reset for a bit of time
      # to prevent someone from leaning on the
      # login/logout button.
      sleep(3)
Exemplo n.º 16
0
class NFCInterface:
    def __init__(self, logger=None):
        # Member variables
        self.running = False
        self.writing = False
        self.write_data = [0]  # 16bytes
        self.nfc = Pn532_i2c()
        self.db = None
        self.logger = logger or logging.getLogger(__name__)

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(12, GPIO.OUT, initial=0)  # Red
        GPIO.setup(15, GPIO.OUT, initial=0)  # Green
        # GPIO.cleanup()

        # Initiate the PN532 module

        self.logger.info('Initializing PN532 ...')
        # Send a FirmwareVersion command
        frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA,
                           data=bytearray([PN532_COMMAND_GETFIRMWAREVERSION]))
        self.nfc.send_command_check_ack(frame)
        response = self.nfc.read_response()

        # Ensure the SAM (Security Access Module) is basically off
        self.nfc.SAMconfigure()

    def red(self, state):
        GPIO.output(12, state)

    def green(self, state):
        GPIO.output(15, state)

    def blink(self, id, number, initial=0):
        for x in range(0, number):
            GPIO.output(id, initial)
            sleep(0.2)
            GPIO.output(id, not initial)
            sleep(0.2)

    def start(self):
        self.logger.info('Starting NFCInterface ...')
        self.db = DBInterface(self.logger)
        self.running = True
        while (self.running):
            # Block waiting for a swipe
            uuid = self.get_uuid()

            # What we really want here is a callback interface, to abstract away the
            # specifics of this particular project. For now, we make it work.

            if (self.writing):
                # If we're in writing mode
                self.logger.info('In writing mode')
                success = 1

                # Populate the database with the UUID, if it's not already available,
                #  so at least this card is registered.
                card_id = self.db.register_card(uuid)
                if card_id is None:
                    success = 0

                # Authenticate for reading/writing
                self.mifare_auth(uuid, 0x04)
                ids = [
                    self.write_data[0], card_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0
                ]
                self.mifare_write(0x04, ids)

                self.mifare_auth(uuid, 0x05)
                md5hash = self.write_data[2:]
                self.mifare_write(0x05, md5hash)

                #binprint.print_r_t(self.write_data, "Data to be written")

                # Need a check here to determine if the card has written correctly,
                # then we can trust the success check below.

                if (success):
                    self.db.update_card(card_id, self.write_data[0])
                    self.writing = False
                    self.logger.info('Success beep.')
                    self.red(0)
                    self.blink(15, 3, 0)

                else:
                    self.logger.info("Failure beep.")
                    self.green(0)
                    self.blink(12, 3, 0)

            else:
                # If we're not in writing mode, we're in default reading mode
                self.mifare_auth(uuid, 0x04)
                response_A = self.mifare_read(0x04)

                self.mifare_auth(uuid, 0x04)
                response_B = self.mifare_read(0x05)

                user_id = self.db.check_hash(uuid, response_A, response_B)
                if (user_id):
                    logged_in = self.db.toggle_status(user_id)  # 1 in, 0 out
                    if (logged_in):
                        self.logger.info("Success in beep.")
                        self.green(1)
                    else:
                        self.logger.info("Success out beep.")
                        self.blink(15, 2, 1)
                else:
                    self.logger.info("Failure beep.")
                    self.red(1)

            sleep(0.5)
            self.logger.info("LED reset")
            self.green(0)
            self.red(0)

            # Delay the loop reset for a bit of time
            # to prevent someone from leaning on the
            # login/logout button.
            sleep(3)

    def stop(self):
        self.logger.info('Stopping NFCInterface ...')
        self.running = False
        self.nfc.stop()

    def set_writing(self, write_data):
        self.logger.info('Received data to write')
        self.red(1)
        self.green(1)
        #binprint.print_r_t(write_data, "Received: ")
        self.writing = True
        self.write_data = write_data

    def get_uuid(self):
        uuid_frame = self.nfc.read_mifare()
        if uuid_frame is None:
            return
        else:
            return uuid_frame.get_data()[-4:]

    def mifare_auth(self, uuid, block):
        if uuid is None:
            return
        # Apparently, before we can do anything at all, we must authenticate against the block.
        # Arduino calls MifareAuthenticate, which wraps the command PN532_COMMAND_INDATAEXCHANGE
        # (0x40) issued to pn532 with payload MIFARE_CMD_AUTH_A (0x60) on block.
        auth_data = bytearray([0x40, 0x01, 0x60,
                               block])  # PN532 + MiFare command
        auth_data += bytearray([0xff, 0xff, 0xff, 0xff, 0xff,
                                0xff])  # default auth KeyA
        auth_data += uuid
        frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=auth_data)
        self.nfc.send_command_check_ack(frame)

    def mifare_read(self, block):
        # Let's try and read a particular block, shall we?
        # So, the Arduino code uses MifareReadBlock, which is a wrapper around the command
        # PN532_COMMAND_INDATAEXCHANGE (0x40) issued to the pn532 controller logical relevant
        # target 0x01, with the payload of MIFARE_CMD_READ (0x30) on block.
        # Build the frame
        frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA,
                           data=bytearray([0x40, 0x01, 0x30, block]))
        # Issue the command
        self.nfc.send_command_check_ack(frame)
        response = self.nfc.read_response()
        return response.get_data()

    def mifare_write(self, block, data):
        # Write write write! What a risk.
        # Arduino uses MifareWriteBlock; a wrapper around PN532_COMMAND_INDATAEXCHANGE (0x40)
        # issued to pn532, logical relevant target 0x01, with a payload of MIFARE_CMD_WRITE
        # (0xA0) on block.
        # Then you've got 16 bytes you can fill with stuff and/or things.
        write_data = bytearray([0x40, 0x01, 0xA0, block])
        write_data += bytearray(data)
        frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=write_data)
        self.nfc.send_command_check_ack(frame)
Exemplo n.º 17
0
class KivySurvey(ScreenManager):
    current_page = ObjectProperty(None, allownone=True)
    current_subjects = ListProperty(None, allownone=True)
    db_interface = ObjectProperty(None)
    current_subjects = ListProperty(None, allownone=True)
    subject_id = NumericProperty(None, allownone=True)
    previous_subject_ids = ListProperty(None, allownone=True)
    current_page = ObjectProperty(None, allownone=True)
    current_subjects_page = ObjectProperty(None, allownone=True)
    next_page = StringProperty(None, allownone=True)
    prev_page = StringProperty(None, allownone=True)
    survey = ObjectProperty(None)
    current_location = DictProperty({})
    gps_loc_interval = NumericProperty(30.0)
    questionnaire = StringProperty(None, allownone=True)
    top_level_questionnaire = StringProperty(None, allownone=True)
    root = ObjectProperty(None)

    def __init__(self, **kwargs):
        global_idmap.update({'kivysurvey': self})
        self.db_interface = DBInterface(self)
        super(KivySurvey, self).__init__(**kwargs)
        self.transition = SlideTransition()
        json = JsonStore(construct_target_file_name('survey.json', __file__))
        for each in json:
            print(each)
        self.survey = Survey(json)
        try:
            gps.configure(on_location=self.receive_gps)
        except:
            pass
        Clock.schedule_once(self.start_gps)

    def on_subject_id(self, instance, value):
        self.load_subjects(value, self.questionnaire)

    def create_subject(self):
        db_interface = self.db_interface
        uid = db_interface.get_unique_id()
        prev_id = self.previous_subject_ids[-1]
        db_interface.add_subject(prev_id, self.questionnaire, uid)
        return uid

    def pop_subjects(self):
        previous_subject_ids = self.previous_subject_ids
        if len(previous_subject_ids) > 0:
            self.subject_id = self.previous_subject_ids.pop()
        else:
            self.subject_id = None
              
    def on_questionnaire(self, instance, value):
        self.load_subjects(self.subject_id, value)
        self.current_subjects_page.allow_add_subject = (
            self.survey.get_allow_add_subjects(value))

    def load_subjects(self, subject_id, questionnaire):
        self.current_subjects = self.db_interface.get_subjects(
            subject_id, questionnaire)

    def get_header_lines(self):
        return self.survey.get_header_definitions(self.questionnaire)

    def set_next_page(self):
        survey = self.survey
        next_page = survey.get_next_page(
            self.questionnaire, self.current_page.page)
        
        if next_page is None:
            return False
        else:
            self.next_page = None
            self.next_page = next_page
            return True

    def add_member(self):
        self.transition.direction = 'left'
        self.previous_subject_ids.append(self.subject_id)
        self.subject_id = None
        self.reset_questionnaire()

    def open_member(self, member_id, instance):
        self.transition.direction = 'left'
        self.previous_subject_ids.append(self.subject_id)
        self.subject_id = member_id
        self.reset_questionnaire()
        current_page = self.current_page.ids.questions
        current_page.load_page_data()

    def reset_questionnaire(self):
        self.current_page.page = None
        self.set_next_page() 
        self.swap_pages()
        self.current_page.ids.questions.clear_questions()

    def set_prev_page(self):
        survey = self.survey
        prev_page = survey.get_prev_page(
            self.questionnaire, self.current_page.page)
        if prev_page is None:
            return False
        else:
            self.prev_page = prev_page
            return True

    def swap_subjects(self):
        subjects1 = self.ids.subjects1
        subjects2 = self.ids.subjects2
        current_subjects_page = self.current_subjects_page
        if current_subjects_page is subjects1:
            self.current = 'subjects2'
            self.current_subjects_page = subjects2
        elif current_subjects_page is subjects2:
            self.current = 'subjects1'
            self.current_subjects_page = subjects1
        self.current_subjects_page.allow_add_subject = (
            self.survey.get_allow_add_subjects(self.questionnaire))
        self.current_page.ids.scrollview.scroll_to_top()

    def swap_pages(self):

        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            self.current = 'questions2'
            self.current_page = questions2
            questions1.page = None
        elif current_page is questions2:
            self.current = 'questions1'
            self.current_page = questions1
            questions2.page = None
        self.current_page.ids.scrollview.scroll_to_top()

    def on_next_page(self, instance, value):
        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            questions2.page = value
        elif current_page is questions2:
            questions1.page = value

    def on_prev_page(self, instance, value):
        questions1 = self.ids.questions1
        questions2 = self.ids.questions2
        current_page = self.current_page
        if current_page is questions1:
            questions2.page = value
        elif current_page is questions2:
            questions1.page = value

    def start_questionnaire(self, questionnaire):
        self.current_page.page = None
        self.swap_subjects()
        self.questionnaire = questionnaire
        self.set_next_page()

    def save_page(self):
        current_page = self.current_page.ids.questions
        current_page.save_page_data()


    def go_back(self):
        does_page_exist = self.set_prev_page()
        survey = self.survey
        questionnaire = self.questionnaire
        prev_questionnaire = survey.get_previous_questionnaire()
        self.transition.direction = 'right'
        if self.current in ['subjects1', 'subjects2']:
            if prev_questionnaire is None:
                self.app.root.change_screen('cluster', go_back=True)
                return
            else:
                if survey.get_allow_add_subjects(questionnaire):
                    self.pop_subjects()
                self.start_questionnaire(survey.pop_previous_questionnaire())
        elif does_page_exist:
            self.swap_pages()
        else:
            if self.subject_id is None:
                self.pop_subjects()
                self.swap_subjects()
            else:
                self.pop_subjects()
                self.swap_subjects()

    def go_forward(self):
        does_page_exist = self.set_next_page()
        survey = self.survey
        questionnaire = self.questionnaire
        next_questionnaire = survey.get_next_questionnaire(questionnaire)
        self.transition.direction = 'left'
        if self.current in ['subjects1', 'subjects2']:
            if next_questionnaire is None:
                if survey.get_allow_add_subjects(questionnaire):
                    self.pop_subjects()
                prev_questionnaire = survey.pop_previous_questionnaire()
                self.start_questionnaire(prev_questionnaire)
            else:
                if survey.get_allow_forward(questionnaire):
                    survey.store_current_questionnaire(questionnaire)
                    self.start_questionnaire(next_questionnaire)
        elif does_page_exist:
            self.save_page()
            self.swap_pages()
        else:
            is_creating_subject = False
            if survey.get_allow_add_subjects(questionnaire) and (
                self.subject_id is None):
                self.subject_id = self.create_subject()
            self.save_page()
            if next_questionnaire is None:
                self.pop_subjects()
                prev_questionnaire = survey.pop_previous_questionnaire()
                self.start_questionnaire(prev_questionnaire)
            elif survey.get_allow_add_subjects(next_questionnaire):
                survey.store_current_questionnaire(questionnaire)
                self.start_questionnaire(next_questionnaire)
            else:
                self.pop_subjects()
                self.swap_subjects()

    def start_gps(self, dt):
        try:
            gps.start()
        except:
            pass

    def receive_gps(self, **kwargs):
        if kwargs is not {}:
            self.current_location = kwargs
            gps.stop()
            Clock.schedule_once(self.start_gps, self.gps_loc_interval)

    def raise_error(self, error_title, error_text):
        self.app.raise_error(error_title, error_text)

    def raise_option_dialogue(self, option_title, option_text, options, 
            callback):
        self.app.raise_option_dialogue(option_title, option_text, options,
            callback)

    def raise_numpad(self, numpad_title, callback, units=None,
        minimum=None, maximum=None, do_decimal=False):
        self.app.raise_numpad(numpad_title, callback, units, 
            minimum, maximum, do_decimal)
Exemplo n.º 18
0
    def start(self):
        self.logger.info('Starting NFCInterface ...')
        self.db = DBInterface(self.logger)
        self.running = True
        while (self.running):
            # Block waiting for a swipe
            uuid = self.get_uuid()

            # What we really want here is a callback interface, to abstract away the
            # specifics of this particular project. For now, we make it work.

            if (self.writing):
                # If we're in writing mode
                self.logger.info('In writing mode')
                success = 1

                # Populate the database with the UUID, if it's not already available,
                #  so at least this card is registered.
                card_id = self.db.register_card(uuid)
                if card_id is None:
                    success = 0

                # Authenticate for reading/writing
                self.mifare_auth(uuid, 0x04)
                ids = [
                    self.write_data[0], card_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0
                ]
                self.mifare_write(0x04, ids)

                self.mifare_auth(uuid, 0x05)
                md5hash = self.write_data[2:]
                self.mifare_write(0x05, md5hash)

                #binprint.print_r_t(self.write_data, "Data to be written")

                # Need a check here to determine if the card has written correctly,
                # then we can trust the success check below.

                if (success):
                    self.db.update_card(card_id, self.write_data[0])
                    self.writing = False
                    self.logger.info('Success beep.')
                    self.red(0)
                    self.blink(15, 3, 0)

                else:
                    self.logger.info("Failure beep.")
                    self.green(0)
                    self.blink(12, 3, 0)

            else:
                # If we're not in writing mode, we're in default reading mode
                self.mifare_auth(uuid, 0x04)
                response_A = self.mifare_read(0x04)

                self.mifare_auth(uuid, 0x04)
                response_B = self.mifare_read(0x05)

                user_id = self.db.check_hash(uuid, response_A, response_B)
                if (user_id):
                    logged_in = self.db.toggle_status(user_id)  # 1 in, 0 out
                    if (logged_in):
                        self.logger.info("Success in beep.")
                        self.green(1)
                    else:
                        self.logger.info("Success out beep.")
                        self.blink(15, 2, 1)
                else:
                    self.logger.info("Failure beep.")
                    self.red(1)

            sleep(0.5)
            self.logger.info("LED reset")
            self.green(0)
            self.red(0)

            # Delay the loop reset for a bit of time
            # to prevent someone from leaning on the
            # login/logout button.
            sleep(3)
Exemplo n.º 19
0
# -*- coding:utf-8 -*-

from flask import Flask, jsonify, url_for, make_response, abort, request
from dbinterface import DBInterface
from utils import API_CLIENTS_ROUTE, API_CLIENTS_PORT, token_required

api = Flask(__name__)

clients = DBInterface('clients', ['name', 'phonenumber', 'medicines'])

# Funções auxiliares


def make_public_client(client):
    '''
	Altera a forma de exibição de um elemento do cadastro.
	Ao invés de mostrar o ID do elemento, mostra a URI do mesmo,
	  tornando assim mais fácil a requisição do mesmo via API.
	'''
    new_client = {}
    for field in client:
        if field == 'id':
            new_client['uri'] = url_for('get_client',
                                        client_id=client['id'],
                                        _external=True)

        else:
            new_client[field] = client[field]

    return new_client
Exemplo n.º 20
0
class DriveMainThread(Thread):


    def __init__(self, folders_to_track, start_sync_at, pyfile, **kwargs):
        super(DriveMainThread, self).__init__(**kwargs)
        self.drive_data = DBInterface(os.path.dirname(
            os.path.abspath(pyfile))+'/drive_data/', 'drive_files')
        base_path = os.path.dirname(os.path.abspath(pyfile))+'/'
        self.updated_folders = set()
        self.start_sync_at = start_sync_at
        self.folders_to_track = folders_to_track
        self.setup_drive()
        self.update_queue = Queue.Queue()
        self.get_tracked_folder_ids( 
            folders_to_track, os.path.dirname(
            os.path.abspath(pyfile))+'/')
        self.tracked_widgets = {}
        self.folders_to_track = [
            base_path+path+'/' for path in folders_to_track]

    def add_drive_widget(self, widget, folder_to_track):
        assert(folder_to_track in self.folders_to_track)
        tracked_widgets = self.tracked_widgets
        if folder_to_track not in tracked_widgets:
            tracked_widgets[folder_to_track] = [widget]
        else:
            tracked_widgets[folder_to_track].append(widget)

    def setup_drive(self):
        credentials = storage.get()
        self.queue = queue = Queue.Queue()
        if credentials is None:
            flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, 
                redirect_uri=REDIRECT_URI)
            authorize_url = flow.step1_get_authorize_url()
            print 'Go to the following link in your browser: ' + authorize_url
            code = raw_input('Enter verification code: ').strip()
            credentials = flow.step2_exchange(code)
            storage.put(credentials)
        http = httplib2.Http()
        http = credentials.authorize(http)
        self.drive_service = drive_service = build('drive', 'v2', http=http)
        self.thread_pool = thread_pool = DriveThreadPool(1, queue, 
            credentials)

    def get_tracked_folder_ids(self, folders_to_track, address):
        drive_data = self.drive_data
        for folder_name in self.folders_to_track:
            q="title = '{}'".format(folder_name)
            data = self.drive_service.children().list(
                folderId='root', q=q).execute()
            folder_add = address+folder_name+'/'
            self.ensure_dir(folder_add)
            #self.add_folder_observer(self.get_callback, unicode(folder_add))
            for dat in data[u'items']:
                item_id = dat[u'id']
                drive_data.set_entry(
                    'folders', item_id, 'file_add', folder_add)
                drive_data.set_entry(
                    'tracked_items', item_id, 'file_add', folder_add)
    

    def check_file_in_tracked_folders(self, file_data):
        parents = file_data[u'parents']
        folders = self.drive_data.get_table('folders')

        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                return True
        return False

    def run(self):
        while True:
            query_download = self.update_queue.get()
            if query_download:
                self.retrieve_all_changes()
                self.update_queue.task_done()
       

    def download_folder(self, file_id, file_data):
        parents = file_data[u'parents']
        drive_data = self.drive_data
        #save_data = self.save_data
        folders = drive_data.get_table('folders')
        get_entry = drive_data.get_entry
        append_entry = drive_data.append_entry
        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                address = get_entry('folders', parent_id, 'file_add')
                folder_name = file_data[u'title']
                folder_add = address+folder_name+'/'
                self.ensure_dir(folder_add)
                append_entry('folders', file_id, 'file_add', folder_add)
                append_entry('tracked_items', file_id, 'file_add', folder_add)

    def place_address_in_queue(self, address, file_name, file_id, 
        time_since_epoch, download_url):
        drive_data = self.drive_data
        self.ensure_dir(address)
        file_add = address+file_name
        drive_data.append_entry('tracked_items', file_id, 'file_add', 
            file_add)
        do_download = False
        try:
            mod_time = os.stat(file_add).st_mtime
            if time_since_epoch > mod_time:
                do_download = True
            else:
                do_download = False
        except:
            do_download = True
        if do_download:
            self.queue.put((self._download, [download_url, file_add, 
                time_since_epoch], {}))

    def download_file(self, file_id, file_data):
        mod_date = file_data[u'modifiedDate']
        parents = file_data[u'parents']
        time_since_epoch = self.calculate_time_since_epoch(mod_date)
        drive_data = self.drive_data
        folders = drive_data.get_table('folders')
        get_entry = drive_data.get_entry
        download_url = file_data[u'downloadUrl']
        file_name = file_data[u'title']
        place_address_in_queue = self.place_address_in_queue
        for parent in parents:
            parent_id = parent[u'id']
            if parent_id in folders:
                address = get_entry('folders', parent_id, 'file_add')
                if isinstance(address, list):
                    for add in address:
                        place_address_in_queue(add, file_name, file_id,
                            time_since_epoch, download_url)
                else:
                    place_address_in_queue(address, file_name, file_id,
                            time_since_epoch, download_url)

    def retrieve_all_changes(self):
        result = []
        page_token = None
        drive_data = self.drive_data
        largest_change = int(self.get_largest_change_id())
        try:
            start_change_id = str(int(
                drive_data.get_entry('changes', 'last_change', 'id')) + 1)
        except:
            start_change_id = str(int(self.start_sync_at))
        # if self.progress_tracker.start_change_id is None:
        #     self.progress_tracker.start_change_id = int(start_change_id)
        # self.progress_tracker.last_change_id = int(start_change_id)
        if largest_change >= int(start_change_id):
            print('we should parse')
            # Clock.schedule_once(partial(self.retrieve_page_of_changes, None, 
            #     start_change_id))
            while True:
                param = {}
                print('grabbing changes')
                if start_change_id is not None:
                    param['startChangeId'] = start_change_id
                if page_token is not None:
                    param['pageToken'] = page_token
                changes = self.drive_service.changes().list(**param).execute()
                self.parse_changes(changes)
                #self.sync()
                page_token = changes.get('nextPageToken')
                if not page_token:
                    print('done breaking')
                    break

    def parse_changes(self, changes):
        drive_data = self.drive_data
        download_folder = self.download_folder
        download_file = self.download_file
        remove_file = self.remove_file
        tracked_items = drive_data.get_table('tracked_items')
        check_file_in_tracked_folders = self.check_file_in_tracked_folders
        get_is_folder = self.get_is_folder
        set_entry = drive_data.set_entry
        get_file = self.get_file
        if len(changes['items']) == 0:
            return None
        for change in changes['items']:
            file_id = change[u'fileId']
            change_id = change[u'id']
            file_data = get_file(file_id)
            is_deleted = change[u'deleted']
            if is_deleted and file_id in tracked_items:
                self.handle_remove_callback(file_id)
                remove_file(file_id)
            if file_data != None:
                if check_file_in_tracked_folders(file_data):
                    if get_is_folder(file_data):
                        download_folder(file_id, file_data)
                    else:
                        download_file(file_id, file_data)
            set_entry('changes', 'last_change', 'id', change_id)
        return change_id


    def handle_remove_callback(self, file_id):
        file_adds = self.drive_data.get_entry(
            'tracked_items', file_id, 'file_add')
        tracked_widgets = self.tracked_widgets
        if file_adds is not None:
            if isinstance(file_adds, list):
                for file_add in file_adds:
                    widgets_for_removal = []
                    widgets_a = widgets_for_removal.append
                    dir_name = str(dirname(file_add) + '/')
                    for wid in tracked_widgets[dir_name]:
                        r_wid = wid()
                        if r_wid is not None:
                            file_callback = r_wid.file_callback
                            Clock.schedule_once(partial(file_callback, 
                                file_add, True))
                        else:
                            widgets_a(wid)
                    for wid_ref in widgets_for_removal:
                        tracked_widgets[file_adds].remove(wid_ref)

    def remove_file(self, file_id):
        drive_data = self.drive_data
        to_remove = []
        to_remove_a = to_remove.append
        remove_entry = drive_data.remove_entry
        file_adds = drive_data.get_entry('tracked_items', file_id, 'file_add')
        if file_adds is not None:
            for file_add in file_adds:
                try:
                    os.remove(file_add)
                    to_remove_a(file_add)
                except:
                    continue
            for add in to_remove:
                remove_entry('tracked_items', file_id, 'file_add', add)

    def ensure_dir(self, f):
        d = os.path.dirname(f)
        if not os.path.exists(d):
            os.makedirs(d)

    def calculate_time_since_epoch(self, drive_time):
        date, current_time = drive_time.split('T')
        year, month, day = date.split('-')
        hours, minutes, seconds = current_time.split(':')
        seconds = seconds.split('.')[0]
        py_date = datetime.datetime(int(year), int(month), int(day), 
            hour=int(hours), minute=int(minutes), 
            second=int(seconds))
        return time.mktime(py_date.timetuple())

    def get_is_folder(self, file_data):
        return file_data[u'mimeType'] == u'application/vnd.google-apps.folder'

    def get_file(self, fid):
        try:
            return self.drive_service.files().get(fileId=fid).execute()
        except:
            return None

    def list_folder_content(self, fid):
        return self.drive_service.children().list(folderId=fid).execute()

    def get_about_data(self):
        return self.drive_service.about().get().execute()

    def get_largest_change_id(self):
        return self.get_about_data()[u'largestChangeId']
    
    def get_content_title(self, fid):
        return self.drive_service.files().get(fileId=fid).execute()[u'title']

    def _download(self, queue, drive_service, download_url, name, time):
        if download_url:
            try:
                resp, content = drive_service._http.request(download_url)
            except:
                print 'An error occurred: '
                return
            if resp.status == 200:
                with open(name, 'w') as save_file:
                    save_file.write(content)
                os.utime(name, (os.stat(name).st_atime, 
                        time))
                folder_name = os.path.dirname(name) + '/'
                tracked_widgets = self.tracked_widgets
                widgets_for_removal = []
                widget_a = widgets_for_removal.append
                if folder_name in tracked_widgets:
                    for wid in tracked_widgets[folder_name]:
                        r_wid = wid()
                        if r_wid is not None:
                            Clock.schedule_once(partial(r_wid.file_callback,
                                name, False), 15.)
                        else:
                            widget_a(wid)
                    for wid_ref in widgets_for_removal:
                        tracked_widgets[folder_name].remove(wid_ref)
                queue.task_done()
            else:
                print 'An error occurred: %s' % resp