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)
Exemple #2
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)
Exemple #3
0
class Game:
    Directions = {
        "north": (0, -1),
        "south": (0, 1),
        "west": (-1, 0),
        "east": (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)

    def _move(self, x, y):
        new_room = self._get_room(x, y)
        if new_room:
            self.current_room = new_room
            self.player_x += x
            self.player_y += y
            self.log.info(f'New player_x = {self.player_x},'
                          f'player_y = {self.player_y}')
            self._look_at(self.current_room)
        else:
            print('Error: missing room')

    def _get_room(self, x, y):
        x += self.player_x
        y += self.player_y
        coords = (x, y)
        room = self.map.get(coords)
        if room:
            self.log.info(f'Get room {room.name}')
        else:
            self.log.warning(f'No room with coords {coords}')
        return room

    @staticmethod
    def _look_at(obj):
        print(obj)

    def _parse(self, in_str):
        in_str = in_str.lower()
        if in_str.startswith('go '):
            direction = in_str[3:]
            self.log.info(f'Direction - {direction}')
            if self.current_room._check_exit(direction):
                new_coords = self.Directions[direction]
                self._move(*new_coords)
            else:
                self.log.warning(
                    f'No exit "{direction}" in {self.current_room}')
        else:
            self.log.warning(f'User enter "{in_str}" != startwith "go "')

    def run(self):
        while True:
            action = input('>>> ')
            self.log.info(f'User enter "{action}". ')
            self._parse(action)
Exemple #4
0
class Application(Application_ui):
    #这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。
    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

    def start_study(self, event=None):
        self.init_start_thread_ifnot()
        if self.t1.is_alive():
            self.logger.info('请不要重复学习')
            return
        try:
            self.t1.start()
        except:
            self.init_start_thread()
            self.t1.start()
        self.logger.info('已开始学习')
        pass

    def init_start_thread_ifnot(self):
        if self.t1 is None:
            self.init_start_thread()

    def init_start_thread(self):
        self.t1 = threading.Thread(target=self.learn.open_main_page)
        self.t1.daemon = True

    last_stop_time = None

    def do_stop_study(self):
        try:
            self.learn.browser.quit()
        except:
            self.logger.info('停止失败!,请重新停止')

        self.logger.info('已停止学习')

    def stop_study(self, event=None):
        if self.last_stop_time is not None:
            if (time.time() - self.last_stop_time) < 10:
                self.logger.info('太快了,请10秒后在点击')
                return
        if self.t1.is_alive() is False:
            self.logger.info('您没有在学习')
            return
        self.last_stop_time = time.time()
        self.logger.info('正在停止学习')
        close_t = threading.Thread(target=self.do_stop_study)
        close_t.daemon = True
        close_t.start()
        pass

    def clear_log_Cmd(self, event=None):
        self.log_board.config(state=NORMAL)
        self.log_board.delete('1.0', END)
        pass
    }
    # url_resp = urllib.request.urlopen(req)
    url_resp = get(url=file_url, headers=headers)
    file_name = get_filename_from_cd(
        url_resp.headers.get('content-disposition'))
    # content_type = url_resp.getheader('Content-type')
    # guess_type = mimetypes.guess_extension(content_type).strip('.')
    # url_content = url_resp.read()
    # create file locally
    if not path.exists(UPLOAD_FOLDER) or not path.isdir(UPLOAD_FOLDER):
        makedirs(UPLOAD_FOLDER)

    file_path = path.join(UPLOAD_FOLDER, file_name)
    with open(file_path, "wb") as _file:
        _file.write(url_resp.content)

    return file_path


####################################################################
#       MAIN                                                       #
####################################################################
if __name__ == "__main__":
    log.info("App started. Check for resume...")
    # sys_params = sys.argv[1:]
    sys_params = [
        'firmajr://007341CA-71B5-B66D-EC22-46185A0335F0;105;false;aHR0cHM6Ly9nZG1sLmludGVybmFsLmF1c2wuYm9sb2duYS5pdC9jZXJ0X3Jldm9jYXRpb25fY2hlY2tlci9zaWduQ29uZmlndXJhdGlvbg==/'
    ]
    handle_sign(sys_params)
    log.info("closing app")
Exemple #6
0
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()
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()

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()
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()
        elif state == MyPiPIR.ACTIVE:
            logger.warn("Motion still being detected!")
            led1.blink(5, 0.2)
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()
    elif state == MyPiPIR.ACTIVE:
      logger.warn("Motion still being detected!")
      led1.blink(5,0.2)