def test_invalid_json_action(): input1 = {"act": "jump", "time": 100} input1_json = json.dumps(input1) actions = Actions(conn) with pytest.raises(KeyError): actions.add_action(input1_json)
def __init__(self, rbc, kb, vision_display=False, socket=False): self.rbc = rbc self.kb = kb self.vision_display = vision_display self.socket = socket if self.socket: self._socket_connect() self.tasks = Tasks(self.rbc, self.socket, self.vision_display) self.actions = Actions(self.rbc)
def test_add_jump_action(): input1 = {"action": "jump", "time": 100} input1_json = json.dumps(input1) actions = Actions(conn) actions.add_action(input1_json) cur.execute("select count(*) from actions") result = cur.fetchone() count = result[0] assert count == 1
def __init__(self, drawer): """Initialization commands class.""" self.drawer = drawer self.phrases = self.drawer.phrases self.message = Message(self.drawer) self.notes = Notes(self.message, self.phrases) self.config = self.drawer.config self.config.checker(self.message, self.phrases) self.tree = Tree() self.actions = Actions(self.tree, self.notes) self.set_window()
def __init__(self, rbc, url, socket, vision_display = False): self.rbc = rbc self.vision_display = vision_display self.socket = socket if self.socket: self._socket_connect() self.tasks = Tasks(self.rbc, self.socket, self.vision_display) self.actions = Actions(self.rbc) websocket.enableTrace(False) self.ws = websocket.WebSocketApp(url, on_message = lambda ws, msg: self.on_command(ws, msg), on_open = lambda ws: self.on_open(ws), on_error = lambda ws, msg: self.on_error(ws, msg), on_close = lambda ws: self.on_close(ws)) _thread.start_new_thread(self.ws.run_forever,())
def test_get_stats(): input1 = {"action": "jump", "time": 100} input1_json = json.dumps(input1) input2 = {"action": "run", "time": 75} input2_json = json.dumps(input2) input3 = {"action": "jump", "time": 200} input3_json = json.dumps(input3) actions = Actions(conn) actions.add_action(input1_json) actions.add_action(input2_json) actions.add_action(input3_json) results_json = actions.get_stats() results = json.loads(results_json) jump_dict = list(filter(lambda dict: dict["action"] == "jump", results))[0] run_dict = list(filter(lambda dict: dict["action"] == "run", results))[0] assert jump_dict["avg"] == 150 assert run_dict["avg"] == 75
class RobotController: is_manual = True current_task = tc.NONE current_action = ac.NONE current_command = 'NONE' previous_command = 'NONE' additional_command = 'NONE' def __init__(self, rbc, url, socket, vision_display=False): self.rbc = rbc self.vision_display = vision_display self.socket = socket if self.socket: self._socket_connect() self.tasks = Tasks(self.rbc, self.socket, self.vision_display) self.actions = Actions(self.rbc) websocket.enableTrace(False) self.ws = websocket.WebSocketApp( url, on_message=lambda ws, msg: self.on_command(ws, msg), on_open=lambda ws: self.on_open(ws), on_error=lambda ws, msg: self.on_error(ws, msg), on_close=lambda ws: self.on_close(ws)) _thread.start_new_thread(self.ws.run_forever, ()) def on_command(self, ws, message): self.current_command = json.loads(message)['command'] def on_open(self, ws): print("### Connected ###") def on_error(self, ws, msg): print("an error has occured") def on_close(self, ws): print("closing...") """ Main Update Logic for the Robot """ def Update(self): # Refresh vision_display if defined if self.vision_display: self.vision_display.refresh(self.rbc.Camera.getImageArray()) # Auto reconnect socket if connection has been lost self._socket_connect() self._handle_command() self._handle_additional_commands() self.previous_command = self.current_command # Action has priority over Task if self.hasAction(): if self.actions.execAction(self.current_action): self.switchAction(ac.NONE) self.actions.resetAllActions() elif self.hasTask(): if self.tasks.execTask(self.current_task, self.additional_command): self.switchTask(tc.NONE) self.tasks.resetAllActions() def hasTask(self): return self.current_task is not tc.NONE def hasAction(self): return self.current_action is not ac.NONE def switchTask(self, task): if self.current_task is task: return if task not in [t for t in tc]: return if task == tc.NONE: self.tasks.forceStop() self.rbc.idle() self.tasks.resetAllActions() self.current_task = task self.disableManual() self._socket_send( Constants.JSON_PREFIX.format( '{', TaskCodes.translateTaskToString(self.current_task), '', '', '', '}')) print('Changed Current Task to: "{}"'.format( TaskCodes.translateTaskToString(self.current_task))) def _handle_additional_commands(self): if self.current_command in ["HEARTS", "CLUBS", "DIAMONDS", "SPADES"]: self.additional_command = self.current_command return self.additional_command = "NONE" def switchAction(self, action): if self.current_action is action: return if action not in [t for t in ac]: return if action == ac.NONE: self.actions.forceStop() self.rbc.idle() self.actions.resetAllActions() self.current_action = action self.disableManual() print('Changed Current Action to: "{}"'.format( ActionCodes.translateActionToString(self.current_action))) def toggleManual(self): if self.is_manual is True: self.disableManual() return self.enableManual() def enableManual(self): if self.is_manual: return #if self.current_task is not tc.NONE: # self.switchTask(tc.NONE) self.is_manual = True print('Manual Controls Enabled') def disableManual(self): if not self.is_manual: return self.is_manual = False print('Manual Controls Disabled') def _socket_send(self, json_string): if not self.socket or not self.socket.isConnected(): return self.socket.send(json_string) def _socket_connect(self): if not self.socket or self.socket.isConnected(): return self.socket.connect() # Default method for switch case, leave empty def _Default(self): pass def _handle_command(self): self.rbc.resetWheelVelocity() self._handle_continuous_command() self._handle_speed_change() #if prev != current then toggle else don't toggle if (self.previous_command != self.current_command): self._handle_toggle_command() def _handle_continuous_command(self): { 'GO_FORWARDS': partial(self.rbc.goStraight, self.rbc.wheel_motor_velocity), 'TURN_ON_SPOT_LEFT': partial(self.rbc.turnOnSpot, self.rbc.wheel_motor_velocity * -1), 'GO_BACKWARDS': partial(self.rbc.goStraight, self.rbc.wheel_motor_velocity * -1), 'TURN_ON_SPOT_RIGHT': partial(self.rbc.turnOnSpot, self.rbc.wheel_motor_velocity), 'FORWARD_TURN_LEFT': partial(self.rbc.turnLeft, self.rbc.wheel_motor_velocity), 'FORWARD_TURN_RIGHT': partial(self.rbc.turnRight, self.rbc.wheel_motor_velocity), 'BACKWARD_TURN_RIGHT': partial(self.rbc.turnLeft, self.rbc.wheel_motor_velocity * -1), 'BACKWARD_TURN_LEFT': partial(self.rbc.turnRight, self.rbc.wheel_motor_velocity * -1), }.get(self.current_command, lambda: self.default)() def _handle_toggle_command(self): { 'CLEAR_ACTION': partial(self.switchAction, ac.NONE), 'TOGGLE_ACTION_GRABARM_GRAB_OBJECT': partial(self.switchAction, ac.GRAB_OBJECT), 'TOGGLE_ACTION_GRABARM_WEIGH_OBJECT': partial(self.switchAction, ac.WEIGH_OBJECT), 'TOGGLE_ACTION_GRABARM_DEPOSIT_OBJECT': partial(self.switchAction, ac.DEPOSIT_OBJECT), 'TOGGLE_ACTION_COLLECT_MINERAL': partial(self.switchAction, ac.COLLECT_MINERAL), 'RETRACT_GRABARM': partial(self.rbc.GrabArmMotors.retract), 'RESET_ARM': partial(self.rbc.GrabArmMotors.idle), 'TOGGLE_MANUAL': partial(self.toggleManual), 'CLEAR_TASK': partial(self.switchTask, tc.NONE), 'TOGGLE_TASK_SCAN_QR_CODE': partial(self.switchTask, tc.SCAN_QR_CODE), 'TOGGLE_TASK_FIND_CARD_SYMBOL': partial(self.switchTask, tc.FIND_CARD_SYMBOL), 'TOGGLE_TASK_RECOGNIZE_TEMPERATURE': partial(self.switchTask, tc.MEASURE_TEMP_OF_WATER_SOURCE), 'TOGGLE_TASK_DANCING_ON_THE_MOON': partial(self.switchTask, tc.DANCING_ON_THE_MOON), 'TOGGLE_TASK_MOON_MAZE': partial(self.switchTask, tc.MOON_MAZE), 'TOGGLE_TASK_MINERAL_ANALYSIS': partial(self.switchTask, tc.MINERAL_ANALYSIS), 'TOGGLE_TASK_MOON_WALK': partial(self.switchTask, tc.MOON_WALK), 'TOGGLE_TASK_MOON_SURVIVAL': partial(self.switchTask, tc.MOON_SURVIVAL), }.get(self.current_command, lambda: self.default)() def _handle_speed_change(self): for i in range(1, 11): if 'SPEED_{}'.format(i) == self.current_command: self.rbc.setWheelMotorVelocity( (self.rbc.MAX_WHEEL_VELOCITY / 10) * i) break def default(self): return
def setup_ui(self): self.setObjectName("self") self.setFixedSize(287, 235) self.actionsMenu = Actions() self.default = DefaultSettings self.cs = CameraSettings() self.path = "" # Gain: self.selfLayoutWidget = QtWidgets.QWidget(self) self.selfLayoutWidget.setGeometry(QtCore.QRect(10, 10, 271, 221)) self.selfLayoutWidget.setObjectName("selfLayoutWidget") self.selfLayout = QtWidgets.QFormLayout(self.selfLayoutWidget) self.selfLayout.setContentsMargins(0, 0, 0, 0) self.selfLayout.setObjectName("selfLayout") self.label = QtWidgets.QLabel(self.selfLayoutWidget) self.label.setObjectName("label") self.selfLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label) self.comboBox = QtWidgets.QComboBox(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth()) self.comboBox.setSizePolicy(sizePolicy) self.comboBox.setObjectName("comboBox") # TODO ?(x2, x4, x8)? self.comboBox.addItems([self.tr("1"), self.tr("2"), self.tr("4")]) self.comboBox.setCurrentIndex(int(self.cs.gain)) # Gain ''' Gain/Temperature ''' # Temperature: self.selfLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.comboBox) self.label_2 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_2.setObjectName("label_2") self.selfLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth()) self.lineEdit.setSizePolicy(sizePolicy) self.lineEdit.setObjectName("lineEdit") self.lineEdit.setValidator(QtGui.QIntValidator(-70, 25)) self.lineEdit.setText(self.cs.temp) # Temperature ''' Temperature/Shooting Time ''' # Shooting Time: self.selfLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit) self.label_3 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_3.setObjectName("label_3") self.selfLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3) self.lineEdit_2 = QtWidgets.QLineEdit(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth()) self.lineEdit_2.setSizePolicy(sizePolicy) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_2.setValidator(QtGui.QIntValidator(60, 600)) self.lineEdit_2.setText(self.cs.time_shooting) # Shooting Time ''' Shooting Time/Time Between Images ''' # Time Between Images: self.selfLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2) self.label_4 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_4.setObjectName("label_4") self.selfLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_4) self.lineEdit_3 = QtWidgets.QLineEdit(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth()) self.lineEdit_3.setSizePolicy(sizePolicy) self.lineEdit_3.setObjectName("lineEdit_3") self.lineEdit_3.setValidator(QtGui.QIntValidator(5, 60)) self.lineEdit_3.setText(self.cs.acq_wait) # Time Between Images ''' Time Between Images/Binning ''' # Binning: self.selfLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.lineEdit_3) self.label_5 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_5.setObjectName("label_5") self.selfLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_5) self.comboBox_2 = QtWidgets.QComboBox(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().hasHeightForWidth()) self.comboBox_2.setSizePolicy(sizePolicy) self.comboBox_2.setCurrentText("") self.comboBox_2.setMinimumContentsLength(0) self.comboBox_2.setObjectName("comboBox_2") self.comboBox_2.addItems([self.tr("1x1"), self.tr("2x2"), self.tr("4x4")]) self.comboBox_2.setCurrentIndex(int(self.cs.binning)) # Binning ''' Binning/Exposure Time ''' # Exposure Time: self.selfLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.comboBox_2) self.label_6 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_6.setObjectName("label_6") self.selfLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_6) self.lineEdit_4 = QtWidgets.QLineEdit(self.selfLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEdit_4.sizePolicy().hasHeightForWidth()) self.lineEdit_4.setSizePolicy(sizePolicy) self.lineEdit_4.setObjectName("lineEdit_4") self.lineEdit_4.setValidator(QtGui.QIntValidator(5, 60)) self.lineEdit_4.setText(self.cs.exp) # Exposure Time ''' Exposure Time/Images Path ''' # Images Path: self.selfLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.lineEdit_4) self.label_7 = QtWidgets.QLabel(self.selfLayoutWidget) self.label_7.setObjectName("label_7") self.selfLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.label_7) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.lineEdit_5 = QtWidgets.QLineEdit(self.selfLayoutWidget) self.lineEdit_5.setObjectName("lineEdit_5") self.lineEdit_5.setText(self.cs.path) self.lineEdit_5.setReadOnly(True) self.horizontalLayout.addWidget(self.lineEdit_5) self.toolButton = QtWidgets.QToolButton(self.selfLayoutWidget) self.toolButton.setObjectName("toolButton") self.horizontalLayout.addWidget(self.toolButton) self.toolButton.clicked.connect(self.get_dir) self.selfLayout.setLayout(6, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout) # Images Path ''' Images Path/Buttons ''' # Buttons: self.buttonBox = QtWidgets.QDialogButtonBox(self.selfLayoutWidget) self.buttonBox.addButton("Defaults", QtWidgets.QDialogButtonBox.RejectRole) self.buttonBox.addButton("Save", QtWidgets.QDialogButtonBox.AcceptRole) self.buttonBox.setCenterButtons(True) self.buttonBox.setObjectName("buttonBox") # self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText("Save") # self.buttonBox.button(QtWidgets.QDialogButtonBox.RejectRole).setText("Defaults") self.selfLayout.setWidget(7, QtWidgets.QFormLayout.SpanningRole, self.buttonBox) # self.buttonBox.clicked(QAbstractButton=QtWidgets.QDialogButtonBox.Save).connect(self.save_settings) self.buttonBox.accepted.connect(self.save_settings) self.buttonBox.rejected.connect(self.defaults) # self.buttonBox.clicked(QAbstractButton=QtWidgets.QDialogButtonBox.RestoreDefaults).connect(self.defaults) self.retranslate_ui() QtCore.QMetaObject.connectSlotsByName(self) self.show()
def setUp(self): self.actions=Actions() SQL="update account_fund set balance='10000',frozen_amount='0',daily_balance='0',daily_frozen_amount='0' where account_id='105372'" self.actions.conn(SQL)
class TestCases(unittest.TestCase): def setUp(self): self.actions=Actions() SQL="update account_fund set balance='10000',frozen_amount='0',daily_balance='0',daily_frozen_amount='0' where account_id='105372'" self.actions.conn(SQL) def tearDown(self): pass def test_001(self): u"""账户资金增加""" response=self.actions.sendRequest("dilipay.account.add.balance") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_002(self): u"""自助圈提-创建圈提记录""" response=self.actions.sendRequest("dilipay.trade.create.unload") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_003(self): u"""圈提""" response=self.actions.sendRequest("dilipay.trade.create.withdraw") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_004(self): u"""创建圈存记录""" response=self.actions.sendRequest("dilipay.trade.create.predeposit") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_005(self): u"""资金账户注册""" #电话号码重复 response=self.actions.sendRequest("dilipay.account.info.register") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_006(self): u"""现金充值交易支付""" response=self.actions.sendRequest("dilipay.trade.pay") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_007(self): u"""现金充值交易创建""" response=self.actions.sendRequest("dilipay.trade.create.deposit") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_008(self): u"""现金提现""" response=self.actions.sendRequest("dilipay.trade.withdraw.cash") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_009(self): u"""统一账号身份认证""" response=self.actions.sendRequest("dilipay.account.secured.auth") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_010(self): u"""自动圈提确认""" response=self.actions.sendRequest("dilipay.account.balance.unload") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_011(self): u"""创建圈提记录""" response=self.actions.sendRequest("dilipay.trade.create.unload") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_012(self): u"""获取账户信息""" response=self.actions.sendRequest("dilipay.account.info.get") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_013(self): u"""获取账户可用余额""" response=self.actions.sendRequest("dilipay.account.balance.get") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_014(self): u"""解冻账号""" response=self.actions.sendRequest("dilipay.account.status.unfreeze") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_015(self): u"""冻结账号资金""" response=self.actions.sendRequest("dilipay.account.fund.freeze") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_016(self): u"""解冻账号资金""" response=self.actions.sendRequest("dilipay.account.fund.unfreeze") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_017(self): u"""账号冻结资金明细查询""" response=self.actions.sendRequest("dilipay.account.fund.freeze.list") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_018(self): u"""清除支付密码错误次数""" response=self.actions.sendRequest("dilipay.password.limit.clear") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_019(self): u"""批量解冻账号资金""" response=self.actions.sendRequest("dilipay.account.fund.unfreeze.batch") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name) def test_020(self): u"""创建及时到账交易""" response=self.actions.sendRequest("dilipay.trade.create.direct") flag=self.actions.verifyResult(response) self.assertEqual(True, flag, u'接口测试失败:'+sys._getframe().f_code.co_name)
class RobotController: CURLY_BRACKET_OPEN = '{' CURLY_BRACKET_CLOSE = '}' # Prevents toggled actions from taking place multiple times in one key press TOGGLE_TIMEOUT = 42 toggle_timeout_count = TOGGLE_TIMEOUT manual_wheel_velocity = 5 is_manual = True current_task = tc.NONE current_action = ac.NONE def __init__(self, rbc, kb, vision_display=False, socket=False): self.rbc = rbc self.kb = kb self.vision_display = vision_display self.socket = socket if self.socket: self._socket_connect() self.tasks = Tasks(self.rbc, self.socket, self.vision_display) self.actions = Actions(self.rbc) """ Main Update Logic for the Robot """ def Update(self): if self.vision_display: self.vision_display.refresh(self.rbc.Camera.getImageArray()) # Auto reconnect socket if connection has been lost self._socket_connect() # Handle User Input self._handleUserInput() # Action has priority over Task if self.hasAction(): if self.actions.execAction(self.current_action): self.switchAction(ac.NONE) self.actions.resetAllActions() elif self.hasTask(): if self.tasks.execTask(self.current_task): self.switchTask(tc.NONE) self.tasks.resetAllActions() def hasTask(self): return self.current_task is not tc.NONE def hasAction(self): return self.current_action is not ac.NONE def switchTask(self, task): if self.current_task is task: return if task not in [t for t in tc]: return if task == tc.NONE: self.tasks.forceStop() self.rbc.idle() self.tasks.resetAllActions() self.current_task = task self.disableManual() self._socket_send( Constants.JSON_PREFIX.format( self.CURLY_BRACKET_OPEN, TaskCodes.translateTaskToString(self.current_task), '', '', '', self.CURLY_BRACKET_CLOSE)) print('Changed Current Task to: "{}"'.format( TaskCodes.translateTaskToString(self.current_task))) def switchAction(self, action): if self.current_action is action: return if action not in [t for t in ac]: return if action == ac.NONE: self.actions.forceStop() self.rbc.idle() self.actions.resetAllActions() self.current_action = action self.disableManual() ### TODO: Send to Website through Socket (as JSON) ### print('Changed Current Action to: "{}"'.format( ActionCodes.translateActionToString(self.current_action))) def toggleManual(self): if self.is_manual is True: self.disableManual() return self.enableManual() def enableManual(self): if self.is_manual: return if self.current_task is not tc.NONE: self.switchTask(tc.NONE) self.is_manual = True print('Manual Controls Enabled') def disableManual(self): if not self.is_manual: return self.is_manual = False print('Manual Controls Disabled') def _socket_send(self, json_string): if not self.socket or not self.socket.isConnected(): return self.socket.send(json_string) def _socket_connect(self): if not self.socket or self.socket.isConnected(): return self.socket.connect() def _handleUserInput(self): self.rbc.keys = self._getActiveKeys() # Reset robot movement self.rbc.resetWheelVelocity() if self._handleToggledInput(self.rbc.keys): self.toggle_timeout_count = 0 return self._handleContinuousInput(self.rbc.keys) def _getActiveKeys(self): # Get list of all pressed keys keys = [] while True: key = self.kb.getKey() if key is -1: break keys.append(key) return keys def _handleToggledInput(self, keys): if self.toggle_timeout_count < self.TOGGLE_TIMEOUT: self.toggle_timeout_count += 1 return False # Handle Single Input Event (return if handled) if self._handleSingleInput(keys): return True # Handle Dual Input Event (return if handled) if self._handleDualInput(keys): return True return False def _handleContinuousInput(self, keys): # Handle manual movement self._handleManualMovement(keys) def _handleManualMovement(self, keys): """ Manual Movement (needs to be enabled) """ if self.is_manual: # Set manual velocity wheels self._handleManualWheelSpeedChange(keys) # Set manual velocity grabarm self._handleManualArmSpeedChange(keys) self._handleManualGrabberSpeedChange(keys) # Handle manual wheel movement self._handleManualWheelsMovement(keys) # Handle manual grabarm movement self._handleManualGrabArmMovement(keys) def _handleManualWheelSpeedChange(self, keys): movement = False option = False for key in keys: if key in kc.WHEEL_MOVEMENT_KEYS: movement = key if key in kc.SPEED_OPTIONS: velocity_step = math.floor(self.rbc.MAX_WHEEL_VELOCITY / 10) option = int( chr(key)) * velocity_step if key != ord('0') else int( 10 * velocity_step) if not movement or not option: continue self.rbc.setWheelMotorVelocity(option) break def _handleManualArmSpeedChange(self, keys): movement = False option = False for key in keys: if key in kc.ARM_MOVEMENT_KEYS: movement = key if key in kc.SPEED_OPTIONS: velocity_step = math.floor(self.rbc.MAX_ARM_VELOCITY / 10) option = int(chr(key) * velocity_step) if key != ord('0') else int( 10 * velocity_step) if not movement or not option: continue self.rbc.GrabArmMotors.arm.setVelocity(option) break def _handleManualGrabberSpeedChange(self, keys): movement = False option = False for key in keys: if key in kc.GRABBER_MOVEMENT_KEYS: movement = key if key in kc.SPEED_OPTIONS: velocity_step = math.floor(self.rbc.MAX_GRABBER_VELOCITY / 10) option = int(chr(key) * velocity_step) if key != ord('0') else int( 10 * velocity_step) if not movement or not option: continue self.rbc.GrabArmMotors.grabber.setVelocity(option) break def _handleSingleInput(self, keys): # Return if not only one input if len(keys) is not 1: return False key = keys[0] # Toggle Manual if kc.TOGGLE_MANUAL_KEY == key: self.toggleManual() return True # Retract Arm if kc.GRABARM_RETRACT_KEY == key: self.rbc.GrabArmMotors.retract() return True if kc.RESET_ARM_KEY == key: self.rbc.GrabArmMotors.idle() return True if key in kc.TOGGLE_ACTION_KEYS: { kc.CLEAR_ACTION: partial(self.switchAction, ac.NONE), kc.TOGGLE_ACTION_GRABARM_GRAB_OBJECT_KEY: partial(self.switchAction, ac.GRAB_OBJECT), kc.TOGGLE_ACTION_GRABARM_WEIGH_OBJECT_KEY: partial(self.switchAction, ac.WEIGH_OBJECT), kc.TOGGLE_ACTION_GRABARM_DEPOSIT_OBJECT_KEY: partial(self.switchAction, ac.DEPOSIT_OBJECT), kc.TOGGLE_ACTION_COLLECT_MINERAL_KEY: partial(self.switchAction, ac.COLLECT_MINERAL) }.get(key, lambda: self._Default)() return True # Task toggles (0-9, starts with '1', ends at '0') # '-' clears current task if key in kc.TOGGLE_TASK_KEYS: { kc.CLEAR_TASK_KEY: partial(self.switchTask, tc.NONE), kc.TOGGLE_TASK_DANCING_ON_THE_MOON_KEY: partial(self.switchTask, tc.DANCING_ON_THE_MOON), kc.TOGGLE_TASK_MOON_MAZE_KEY: partial(self.switchTask, tc.MOON_MAZE), kc.TOGGLE_TASK_MOON_SURVIVAL_KEY: partial(self.switchTask, tc.MOON_SURVIVIVAL), kc.TOGGLE_TASK_FIND_CARD_SYMBOL_KEY: partial(self.switchTask, tc.FIND_CARD_SYMBOL), kc.TOGGLE_TASK_MEASURE_TEMP_OF_WATER_SOURCE_KEY: partial(self.switchTask, tc.MEASURE_TEMP_OF_WATER_SOURCE), kc.TOGGLE_TASK_SCAN_QR_CODE_KEY: partial(self.switchTask, tc.SCAN_QR_CODE), kc.TOGGLE_TASK_MINERAL_ANALYSIS_KEY: partial(self.switchTask, tc.MINERAL_ANALYSIS) }.get(key, lambda: self._Default)() return True return False def _handleDualInput(self, keys): # Return if not only two inputs if len(keys) is not 2: return False return False def _handleManualWheelsMovement(self, keys): # STRAFING if kc.FORWARD_KEY in keys and kc.LEFT_KEY in keys: self.rbc.turnLeft(self.rbc.wheel_motor_velocity) return if kc.FORWARD_KEY in keys and kc.RIGHT_KEY in keys: self.rbc.turnRight(self.rbc.wheel_motor_velocity) return if kc.BACKWARD_KEY in keys and kc.LEFT_KEY in keys: self.rbc.turnRight(self.rbc.wheel_motor_velocity * -1) return if kc.BACKWARD_KEY in keys and kc.RIGHT_KEY in keys: self.rbc.turnLeft(self.rbc.wheel_motor_velocity * -1) return # ON POSITION if kc.FORWARD_KEY in keys: self.rbc.goStraight(self.rbc.wheel_motor_velocity) return if kc.BACKWARD_KEY in keys: self.rbc.goStraight(self.rbc.wheel_motor_velocity * -1) return if kc.LEFT_KEY in keys: self.rbc.turnOnSpot(self.rbc.wheel_motor_velocity * -1) return if kc.RIGHT_KEY in keys: self.rbc.turnOnSpot(self.rbc.wheel_motor_velocity) return def _handleManualGrabArmMovement(self, keys): # Arm if kc.ARM_EXTEND_KEY in keys: self.rbc.GrabArmMotors.arm.moveArmForwards() elif kc.ARM_RETRACT_KEY in keys: self.rbc.GrabArmMotors.arm.moveArmBackwards() # Grabber if kc.GRABBER_OPEN_KEY in keys: self.rbc.GrabArmMotors.grabber.continuousOpen() elif kc.GRABBER_CLOSE_KEY in keys: self.rbc.GrabArmMotors.grabber.continuousClose() # Default method for switch case, leave empty def _Default(self): pass
def setup_ui(self): self.settings = UiSelf() self.actionsMenu = Actions() # self.actionsMenu.signal_console.connect(self.write_to_console) self.console = ConsoleThreadOutput() self.setObjectName("self") self.setFixedSize(500, 268) size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setWindowTitle("CCD Controller 3.0.0 (Pixis)") self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit.setEnabled(True) font = QtGui.QFont() if os.name == "nt": font.setFamily("Terminal") font.setPointSize(11) else: font.setFamily("Noto") font.setPointSize(11) self.plainTextEdit.setFont(font) self.plainTextEdit.viewport().setProperty( "cursor", QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.plainTextEdit.setFocusPolicy(QtCore.Qt.NoFocus) self.plainTextEdit.setToolTip("") self.plainTextEdit.setStatusTip("") self.plainTextEdit.setWhatsThis("") self.plainTextEdit.setAccessibleName("") self.plainTextEdit.setAccessibleDescription("") # color: rgb(0, 255, 0) self.plainTextEdit.setStyleSheet( "color: green; background-color: rgb(0, 0, 0);") self.plainTextEdit.setPlainText("") self.plainTextEdit.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) self.plainTextEdit.setObjectName("plainTextEdit") self.console.set_console(self.plainTextEdit) self.verticalLayout.addWidget(self.plainTextEdit) self.setCentralWidget(self.centralwidget) self.toolBar = QtWidgets.QToolBar(self) self.toolBar.setMovable(False) self.toolBar.setIconSize(QtCore.QSize(48, 48)) self.toolBar.setObjectName("toolBar") self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) if os.name == "nt": dir_orientation = os.getcwd() + "\\ui\\icons\\" else: dir_orientation = os.getcwd() + "/ui/icons/" self.actionConnect = QtWidgets.QAction(self) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(dir_orientation + "Connect.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionConnect.setIcon(icon) self.actionConnect.setObjectName("actionConnect") self.actionConnect.triggered.connect(self.actionsMenu.connect) self.actionDisconnect = QtWidgets.QAction(self) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(dir_orientation + "Disconnect.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionDisconnect.setIcon(icon1) self.actionDisconnect.setObjectName("actionDisconnect") self.actionDisconnect.triggered.connect( self.actionsMenu.disconnect_cam) self.actionRun = QtWidgets.QAction(self) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(dir_orientation + "Run_Manual.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionRun.setIcon(icon2) self.actionRun.setObjectName("actionRun") self.actionRun.triggered.connect(self.actionsMenu.shoot) self.actionStop = QtWidgets.QAction(self) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(dir_orientation + "Stop.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionStop.setIcon(icon3) self.actionStop.setObjectName("actionStop") self.actionStop.triggered.connect(self.actionsMenu.stop) self.actionSettings = QtWidgets.QAction(self) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(dir_orientation + "Settings.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionSettings.setIcon(icon4) self.actionSettings.setObjectName("actionSettings") self.actionSettings.triggered.connect(self.open_settings) self.actionExit = QtWidgets.QAction(self) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(dir_orientation + "Exit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionExit.setIcon(icon5) self.actionExit.setObjectName("actionExit") self.actionExit.triggered.connect(self.close) self.actionPicFolder = QtWidgets.QAction(self) icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap(dir_orientation + "Folder.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionPicFolder.setIcon(icon6) self.actionPicFolder.setObjectName("actionPicFolder") self.actionPicFolder.triggered.connect(self.pics_folder) self.actionGetTemp = QtWidgets.QAction(self) icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap(dir_orientation + "Temp.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionGetTemp.setIcon(icon7) self.actionGetTemp.setObjectName("actionGetTemp") self.actionGetTemp.triggered.connect(self.show_temp) self.toolBar.addAction(self.actionConnect) self.toolBar.addAction(self.actionDisconnect) self.toolBar.addSeparator() self.toolBar.addAction(self.actionRun) self.toolBar.addAction(self.actionStop) self.toolBar.addSeparator() self.toolBar.addAction(self.actionSettings) self.toolBar.addAction(self.actionExit) self.toolBar.addSeparator() self.toolBar.addAction(self.actionPicFolder) self.toolBar.addAction(self.actionGetTemp) self.toolBar.addSeparator() self.retranslate_ui() QtCore.QMetaObject.connectSlotsByName(self) self.show()
class UiMainwindow(QtWidgets.QMainWindow): def setup_ui(self): self.settings = UiSelf() self.actionsMenu = Actions() # self.actionsMenu.signal_console.connect(self.write_to_console) self.console = ConsoleThreadOutput() self.setObjectName("self") self.setFixedSize(500, 268) size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setWindowTitle("CCD Controller 3.0.0 (Pixis)") self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit.setEnabled(True) font = QtGui.QFont() if os.name == "nt": font.setFamily("Terminal") font.setPointSize(11) else: font.setFamily("Noto") font.setPointSize(11) self.plainTextEdit.setFont(font) self.plainTextEdit.viewport().setProperty( "cursor", QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.plainTextEdit.setFocusPolicy(QtCore.Qt.NoFocus) self.plainTextEdit.setToolTip("") self.plainTextEdit.setStatusTip("") self.plainTextEdit.setWhatsThis("") self.plainTextEdit.setAccessibleName("") self.plainTextEdit.setAccessibleDescription("") # color: rgb(0, 255, 0) self.plainTextEdit.setStyleSheet( "color: green; background-color: rgb(0, 0, 0);") self.plainTextEdit.setPlainText("") self.plainTextEdit.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) self.plainTextEdit.setObjectName("plainTextEdit") self.console.set_console(self.plainTextEdit) self.verticalLayout.addWidget(self.plainTextEdit) self.setCentralWidget(self.centralwidget) self.toolBar = QtWidgets.QToolBar(self) self.toolBar.setMovable(False) self.toolBar.setIconSize(QtCore.QSize(48, 48)) self.toolBar.setObjectName("toolBar") self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) if os.name == "nt": dir_orientation = os.getcwd() + "\\ui\\icons\\" else: dir_orientation = os.getcwd() + "/ui/icons/" self.actionConnect = QtWidgets.QAction(self) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(dir_orientation + "Connect.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionConnect.setIcon(icon) self.actionConnect.setObjectName("actionConnect") self.actionConnect.triggered.connect(self.actionsMenu.connect) self.actionDisconnect = QtWidgets.QAction(self) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(dir_orientation + "Disconnect.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionDisconnect.setIcon(icon1) self.actionDisconnect.setObjectName("actionDisconnect") self.actionDisconnect.triggered.connect( self.actionsMenu.disconnect_cam) self.actionRun = QtWidgets.QAction(self) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(dir_orientation + "Run_Manual.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionRun.setIcon(icon2) self.actionRun.setObjectName("actionRun") self.actionRun.triggered.connect(self.actionsMenu.shoot) self.actionStop = QtWidgets.QAction(self) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(dir_orientation + "Stop.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionStop.setIcon(icon3) self.actionStop.setObjectName("actionStop") self.actionStop.triggered.connect(self.actionsMenu.stop) self.actionSettings = QtWidgets.QAction(self) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(dir_orientation + "Settings.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionSettings.setIcon(icon4) self.actionSettings.setObjectName("actionSettings") self.actionSettings.triggered.connect(self.open_settings) self.actionExit = QtWidgets.QAction(self) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(dir_orientation + "Exit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionExit.setIcon(icon5) self.actionExit.setObjectName("actionExit") self.actionExit.triggered.connect(self.close) self.actionPicFolder = QtWidgets.QAction(self) icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap(dir_orientation + "Folder.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionPicFolder.setIcon(icon6) self.actionPicFolder.setObjectName("actionPicFolder") self.actionPicFolder.triggered.connect(self.pics_folder) self.actionGetTemp = QtWidgets.QAction(self) icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap(dir_orientation + "Temp.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionGetTemp.setIcon(icon7) self.actionGetTemp.setObjectName("actionGetTemp") self.actionGetTemp.triggered.connect(self.show_temp) self.toolBar.addAction(self.actionConnect) self.toolBar.addAction(self.actionDisconnect) self.toolBar.addSeparator() self.toolBar.addAction(self.actionRun) self.toolBar.addAction(self.actionStop) self.toolBar.addSeparator() self.toolBar.addAction(self.actionSettings) self.toolBar.addAction(self.actionExit) self.toolBar.addSeparator() self.toolBar.addAction(self.actionPicFolder) self.toolBar.addAction(self.actionGetTemp) self.toolBar.addSeparator() self.retranslate_ui() QtCore.QMetaObject.connectSlotsByName(self) self.show() def retranslate_ui(self): _translate = QtCore.QCoreApplication.translate self.plainTextEdit.setPlaceholderText( _translate("MainWindow", "PlaceholderText")) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar")) self.actionConnect.setText(_translate("MainWindow", "Connect")) self.actionConnect.setToolTip(_translate("MainWindow", "Connect")) self.actionDisconnect.setText(_translate("MainWindow", "Disconnect")) self.actionDisconnect.setToolTip(_translate("MainWindow", "Disconnect")) self.actionRun.setText(_translate("MainWindow", "Run")) self.actionRun.setToolTip(_translate("MainWindow", "Run")) self.actionStop.setText(_translate("MainWindow", "Stop")) self.actionStop.setToolTip(_translate("MainWindow", "Stop")) self.actionSettings.setText(_translate("MainWindow", "Settings")) self.actionSettings.setToolTip(_translate("MainWindow", "Settings")) self.actionExit.setText(_translate("MainWindow", "Exit")) self.actionExit.setToolTip(_translate("MainWindow", "Exit")) ''' self.actionPicFolder.setText(_translate("MainWindow", "PicFolder")) ''' self.actionPicFolder.setToolTip( _translate("MainWindow", "Open Pictures Folder")) self.actionGetTemp.setToolTip( _translate("MainWindow", "Get Current Temperature")) def open_settings(self): if not self.actionsMenu.shooter.shoot_on: self.settings.setup_ui() else: self.console.write_to_console( "Cannot Change Settings During Acquisition.", 2) def show_temp(self): if self.actionsMenu.is_connected: self.console.write_to_console( "Current Temperature: " + "{0:.2f}".format(self.actionsMenu.get_temp() / 100, 0), 0) elif self.actionsMenu.shooter.shoot_on: self.console.write_to_console("Unavailable During Acquisition.", 2) else: self.console.write_to_console("Not Connected.", 2) def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: if self.actionsMenu.is_connected: if self.actionsMenu.shooter.shoot_on: self.actionsMenu.stop() while self.actionsMenu.shooter.shoot_on: continue # self.close() event.accept() else: event.ignore() def pics_folder(self): try: if not os.path.exists(self.actionsMenu.cs.path): os.makedirs(self.actionsMenu.cs.path) if os.name == "nt": os.startfile(self.actionsMenu.cs.path) else: subprocess.Popen(["xdg-open", self.actionsMenu.cs.path]) except Exception as e: self.console.write_to_console( "Failed to open images folder: " + str(e), 3) # TODO Darwin? """
class Commands: """Helper class, contains command for bind events, menu and buttons.""" def __init__(self, drawer): """Initialization commands class.""" self.drawer = drawer self.phrases = self.drawer.phrases self.message = Message(self.drawer) self.notes = Notes(self.message, self.phrases) self.config = self.drawer.config self.config.checker(self.message, self.phrases) self.tree = Tree() self.actions = Actions(self.tree, self.notes) self.set_window() def set_window(self): """Set size and position window from saving data.""" self.drawer.SetPosition(self.config.get_pos()) self.drawer.SetSize(self.config.get_size()) self.drawer.Layout() def donate(self, event): """Run donate hyperlink in browser.""" webbrowser.open(self.config.donate_url) def home(self, event): """Run home page hyperlink in browser.""" webbrowser.open(self.phrases.about.url) def about(self, event): """Run about dialog.""" About( self.drawer, self.phrases.about.title, self.phrases.about.name, version.VERSION, self.phrases.about.author ).ShowModal() def close(self, event): """Close event for button close.""" self.drawer.Close(True) def close_window(self, event): """Close window event.""" if self.config.general_expand == 'true': self.expand_tree_save() self.notes.close() self.config.set_pos(self.drawer.GetScreenPosition()) self.config.set_size(self.drawer.GetSize()) self.config.close() self.drawer.Destroy() def __sort(self, titles, parents): """Sort titles and parents dictionaries by order_sort field.""" sort_notes = OrderedDict() parents_list = [0] childs = [] while parents: for parent in parents_list: order_dict = self.notes.get_order(parent) if order_dict: order_id = [item[0] for item in sorted(list(order_dict.items()), key=lambda i: i[1])] for index in order_id: sort_notes[index] = (parent, titles[index]) parents.pop(index) childs.append(copy.copy(order_id)) parents_list = childs.pop(0) return sort_notes def init_tree(self): """Initialization tree widget.""" titles = self.notes.get_titles() parents = self.notes.get_parents() sort_notes = self.__sort(titles, parents) wx_tree_id = self.drawer.tree.AddRoot(self.phrases.widgets.tree.root) self.tree.add(0, -1, wx_tree_id) for index, note in sort_notes.items(): parent_wx_tree_id = self.tree.id2wx_tree_id(note[0]) wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, note[1]) self.tree.add(index, note[0], wx_tree_id) if self.config.general_expand == 'true': self.expand_tree_init() def expand_tree_init(self): """Init expand tree if set config settings.""" expands = self.notes.get_expands() wx_tree_id = self.tree.id2wx_tree_id(0) self.drawer.tree.Expand(wx_tree_id) for index in range(1, self.tree.get_count()): wx_tree_id = self.tree.id2wx_tree_id(index) if expands.get(index, 0) == 1: self.drawer.tree.Expand(wx_tree_id) else: self.drawer.tree.Collapse(wx_tree_id) def expand_tree_save(self): """Save expand tree if set config settings.""" expands = {} for index in range(1, self.tree.get_count()): wx_tree_id = self.tree.id2wx_tree_id(index) if self.drawer.tree.IsExpanded(wx_tree_id): expands[index] = 1 else: expands[index] = 0 self.notes.set_expands(expands) def __set_state_order_menuitem(self, state): """Set state menu items order.""" self.drawer.order_up.Enable(state) self.drawer.order_down.Enable(state) self.drawer.order_parent_up.Enable(state) self.drawer.order_parent_down.Enable(state) def __set_state_sort_menuitem(self, state): """Set state menu items sort.""" self.drawer.sort_titles.Enable(state) self.drawer.sort_childcount_up.Enable(state) self.drawer.sort_childcount_down.Enable(state) self.drawer.sort_state_up.Enable(state) self.drawer.sort_state_down.Enable(state) def __set_state_undo_menuitem(self): """Set menu items undo and redo.""" if self.actions.isUndo(): self.drawer.undo.Enable(True) else: self.drawer.undo.Enable(False) if self.actions.isRedo(): self.drawer.redo.Enable(True) else: self.drawer.redo.Enable(False) def __set_state_del(self, state): """Set state to delete button and delete menu item.""" self.drawer.but_del.Enable(state) self.drawer.del_note.Enable(state) def __disable_widgets(self): """Disable state for all widgets.""" self.__set_state_del(False) self.drawer.data.SetValue('') self.drawer.data.Disable() self.drawer.readonly.Enable(False) self.drawer.state_check.Enable(False) self.drawer.states.Enable(False) def __tree_select(self): """Change select item in tree with program select.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) if index is None: self.__set_state_order_menuitem(False) self.__set_state_sort_menuitem(False) self.__disable_widgets() self.drawer.but_create.Disable() self.drawer.create_child.Enable(False) self.drawer.info_date.Enable(False) elif index == 0: self.__set_state_order_menuitem(False) self.__set_state_sort_menuitem(True) self.__disable_widgets() self.drawer.but_create.Enable(True) self.drawer.create_child.Enable(True) self.drawer.info_date.Enable(False) else: self.__set_state_order_menuitem(True) self.__set_state_sort_menuitem(True) self.drawer.info_date.Enable(True) self.drawer.data.Enable() data = self.notes.get_note(index) self.drawer.data.SetValue(data) self.drawer.readonly.Enable(True) readonly = self.notes.get_readonly(index) self.drawer.readonly.SetValue(readonly) self.__set_state_text_note(not readonly) self.__set_state_del(not readonly) self.drawer.state_check.Enable(True) state_check = self.notes.get_state_check(index) self.drawer.state_check.SetValue(state_check) self.drawer.states.Enable(state_check) self.__set_state(index) self.drawer.but_create.Enable(True) self.drawer.create_child.Enable(True) self.drawer.but_save.Disable() self.drawer.save_note.Enable(False) def tree_select(self, event): """Change select item in tree.""" self.__tree_select() def tree_activated(self, event): """Activated edit label on tree item.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) readonly = self.drawer.readonly.GetValue() if readonly: if (self.config.readonly_password_check == "true") and self.__check_password(): readonly = False if (index != 0) and (not readonly): self.drawer.tree.EditLabel(event.GetItem()) def tree_end_edit(self, event): """Finish edit label item tree.""" wx_tree_id = self.drawer.tree.GetSelection() index = self.tree.wx_tree_id2id(wx_tree_id) title = event.GetLabel() if title != '': self.actions.run(SaveTitle(index, title)) self.__set_state_undo_menuitem() def text_change(self, event): """Change text controls note.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) if index != 0: self.drawer.but_save.Enable() self.drawer.save_note.Enable(True) def __set_state_text_note(self, state): """Set data text control note readonly state.""" self.drawer.data.SetEditable(state) def __check_password(self): """Check state readonly password.""" result = False dlg = PasswordEntryDialog(self.drawer, self.drawer.phrases.titles.password) if RetCode.OK == dlg.ShowModal(): hashpass= hashlib.sha1(dlg.GetValue().encode("utf-8")) if hashpass.hexdigest() == self.config.readonly_password: result = True dlg.Destroy() return result def __change_readonly(self, index, readonly): """Change readonly attribute for widgets.""" self.actions.run(SetReadonly(index, readonly)) self.__set_state_text_note(not readonly) self.__set_state_del(not readonly) def change_readonly(self, event): """Change readonly attribute for note.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) readonly = self.drawer.readonly.GetValue() if readonly: self.__change_readonly(index, readonly) elif self.config.readonly_password_check != "true": self.__change_readonly(index, readonly) elif self.__check_password(): self.__change_readonly(index, readonly) else: self.drawer.readonly.SetValue(True) self.__set_state_undo_menuitem() def change_state(self, event): """Change state attribute for note.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) state_check = self.drawer.state_check.GetValue() self.actions.run(SetStateCheck(index, state_check)) self.drawer.states.Enable(state_check) self.__set_state_undo_menuitem() def choice_state(self, event): """Set state for note.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) state = self.drawer.states.GetString(self.drawer.states.GetSelection()) self.actions.run(SetState(index, state)) self.__set_state_undo_menuitem() def __set_state(self, index): """Set string in choice states.""" state = self.notes.get_state(index) select = self.drawer.states.FindString(state) if select == self.drawer.get_not_found(): select = 0 self.drawer.states.SetSelection(select) def save(self, event): """Save data note in database.""" wx_tree_id = self.drawer.tree.GetSelection() index = self.tree.wx_tree_id2id(wx_tree_id) data = self.drawer.data.GetValue() self.actions.run(SaveNote(index, data)) self.__set_state_undo_menuitem() self.drawer.but_save.Disable() self.drawer.save_note.Enable(False) def delete(self, event): """Delete note from database.""" if self.message.question(self.phrases.titles.warning, self.phrases.questions.del_note): index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) parent_id = self.tree.get_parent_id(index) self.drawer.tree.DeleteAllItems() self.actions.run(DelNote(index)) self.__set_state_undo_menuitem() self.tree.clear() self.init_tree() self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(parent_id)) self.__tree_select() def create(self, event): """Create new note.""" if event.GetId() == self.drawer.create_root.GetId(): parent_id = 0 else: parent_id = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) index = self.tree.get_count() parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id) wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, self.phrases.widgets.tree.new_note) self.drawer.tree.Expand(parent_wx_tree_id) self.drawer.tree.SelectItem(wx_tree_id) self.tree.add(index, parent_id, wx_tree_id) self.actions.run(CreateNote(index, self.drawer.tree.GetItemText(wx_tree_id))) self.__set_state_undo_menuitem() self.__tree_select() def insert(self, event): """Insert new note.""" before_item = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) if before_item != 0: parent_id = self.tree.get_parent_id(before_item) index = self.tree.get_count() parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id) wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, self.phrases.widgets.tree.new_note) self.actions.run(InsertNote(index, before_item, self.drawer.tree.GetItemText(wx_tree_id))) self.__set_state_undo_menuitem() self.expand_tree_save() self.tree.clear() self.drawer.tree.DeleteAllItems() self.init_tree() parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id) self.drawer.tree.Expand(parent_wx_tree_id) self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index)) self.__tree_select() def rollback(self, event): """Process menu commands undo and redo.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) parent = self.tree.get_parent_id(index) if event.GetId() == self.drawer.undo.GetId(): self.actions.undo() elif event.GetId() == self.drawer.redo.GetId(): self.actions.redo() self.__set_state_undo_menuitem() self.expand_tree_save() self.tree.clear() self.drawer.tree.DeleteAllItems() self.init_tree() select = self.tree.id2wx_tree_id(index) if select is None: select = self.tree.id2wx_tree_id(parent) self.drawer.tree.SelectItem(select) self.__tree_select() def order(self, event): """Order items.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) if event.GetId() == self.drawer.order_up.GetId(): self.actions.run(OrderUp(index)) elif event.GetId() == self.drawer.order_down.GetId(): self.actions.run(OrderDown(index)) elif event.GetId() == self.drawer.order_parent_up.GetId(): self.actions.run(OrderParentUp(index)) elif event.GetId() == self.drawer.order_parent_down.GetId(): self.actions.run(OrderParentDown(index)) self.__set_state_undo_menuitem() self.expand_tree_save() self.tree.clear() self.drawer.tree.DeleteAllItems() self.init_tree() self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index)) self.__tree_select() def sort(self, event): """Sort items.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) if event.GetId() == self.drawer.sort_titles.GetId(): self.actions.run(SortTitle(index)) elif event.GetId() == self.drawer.sort_childcount_up.GetId(): self.actions.run(SortChildCountUp(index)) elif event.GetId() == self.drawer.sort_childcount_down.GetId(): self.actions.run(SortChildCountDown(index)) elif event.GetId() == self.drawer.sort_state_up.GetId(): self.actions.run(SortStateUp(index)) elif event.GetId() == self.drawer.sort_state_down.GetId(): self.actions.run(SortStateDown(index)) self.__set_state_undo_menuitem() self.expand_tree_save() self.tree.clear() self.drawer.tree.DeleteAllItems() self.init_tree() self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index)) self.__tree_select() def count(self, event): """Show information of count notes.""" if event.GetId() == self.drawer.count_root.GetId(): self.message.information(self.phrases.titles.info, self.phrases.info.count.root % self.tree.get_count_childs(0)) elif event.GetId() == self.drawer.count_child.GetId(): index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) self.message.information(self.phrases.titles.info, self.phrases.info.count.child % self.tree.get_count_childs(index)) else: self.message.information(self.phrases.titles.info, self.phrases.info.count.total % (self.tree.get_count() - 1)) def info_date(self, event): """Show info of date create and date update note.""" index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) date_create, date_update = self.notes.get_date(index) create = self.phrases.info.date.create.format(date_create) update = self.phrases.info.date.update.format(date_update) self.message.information(self.phrases.titles.info, '\n'.join([create, update])) def options(self, event): """Run settings dialog.""" if self.config.open_settings(self.drawer): self.drawer.states.Set(self.config.get_states(self.phrases.widgets.states)) index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection()) self.drawer.Layout() state = self.notes.get_state(index) self.drawer.states.SetSelection(self.drawer.states.FindString(state)) self.message.information(self.phrases.titles.info, self.phrases.info.need_restart)
from flask import Flask, request, send_file, render_template, abort, Response, redirect from rq import Queue from rq.job import Job from flask_cors import CORS from rq_scheduler import Scheduler from redis import Redis from utils.config import Configs from packages.github.github import Github from worker import conn from actions.actions import Actions from mongo.db import * configs = Configs() actions = Actions() github = Github() DB() app = Flask(__name__, static_folder="./dist/static", template_folder="./dist") CORS(app, resources={r"/*": {"origins": "*"}}) q = Queue(connection=conn) scheduler = Scheduler(connection=Redis()) @app.after_request def set_response_headers(response): response.headers["Cache-Control"] = "no-cache" response.headers["Pragma"] = "no-cache"