Exemplo n.º 1
0
 def __init__(self, map):
     self.log = MyLogger(name='Game')
     self.player_x = 0
     self.player_y = 0
     self.map = map
     self.current_room = self._get_room(0, 0)
     self._look_at(self.current_room)
Exemplo n.º 2
0
 def __init__(self, master=None):
     Application_ui.__init__(self, master)
     self.logger = MyLogger(log_board=self.log_board,
                            filename='all.log',
                            level='debug')
     self.learn = Learn(self.logger)
     self.t1 = None
Exemplo n.º 3
0
    def __init__(self):
        self.pir = MyPiPIR(MyPiPIR.DEFAULT)
        self.led = MyPiLed(MyPiLed.RED)
        self.buzzer = MyPiBuzzer(MyPiBuzzer.DEFAULT)
        self.locks = []
        self.tries = 0
        self.max_tries = 3
        self.locks.append(Lock('Vault'))

        self.logger = MyLogger("SecuritySystem")
        self.check_interval = self.__class__.CHECK_INTERVAL
        self.enabled = False
Exemplo n.º 4
0
def server_start():
    MyLogger().my_logger().info("Server started!")

    # Check for upload and signed folder
    if not path.exists(UPLOAD_FOLDER) or not path.isdir(UPLOAD_FOLDER):
        makedirs(UPLOAD_FOLDER)
    if not path.exists(SIGNED_FOLDER) or not path.isdir(SIGNED_FOLDER):
        makedirs(SIGNED_FOLDER)

    try:
        server.run(host=HOST, port=PORT, debug=False)
    except:
        MyLogger().my_logger().error("Impossible to start Server")
        pass
Exemplo n.º 5
0
class MysqlHandler():
    def __init__(self,
                 host='http://127.0.0.1',
                 user='******',
                 password='******',
                 database='zhihu'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.conn = pymysql.connect(host=host,
                                    user=user,
                                    password=password,
                                    database=database,
                                    charset='utf-8')

        self.logger = MyLogger(name='mysql')
        self.error_count = 0

    def __enter__(self):
        self.cur = self.conn.cursor()
        return self.cur

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.error_count += 1
        if self.error_count > 3:
            return False

        if exc_type == InterfaceError:
            msg = '\n'.join(
                traceback.format_exception(exc_type, exc_val, exc_tb))
            self.logger.log(msg=msg)
            self.conn.rollback()
            self.conn = pymysql.conncet(host=self.host,
                                        user=self.user,
                                        password=self.password,
                                        database=self.database,
                                        charset='utf-8')
        else:
            msg = '\n'.join(
                traceback.format_exception(exc_type, exc_val, exc_tb))
            self.logger.log(msg=msg)
            self.conn.rollback()
        return True

    def __del__(self):
        self.cur.close()
        self.conn.close()
Exemplo n.º 6
0
def clear_pin(user_id):
    MyLogger().my_logger().info("Clearing PIN")
    if user_id in memorized_pin:
        if "timestamp" in memorized_pin[user_id]:
            memorized_pin[user_id].pop("timestamp")
        if "pin" in memorized_pin[user_id]:
            memorized_pin[user_id].pop("pin")
    def _not_valid_yet_popup():
        ''' Little popup for telling the user that his certificate is not valid yet '''

        MyLogger().my_logger().info("Certificate not valid yet")
        widget = Tk()
        row = Frame(widget)
        label1 = Label(row,
                       text="Il certificato di firma non è ancora valido,")
        label2 = Label(row, text="firma digitale annullata")
        row.pack(side="top", padx=60, pady=20)
        label1.pack(side="top")
        label2.pack(side="top")

        def on_click():
            widget.destroy()

        button = Button(widget, command=on_click, text="OK")
        button.pack(side="top", fill="x", padx=120)
        filler = Label(widget, height=1, text="")
        filler.pack(side="top")

        widget.title("Warning")
        widget.attributes("-topmost", True)
        widget.update()
        DigiSignLib()._center(widget)
        widget.mainloop()
Exemplo n.º 8
0
    def __init__(self, ip=HOST, port=PORT):
        """
        initializing

        Args:
            ip: server ip
            port: server port
        """
        if ClientModel.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            ClientModel.__instance = self
        #log
        self.logger = MyLogger.getInstance("client.log")
        #server ip and port
        self.ip, self.port = ip, port
        #TCP socket建立
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.ip, self.port))
        #建立锁
        self.mutex = threading.Lock()
        #读取服务器公钥
        with open("publicKey.pem", "r") as f:
            self.server_public_key = rsa.PublicKey.load_pkcs1(
                f.read().encode())

        self.Crypto = ClientCrypto()
        self.Crypto.new_rsa(self.server_public_key)
        self.logger.info("client model initializd successfully...")
Exemplo n.º 9
0
    def make_a_p7m(content, certificate_value, signer_info,
                   p7m_sig_attrs: P7mAttributes):
        '''
            Return a well formed complete p7m

            Param:
                content: file content to sign
                certificate_value: value field of the smart card certificate
                signer_info: signer info in asn1 form
                p7m_sig_attrs: existing p7m signatures attributes
        '''

        p7m = Encoder()
        p7m.start()

        MyLogger().my_logger().info("encoding p7m")
        p7m.enter(Numbers.Sequence)  # 1
        p7m.write(PKCS7_SIGNED_DATA, Numbers.ObjectIdentifier)
        p7m.enter(ZERO_TAG, Classes.Context)  # 2
        p7m.enter(Numbers.Sequence)  # 3
        p7m._emit(P7mEncoder._version_number())
        p7m.enter(Numbers.Set)  # 4
        p7m._emit(P7mEncoder._digest_algorithm() + p7m_sig_attrs.algos)
        p7m.leave()  # 4
        p7m._emit(P7mEncoder._content_info(content))
        p7m.enter(ZERO_TAG, Classes.Context)  # 4
        p7m._emit(certificate_value + p7m_sig_attrs.certificates)
        p7m.leave()  # 4
        p7m._emit(signer_info)
        p7m.leave()  # 3
        p7m.leave()  # 2
        p7m.leave()  # 1

        return p7m.output()
    def get_certificate_serial_number(session, certificate):
        ''' 
            Return the serial number of `certificate`

            Params:
                session: smart card session
                certificate: smart card certificate
        '''

        MyLogger().my_logger().info("fetching certificate serial number")
        try:
            serial_number = session.getAttributeValue(
                certificate, [LowLevel.CKA_SERIAL_NUMBER])[0]
        except:
            raise SmartCardConnectionError(
                "Certificate has no valid serial number")

        try:
            int_serial_number = int.from_bytes(serial_number,
                                               byteorder='big',
                                               signed=True)
        except:
            raise SmartCardConnectionError(
                "Can not cast certificate serial number to integer")
        return int_serial_number
Exemplo n.º 11
0
def _get_pin_popup(user_id):
    ''' Little popup to input Smart Card PIN '''

    MyLogger().my_logger().info("User PIN input")
    widget = Tk()
    row = Frame(widget)
    label = Label(row, width=10, text="Insert PIN")
    pinbox = Entry(row, width=15, show='*')
    row.pack(side="top", padx=60, pady=20)
    label.pack(side="left")
    pinbox.pack(side="right")

    def on_enter(evt):
        on_click()

    def on_click():
        memorized_pin[user_id]["pin"] = pinbox.get()
        memorized_pin[user_id]["timestamp"] = datetime.now()
        widget.destroy()

    pinbox.bind("<Return>", on_enter)
    button = Button(widget, command=on_click, text="OK")
    button.pack(side="top", fill="x", padx=80)
    filler = Label(widget, height=1, text="")
    filler.pack(side="top")

    widget.title("Smart Card PIN")
    widget.attributes("-topmost", True)
    widget.update()
    _center(widget)
    widget.mainloop()
Exemplo n.º 12
0
    def __init__(self,
                 host='http://127.0.0.1',
                 user='******',
                 password='******',
                 database='zhihu'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.conn = pymysql.connect(host=host,
                                    user=user,
                                    password=password,
                                    database=database,
                                    charset='utf-8')

        self.logger = MyLogger(name='mysql')
        self.error_count = 0
Exemplo n.º 13
0
class Lock:
  def __init__(self, name):
    self.name = name
    self.motor = MyPiStepperMotor(MyPiStepperMotor.DEFAULT)
    self.logger = MyLogger('Lock')

  #def reset(self):
    # TODO Should reset to known orientation

  def lock(self):
    self.logger.info("Locking " + self.name)
    self.motor.rotate(90)

  def unlock(self):
    # FIXME should rotate anticlockwise
    self.logger.info("Unlocking " + self.name)
    self.motor.rotate(-90)
    def get_file_content(file_path):
        ''' Return `file_path` content in binary form '''

        MyLogger().my_logger().info(f"reading file {file_path}")
        with open(file_path, "rb") as file:
            file_content = file.read()

        return file_content
    def _check_certificate_owner(certificate_value, user_cf):
        ''' Check if user_cf is equal to smart card cf. Raise a `CertificateOwnerException` '''

        MyLogger().my_logger().info("Chech for certificate owner")
        certificate_x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                                   bytes(certificate_value))

        subject = certificate_x509.get_subject()
        components = dict(subject.get_components())
        component = components[bytes("serialNumber".encode())]
        codice_fiscale = component.decode()[-16:]

        if codice_fiscale.upper() != user_cf.upper():
            raise CertificateOwnerException(
                f"{user_cf} (input) != {codice_fiscale} (smartcard)")
        else:
            MyLogger().my_logger().info("owner verified")
    def fetch_smart_card_sessions():
        ''' Return a `session` list for the connected smart cards '''

        MyLogger().my_logger().info("loading drivers")
        pkcs11 = PyKCS11Lib()
        driver_loaded = False

        # try with default
        try:
            pkcs11.load()
            driver_loaded = True
        except:
            MyLogger().my_logger().warning("no default driver")

        # anyway load known drivers
        for file in listdir(DRIVER_FOLDER):
            try:
                pkcs11.load(file)
                MyLogger().my_logger().info(f"driver {fsdecode(file)} loaded")
                driver_loaded = True
            except:
                MyLogger().my_logger().warning(
                    f"driver {fsdecode(file)} NOT loaded")
                continue

        # cannot load any driver file
        if (not driver_loaded):
            raise SmartCardConnectionError("No driver found")

        slots = SignatureUtils._fetch_slots(pkcs11)

        # TODO select slot (and log something?)
        sessions = []
        for slot in slots:
            try:
                session = pkcs11.openSession(slot,
                                             LowLevel.CKS_RW_PUBLIC_SESSION)
                sessions.append(session)
            except:
                continue

        if (len(sessions) < 1):
            raise SmartCardConnectionError("Can not open any session")

        return sessions
    def user_logout(session):
        ''' 
            User logout from a `session`

            Params:
                session: smart card session
        '''

        MyLogger().my_logger().info("user logout")
        session.logout()
Exemplo n.º 18
0
def get_pin(user_id):
    ''' Gets you the `PIN` '''

    if user_id not in memorized_pin:
        memorized_pin[user_id] = {}

    if "pin" not in memorized_pin[user_id]:
        _get_pin_popup(user_id)
    elif not _is_pin_valid(user_id):
        MyLogger().my_logger().info("Invalidating PIN")
        clear_pin(user_id)
        _get_pin_popup(user_id)
    else:
        MyLogger().my_logger().info("Refreshing PIN")
        memorized_pin[user_id]["timestamp"] = datetime.now()

    # check for mishapening
    if "pin" not in memorized_pin[user_id]:
        raise ValueError("No pin inserted")
    def _fetch_slots(pkcs11_lib):
        ''' Return a `slot list` (connected Smart Cards) '''

        MyLogger().my_logger().info("getting slots")
        try:
            slots = pkcs11_lib.getSlotList(tokenPresent=True)
            if (len(slots) < 1):
                raise Exception()  # only to get to the external except block
            else:
                return slots
        except:
            raise SmartCardConnectionError("No smart card slot found")
 def __init__(self):
   self.pir = MyPiPIR(MyPiPIR.DEFAULT)
   self.led = MyPiLed(MyPiLed.RED)
   self.buzzer = MyPiBuzzer(MyPiBuzzer.DEFAULT)
   self.locks = []
   self.tries = 0
   self.max_tries = 3
   self.locks.append(Lock('Vault'))
   
   self.logger = MyLogger("SecuritySystem")
   self.check_interval = self.__class__.CHECK_INTERVAL
   self.enabled = False
Exemplo n.º 21
0
class CateDetail():
    def __init__(self):
        self.log = MyLogger(
            'SougouSpider',
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         'log_SougouSpider.log'))

    def cate_detail(self, html, type1, type2):
        result = list()
        pattern = re.compile(
            '<div class="detail_title">.*?>(.*?)</a></div>.*?"dict_dl_btn"><a href="(.*?)"></a></div>',
            re.S)
        items = re.findall(pattern, html)
        for item in items:
            name, url = item
            result.append({
                'name': type1 + '_' + type2 + '_' + name,
                'url': url,
                'type1': type1,
                'type2': type2
            })
        return result

    def start(self):
        cate_list = db.find_all('sougou_cate')
        for cate in cate_list:
            type1 = cate['type1']
            type2 = cate['type2']
            n = int(cate['page'])
            for i in range(1, n + 1):
                print('正在解析{}的第{}页'.format(type1 + type2, i))
                url = cate['url'].format(i)
                html = get_html(url)
                if html != -1:
                    result = self.cate_detail(html, type1, type2)
                    self.log.info('正在解析页面{}'.format(url))
                    for data in result:
                        db.save_one_data('sougou_detail', data)
                        self.log.info('正在存储数据{}'.format(data['name']))
            time.sleep(2)
Exemplo n.º 22
0
class MySQLConnection(Singleton):

    def __init__(self):
        self.logger = MyLogger()
        self._conn()
        self.pool = Queue.Queue(maxsize=conf.MAX_POOL_SIZE)
        self._init_pool()

    def _init_pool(self):
        for _ in range(0, conf.MAX_POOL_SIZE):
            self.pool.put(self._conn())

    def get_connection(self):
        conn = self.pool.get()
        self._maybe_reconn(conn)
        return conn

    def return_connection(self, conn):
        # conn.commit()
        return self.pool.put(conn)

    def _conn(self):
        try:
            conn = pymysql.connect(** conf.DB_CONFIG)
            conn.autocommit(True)
            return conn
        except Exception as e:
            self.logger.error(e)
            return False

    def _maybe_reconn(self, conn):
        try:
            conn.ping(reconnect=True)
        except Error as e:
            self.logger.warn(e)
            raise e

    def close_conn(self):
        while not self.pool.empty():
            self.pool.get().close()
    def _check_certificate_validity(certificate_value):
        MyLogger().my_logger().info("Chech for certificate time validity")
        certificate_x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                                   bytes(certificate_value))
        # [2:14] gets rid of "b'" at the beginning and "##Z" at the end
        # precision in minutes
        notBefore = str(certificate_x509.get_notBefore())[2:14]
        notAfter = str(certificate_x509.get_notAfter())[2:14]
        current_time = int(datetime.now().strftime("%Y%m%d%H%M"))

        try:
            diff = current_time - int(notBefore)
        except:
            raise ValueError(f"Impossible to cast {notBefore} to int")

        # <= for safety
        if diff <= 0:
            DigiSignLib()._not_valid_yet_popup()
            raise CertificateValidityError("Certificate not valid yet")

        try:
            diff = int(notAfter) - current_time
        except:
            raise ValueError(f"Impossible to cast {notAfter} to int")

        # <= for safety
        if diff <= 0:
            DigiSignLib().PROCEED = None
            DigiSignLib()._proceed_with_expired_certificate()
            if DigiSignLib().PROCEED == None:
                MyLogger().my_logger().error("PROCEED is still None")
                raise ValueError(
                    "Something went wrong with the expired certificate choise popup"
                )
            if not DigiSignLib().PROCEED:
                MyLogger().my_logger().warning("User chosen to NOT proceed")
                raise CertificateValidityError("Certificate expired")
        MyLogger().my_logger().info("User chosen to proceed")
    def digest(session, content):
        ''' 
            Return `content` hash

            Params:
                session: smart card session
                content: content to hash
        '''

        MyLogger().my_logger().info("hashing content")
        try:
            digest = session.digest(content, Mechanism(LowLevel.CKM_SHA256))
        except:
            raise SmartCardConnectionError("Failed on digest content")

        return bytes(digest)
    def get_certificate_issuer(session, certificate):
        ''' 
            Return the issuer of `certificate`

            Params:
                session: smart card session
                certificate: smart card certificate
        '''

        MyLogger().my_logger().info("fetching certificate issuer")
        try:
            certificate_issuer = session.getAttributeValue(
                certificate, [LowLevel.CKA_ISSUER])[0]
        except:
            raise SmartCardConnectionError("Certificate has no valid issuer")

        return bytes(certificate_issuer)
Exemplo n.º 26
0
def error_response_maker(error_message, user_tip, status):
    ''' Returns an HTTP error response with HTTP_status = `status`.

            body structure:

            {
                error_message: error_message,
                user_tip: user_tip
            }
    '''

    MyLogger().my_logger().error(error_message)
    return make_response(
        jsonify({
            "error_message": error_message,
            "user_tip": user_tip
        }), status)
    def fetch_certificate(session):
        ''' 
            Return smart card certificate

            Params:
                session: smart card session
        '''

        MyLogger().my_logger().info("fetching certificate")
        try:
            certificates = session.findObjects([(LowLevel.CKA_CLASS,
                                                 LowLevel.CKO_CERTIFICATE)])
        except:
            raise SmartCardConnectionError("Certificate not found")

        # TODO check for right certificate
        certificate = certificates[1]
        return certificate
Exemplo n.º 28
0
    def encode_signed_attributes(content_hash, certificate_hash):
        ''' Return a well formed signed attributes p7m field

            Params:
                content_hash: content digest
                certificate_hash: certificate digest
        '''

        signed_attributes = Encoder()
        signed_attributes.start()

        MyLogger().my_logger().info("encoding signed attributes")
        signed_attributes.enter(ZERO_TAG, Classes.Context)
        signed_attributes._emit(
            P7mEncoder._get_signed_attributes(content_hash, certificate_hash))
        signed_attributes.leave()

        return signed_attributes.output()
Exemplo n.º 29
0
    def bytes_to_sign(content_hash, certificate_hash):
        ''' Return the p7m part that needs to be signed

            Params:
                content_hash: content digest
                certificate_hash: certificate digest
        '''

        signed_attributes = Encoder()
        signed_attributes.start()

        MyLogger().my_logger().info("building bytes to sign")
        signed_attributes.enter(Numbers.Set)
        signed_attributes._emit(
            P7mEncoder._get_signed_attributes(content_hash, certificate_hash))
        signed_attributes.leave()

        return signed_attributes.output()
Exemplo n.º 30
0
    def encode_signer_info(issuer, serial_number, signed_attributes,
                           signed_bytes, existing_sig_infos):
        ''' Return a well formed signer info p7m field

            Params:
                issuer: smart card certificate issuer (bytes)
                serial_number: smart card serial number (int)
                signed_attributes: signed attributes p7m field
                signed_bytes: signature (bytes)
        '''

        signer_info = Encoder()
        signer_info.start()

        MyLogger().my_logger().info("encoding signer info")
        signer_info.enter(Numbers.Set)  # 1
        signer_info.enter(Numbers.Sequence)  # 2
        signer_info._emit(P7mEncoder._version_number())

        signer_info.enter(Numbers.Sequence)  # 3
        signer_info._emit(issuer)
        signer_info.write(serial_number, Numbers.Integer)
        signer_info.leave()  # 3

        signer_info.enter(Numbers.Sequence)  # 3
        signer_info.write(SHA256, Numbers.ObjectIdentifier)
        signer_info.write(0, Numbers.Null)
        signer_info.leave()  # 3

        signer_info._emit(signed_attributes)

        signer_info.enter(Numbers.Sequence)  # 3
        signer_info.write(RSA, Numbers.ObjectIdentifier)
        signer_info.write(0, Numbers.Null)
        signer_info.leave()  # 3

        signer_info.write(signed_bytes, Numbers.OctetString)

        signer_info.leave()  # 2
        if existing_sig_infos != b'':
            signer_info._emit(existing_sig_infos)
        signer_info.leave()  # 1

        return signer_info.output()
Exemplo n.º 31
0
    def handle(self):
        '''
        handle request
        '''
        #log
        self.logger = MyLogger.getInstance("server.log")
        #读取服务器私钥
        with open("privateKey.pem", "r") as f:
            self.private_key = rsa.PrivateKey.load_pkcs1(f.read().encode())
        #服务器加密管理
        self.Crypto = ServerCrypto()
        self.Crypto.new_rsa(self.private_key)
        #服务器数据库管理
        self.db = db(DB_NAME)
        self.db.create_user_table()

        #消息读取循环
        while True:
            #接受客户端数据
            data_spec, data_recv = self.recv_data()
            #若客户端断开则退出
            if not data_recv:
                self.logger.info("client disconnected...")
                break
            #解密
            data_recv = self.Crypto.decrypt(data_spec, data_recv)
            self.logger.info("server received (crypto removed) from client " +
                             str(threading.current_thread()) + ": " +
                             json.dumps(data_recv))

            #客户端登陆处理
            if data_recv["type"] == "req_login":
                self.handle_login(data_recv)
            elif data_recv["type"] == "req_stock_kline":
                self.handle_kline(data_recv)
            elif data_recv["type"] == "req_stock_detail":
                self.handle_detail(data_recv)
            elif data_recv["type"] == "req_stock_list":
                self.handle_list(data_recv)
            elif data_recv["type"] == "live_check":
                self.send_data("2", dict({"type": "live_check"}))
            else:
                self.send_data("2", dict({"type": "error"}))
    def user_login(sessions, pin):
        ''' 
            User login on a `session` using `pin`

            Params:
                sessions: smart card session list
                pin: user pin

            Returns:
                the logged in session
        '''

        MyLogger().my_logger().info("user login")
        for session in sessions:
            try:
                session.login(pin)
                return session
            except:
                continue

        raise SmartCardConnectionError(
            "Can not login on any sessions provided")
Exemplo n.º 33
0
class MySQLQuery(Singleton):

    def __init__(self, redis):
        self.connection = MySQLConnection()
        self.logger = MyLogger().logger
        self.redis = redis
        self.executor = ThreadPoolExecutor(conf.THREAD_NUM)

    @staticmethod
    def gen_table(timestamp, _type="month"):

        timestamp = timestamp and time.localtime(float(timestamp)) or time.localtime()
        _format = ""
        if _type == "day":
            _format = "%Y%m%d"
        elif _type == "month":
            _format = "%Y%m"
        elif _type == "year":
            _format = "%Y"
        date_str = time.strftime(_format, timestamp)
        #TODO to cache the date_str for performance
        return "%s%s" % (conf.MYSQL_TABLE_PREFIX, date_str), date_str

    @get_and_return_connection
    def create_table(self, table_name, **_):

        sql = '''
        CREATE TABLE if not exists `%s` (
          `id` bigint not null auto_increment,
          `user_id` bigint not null,
          `ip` varchar(100) NOT NULL,
          `domain` varchar(100) NOT NULL,
          `timestamp` bigint(24) not null,
          `total_time` smallint NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8
        ''' % table_name
        try:
            cursor = _['connection'].cursor()
            cursor.execute(sql)
            cursor.close()
            return table_name
        except Exception as e:
            self.logger.error("create table error: %s" % e)
            # print sql
            raise
            # if self.connection.reconn():
            #     # self.create_table()
            #
            # else:
            #     self.logger.error("reconnection mysql failed")
    @add_executor_param
    @run_on_executor
    @get_and_return_connection
    def insert_table(self, timestamp, user_id, ip, domains, **_):
        db_conn = _.get('connection')
        if db_conn is None:
            return
        table, date_str = self.gen_table(timestamp)
        if not self.redis.get_last_table(date_str):
            print "creating table"
            table = self.create_table(table)
            if table:
                self.redis.set_last_table(date_str)

        sql = "insert into %s (user_id,ip,timestamp,total_time,domain) values(%s,%s,%s,%s,%s);" % \
              (table, '%s', '%s', '%s', '%s', '%s')
        print sql
        try:
            cursor = db_conn.cursor()
            args = [(user_id, ip, timestamp, total_time, domain) for domain, total_time in domains.iteritems()]
            cursor.executemany(sql, args)

            # self.redis.add_mysql_table(date_str)
            cursor.close()
        except Exception as e:
            self.logger.error(e)
            raise

        else:
            return True

    @run_on_executor
    @check_key_exists
    @get_and_return_connection
    def select(self, timestamp, sql, params, **_):
        cursor = _['connection'].cursor()
        cursor.execute(sql, params)
        cursor.close()
        return self.cursor.fetchmany()

    @run_on_executor
    @check_key_exists
    @get_and_return_connection
    def day_avg_time(self, user_id, timestamp=None, **_):
        #TODO find table name in redis, if not found return false
        sql = '''
            select avg(total_time) from %s where user_id = %s
        '''
        cursor = _['connection'].cursor()
        cursor.execute(sql, (_['table'], user_id))
        cursor.close()
        return self.cursor.fetchone()

    def __getattr__(self, item):
        return self.connection.__getattribute__(item)
class SecuritySystem:

  CHECK_INTERVAL = 0.01
  THREADS = []
  CODE = 1234

  def __init__(self):
    self.pir = MyPiPIR(MyPiPIR.DEFAULT)
    self.led = MyPiLed(MyPiLed.RED)
    self.buzzer = MyPiBuzzer(MyPiBuzzer.DEFAULT)
    self.locks = []
    self.tries = 0
    self.max_tries = 3
    self.locks.append(Lock('Vault'))
    
    self.logger = MyLogger("SecuritySystem")
    self.check_interval = self.__class__.CHECK_INTERVAL
    self.enabled = False

  def __check_code(self):
    while self.tries <= self.max_tries:
      code = input("Enter security system code (Tries: " + str(self.max_tries - self.tries) + "): ")
      if str(code) == str(self.__class__.CODE):
        return True
      else:
        self.tries+=1

    self.logger.warn("Code entered incorrectly " + str(self.max_tries) + " times")
    self.buzzer.on()
    return False
      

  # Public implementation (non-blocking)
  def enable(self):
    if self.__check_code():
      self.lockdown()
      if len(self.__class__.THREADS) == 0:
        self.enabled = True
        t = threading.Thread(target=self.__enable)
        t.start()
        self.__class__.THREADS.append(t)
        return t
      else:
        self.logger.warn("Security already active")
        return self.__class__THREADS[0]
    
  # Private implementation (blocking)
  def __enable(self):
    while self.enabled == True:
      state = self.pir.state()
      if state == MyPiPIR.ACTIVATED:
        self.logger.warn("Motion detected!")
        self.buzzer.on()
        self.led.blink(5,0.2)
        time.sleep(1)
      elif state == MyPiPIR.DEACTIVATED:
        self.logger.info("Waiting for motion...")
        self.led.off()
        self.buzzer.off()
      elif state == MyPiPIR.ACTIVE:
        self.logger.warn("Motion still being detected!")
        self.led.blink(5,0.2)
        self.buzzer.on()
        time.sleep(1)
      elif state == MyPiPIR.INACTIVE:
        self.led.off()
        self.buzzer.off()

      time.sleep(self.check_interval)

  # Disable the security system, wait for threads to finish
  def disable(self):
    if self.__check_code():
      self.enabled = False
      self.end_lockdown()
    for t in self.__class__.THREADS:
      t.join()


  def lockdown(self):
    for lock in self.locks:
      lock.lock()

  def end_lockdown(self):
    for lock in self.locks:
      lock.unlock()
import time
import RPi.GPIO as GPIO
from security_system import SecuritySystem
from my_logger import MyLogger

try:
  logger = MyLogger("SecurityTester")
  logger.info("Started security system test")
  security_system = SecuritySystem()
  logger.info("Security system enabled")
  security_system.enable()

  for i in range(10):
    logger.info("Active for " + str(10-i) + " more seconds")
    time.sleep(1)


  security_system.disable()
  logger.info("Security system disabled")

except KeyboardInterrupt:
  logger.info("Quit!")
  if security_system.enabled:
    security_system.disable()

finally:
  GPIO.cleanup()

Exemplo n.º 36
0
 def __init__(self, name):
   self.name = name
   self.motor = MyPiStepperMotor(MyPiStepperMotor.DEFAULT)
   self.logger = MyLogger('Lock')
Exemplo n.º 37
0
 def __init__(self, redis):
     self.connection = MySQLConnection()
     self.logger = MyLogger().logger
     self.redis = redis
     self.executor = ThreadPoolExecutor(conf.THREAD_NUM)
Exemplo n.º 38
0
import time
import RPi.GPIO as GPIO

from pir import MyPiPIR
from led import MyPiLed
from buzzer import MyPiBuzzer
from my_logger import MyLogger

logger = MyLogger("PIR")
logger.debug("PIR Module Test (Ctrl-C to exit)")

pir1 = MyPiPIR(MyPiPIR.DEFAULT)
led1 = MyPiLed(MyPiLed.RED)
buzzer1 = MyPiBuzzer(MyPiBuzzer.DEFAULT)

check_interval = 0.01

try:
  logger.info("Ready!")

  while True:
    state = pir1.state()
    if state == MyPiPIR.ACTIVATED:
      logger.warn("Motion detected!")
      buzzer1.on()
      led1.blink(5,0.2)
      time.sleep(1)
    elif state == MyPiPIR.DEACTIVATED:
      logger.info("Waiting for motion...")
      led1.off()
      buzzer1.off()