Exemple #1
0
    def __init__(self):
        super().__init__()

        self.loggedIn = False
        self.resources = Resources()
        if SysParams.tag == "ukb-7":
            self.createLogo()
        self.createLoginTab()
        # self.createRegisterTab()

        # define layout
        self.layout = QtWidgets.QVBoxLayout()
        self.blankLabel = QtWidgets.QLabel()
        self.blankLabel.setFixedHeight(75)
        if SysParams.tag == "ukb-5":
            self.layout.addWidget(self.blankLabel)

        # style
        self.setContentsMargins(50, 5, 50, 0)  #left, top, right, bottom
        self.layout.setSpacing(1)
        self.loginFormLayout.setContentsMargins(0, 0, 0, 0)

        # add to layout
        self.layout.addWidget(self.loginFormLayoutWidget)
        self.setLayout(self.layout)
 def __init__(self):
     super().__init__()
     # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
     self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
     self.loginTab = None
     self.launcherTab = None
     self.loggedIn = False
     self.userPermission = 0
     self.resources = Resources()
     self.init_ui()
class SimpleDialog(QtWidgets.QDialog):
    def init(self, message, yesString, noString, succesFn=None, failFn=None):
        self.succesFn = succesFn
        self.failFn = failFn
        self.resources = Resources()
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                            | QtCore.Qt.FramelessWindowHint)
        # self.setWindowFlag(QtCore.Qt.Popup)

        self.setWindowTitle(" ")
        # self.setMaximumWidth(250)
        # self.setMaximumHeight(250)

        messageLabel = QtWidgets.QLabel()
        messageLabel.setText(message)
        messageLabel.setWordWrap(True)
        layout2 = QtWidgets.QVBoxLayout()
        layout2.addWidget(messageLabel)

        if yesString is not None:
            yesButton = QtWidgets.QPushButton(yesString)
            noButton = QtWidgets.QPushButton(noString)

            yesButton.clicked.connect(self.yes)
            noButton.clicked.connect(self.no)

            layout1 = QtWidgets.QHBoxLayout()
            layout1.addWidget(yesButton)
            layout1.addWidget(noButton)
            widget1 = QtWidgets.QWidget()
            widget1.setLayout(layout1)
            layout2.addWidget(widget1)

        self.setLayout(layout2)

        self.setMyStyleSheet()

        self.exec_()

    def setMyStyleSheet(self):
        self.resources.set_color(self, self.resources.get_primary_color())
        self.setStyleSheet(self.resources.styeSheet())

    def yes(self):
        if self.succesFn is not None:
            self.succesFn()
        self.close()

    def no(self):
        if self.failFn is not None:
            self.failFn()
        self.close()
class QBattery(QtWidgets.QWidget):
    def __init__(self, pixmap_list, default_lvl=-1, prefix="", parent=None):
        super().__init__(parent)
        self.warning_30_flag = False
        self.warning_10_flag = False
        self.resources = Resources()
        self.messagePopup = MessagePopup(
            self.resources.get("battery_30").replace("\\n", "\n"),
            addCloseButton=True)
        self.pixmapList = pixmap_list
        self.label = QtWidgets.QLabel()
        self.prefix = prefix
        self.iconLabel = QtWidgets.QLabel()

        self.batteryLevel = default_lvl

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.iconLabel)
        layout.addWidget(self.label)
        layout.setSpacing(10)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.set_battery_level(100)

    def set_battery_level(self, level, is_charging=False):
        if not self.batteryLevel == level:
            self.batteryLevel = level
            self.label.setText(self.prefix + str(level))

            if is_charging:
                self.iconLabel.setPixmap(self.pixmapList[5])
            elif level > 90:  # 4
                self.iconLabel.setPixmap(self.pixmapList[0])
            elif level > 60:  # 3
                self.iconLabel.setPixmap(self.pixmapList[1])
            elif level > 40:  # 2
                self.iconLabel.setPixmap(self.pixmapList[2])
            elif level > 10:  # 1
                self.iconLabel.setPixmap(self.pixmapList[3])
            else:  # 0
                self.iconLabel.setPixmap(self.pixmapList[4])

            if level <= 10 and not self.warning_10_flag and not self.messagePopup.isOpen:
                self.warning_10_flag = True
                # self.messagePopup.messageLabel.setText(self.resources.get("battery_10").replace("\\n", "\n"))
                # self.messagePopup.openThis()
                return 10

            elif 10 < level <= 30 and not self.warning_30_flag and not self.messagePopup.isOpen:
                self.warning_30_flag = True
                print("self.warning_30_flag = True")
                # self.messagePopup.messageLabel.setText(self.resources.get("battery_30").replace("\\n", "\n"))
                # self.messagePopup.openThis()
                return 30
            elif level > 40:
                self.warning_30_flag = False
                self.warning_10_flag = False
            return -1
    def __init__(self, parent=None, margin=None):
        super(OverlayDialog, self).__init__(parent=parent)
        self.id = None
        self.isOpen = False
        self.setFixedSize(300, 200)
        self.successFn = None
        self.failFn = None
        self.resources = Resources()

        self.messageLabel = QtWidgets.QLabel()
        self.messageLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.messageLabel.setText("")
        self.messageLabel.setWordWrap(True)
        layout2 = QtWidgets.QVBoxLayout()
        layout2.addWidget(self.messageLabel)
        layout2.setAlignment(QtCore.Qt.AlignCenter)

        self.yesButton = QtWidgets.QPushButton("")
        self.noButton = QtWidgets.QPushButton("")
        self.yesButton.clicked.connect(self.yes)
        self.noButton.clicked.connect(self.no)

        layout1 = QtWidgets.QHBoxLayout()
        layout1.addWidget(self.yesButton)
        layout1.addWidget(self.noButton)
        widget1 = QtWidgets.QWidget()
        widget1.setLayout(layout1)
        layout2.addWidget(widget1)
        layout2.setSpacing(0)
        # layout1.setContentsMargins(0, 0, 0, 0)

        self.setLayout(layout2)

        self.setMyStyleSheet()

        if margin is None:
            self.paddingLeft = 5
            self.paddingTop = 5
        else:
            self.paddingLeft = margin[0]
            self.paddingTop = margin[1]
    def __init__(self, pixmap_list, default_lvl=-1, prefix="", parent=None):
        super().__init__(parent)
        self.warning_30_flag = False
        self.warning_10_flag = False
        self.resources = Resources()
        self.messagePopup = MessagePopup(
            self.resources.get("battery_30").replace("\\n", "\n"),
            addCloseButton=True)
        self.pixmapList = pixmap_list
        self.label = QtWidgets.QLabel()
        self.prefix = prefix
        self.iconLabel = QtWidgets.QLabel()

        self.batteryLevel = default_lvl

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.iconLabel)
        layout.addWidget(self.label)
        layout.setSpacing(10)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.set_battery_level(100)
    def __init__(self, parent=None):
        super(DateTimeWidget, self).__init__(parent)

        self.dayComboBox = QtWidgets.QComboBox()

        for n in range(31):
            self.dayComboBox.addItem(str(n + 1))

        self.monthComboBox = QtWidgets.QComboBox()

        for n in range(12):
            self.monthComboBox.addItem(str(n + 1))

        self.yearComboBox = QtWidgets.QComboBox()

        for n in range(10):
            self.yearComboBox.addItem(str(n + 2019))

        self.hourComboBox = QtWidgets.QComboBox()

        for n in range(24):
            self.hourComboBox.addItem(str(n))

        self.min10ComboBox = QtWidgets.QComboBox()

        for n in range(60):
            self.min10ComboBox.addItem(str(n))

        setDateTimeButton = QtWidgets.QPushButton(
            Resources().get("set_date_time"))
        setDateTimeButton.setFixedWidth(60)
        setDateTimeButton.clicked.connect(self.set_date_time)

        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(self.dayComboBox)
        layout.addWidget(self.monthComboBox)
        layout.addWidget(self.yearComboBox)
        layout.addWidget(self.hourComboBox)
        layout.addWidget(self.min10ComboBox)
        layout.addWidget(setDateTimeButton)
        # layout.addWidget(min1ComboBox)

        self.setLayout(layout)

        self.setContentsMargins(0, 0, 0, 0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        # self.setStyleSheet(" QComboBox::drop-down{height: 200px;}")
        # time.strftime('%d-%m-%Y %H:%M')
        self.print_date_time()
Exemple #8
0
class LoginTab(DoubleClickQWidget):
    loginSuccess = None
    logoutFunction = None
    iconName = "esetron_icon_128.png"
    isMoreOptionsOpen = False
    userName = "******"

    def __init__(self):
        super().__init__()

        self.loggedIn = False
        self.resources = Resources()
        if SysParams.tag == "ukb-7":
            self.createLogo()
        self.createLoginTab()
        # self.createRegisterTab()

        # define layout
        self.layout = QtWidgets.QVBoxLayout()
        self.blankLabel = QtWidgets.QLabel()
        self.blankLabel.setFixedHeight(75)
        if SysParams.tag == "ukb-5":
            self.layout.addWidget(self.blankLabel)

        # style
        self.setContentsMargins(50, 5, 50, 0)  #left, top, right, bottom
        self.layout.setSpacing(1)
        self.loginFormLayout.setContentsMargins(0, 0, 0, 0)

        # add to layout
        self.layout.addWidget(self.loginFormLayoutWidget)
        self.setLayout(self.layout)

    def createLogo(self):
        self.iconContainer = QtWidgets.QWidget()
        self.iconContainer.setContentsMargins(0, 0, 0, 0)
        layout = QtWidgets.QHBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.icon = QtWidgets.QLabel()
        self.icon = PicButton(
            QtGui.QPixmap(UKBParams.dirResources + self.iconName))
        width = 100
        r = 1 / 1
        self.icon.setFixedSize(width, int(width * r))
        layout.addWidget(self.icon)
        self.iconContainer.setLayout(layout)

    def createLoginTab(self):
        # define widgets
        self.loginUserNameLine = QtWidgets.QComboBox()
        self.loginUserNameLine.addItem(self.resources.get("admin"))
        self.loginUserNameLine.addItem(self.resources.get("user_2"))
        self.loginUserNameLine.addItem(self.resources.get("password_security"))

        self.loginPasswordLine = MyLineEdit()
        self.loginPasswordLine.setEchoMode(QtWidgets.QLineEdit.Password)
        self.loginPasswordLine.setPlaceholderText(
            self.resources.get("password"))
        self.loginPasswordLine.mousePressed = self.update_current_widget
        self.current_widget = self.loginPasswordLine

        self.loginNew1PasswordLine = MyLineEdit()
        self.loginNew1PasswordLine.setEchoMode(QtWidgets.QLineEdit.Password)
        self.loginNew1PasswordLine.setPlaceholderText(
            self.resources.get("new_password"))
        self.loginNew1PasswordLine.mousePressed = self.update_current_widget
        self.loginNew1PasswordLine.setVisible(False)

        self.loginNew2PasswordLine = MyLineEdit()
        self.loginNew2PasswordLine.setEchoMode(QtWidgets.QLineEdit.Password)
        self.loginNew2PasswordLine.setPlaceholderText(
            self.resources.get("new_password_again"))
        self.loginNew2PasswordLine.mousePressed = self.update_current_widget
        self.loginNew2PasswordLine.setVisible(False)

        self.moreOptionsLabel = ClickAbleLabel()
        self.moreOptionsLabel.setText(self.resources.get("more"))
        self.moreOptionsLabel.clickedFn = self.open_more_options

        self.closeLabel = ClickAbleLabel()
        self.closeLabel.setText(self.resources.get("close_2"))
        self.closeLabel.setVisible(False)

        self.coordinateTypeComboBox = QtWidgets.QComboBox()
        self.coordinateTypeComboBox.addItem(
            self.resources.get("decimal_coord"))
        self.coordinateTypeComboBox.addItem(
            self.resources.get("military_coord"))

        self.disconnectionPolicyComboBox = QtWidgets.QComboBox()
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("connection_loss_rule"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_return_home"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_destruct"))

        self.loginFromSubmitButton = QtWidgets.QPushButton(
            self.resources.get('login'))
        self.loginFromSubmitButton.clicked.connect(
            self.loginFromSubmitButtonOnClick)

        self.loginInfoBox = QtWidgets.QLabel("")
        # self.loginInfoBox.setFont(QtGui.QFont("Times", 16, QtGui.QFont.Bold))

        self.securityCode = QtWidgets.QLabel("123456")

        # keyboard
        keyboard_layout = QtWidgets.QHBoxLayout()
        keyboard_layout.setSpacing(5)

        for n, ch in enumerate("0123456789<"):
            bt = MyButton(ch)
            bt.effect = ch
            bt.setOnClick(self.virtual_keyboard)
            bt.setMaximumWidth(50)

            keyboard_layout.addWidget(bt)

        # temp
        self.loginPasswordLine.setText('123456')

        # define forms
        self.loginFormLayoutWidget = QtWidgets.QFrame()
        self.loginFormLayout = QtWidgets.QFormLayout(
            self.loginFormLayoutWidget)
        zeroLabel = QtWidgets.QLabel("")
        zeroLabel.setFixedSize(0, 20)
        if SysParams.tag == "ukb-7":
            self.loginFormLayout.addRow("", self.iconContainer)
        self.loginFormLayout.addRow("", self.loginUserNameLine)
        self.loginFormLayout.addRow("", self.loginPasswordLine)
        self.loginFormLayout.addRow("", self.loginNew1PasswordLine)
        self.loginFormLayout.addRow("", self.loginNew2PasswordLine)
        # self.loginFormLayout.addRow("", self.coordinateTypeComboBox)
        # self.loginFormLayout.addRow("", self.disconnectionPolicyComboBox)
        self.loginFormLayout.addRow("", self.loginFromSubmitButton)
        self.loginFormLayout.addRow("", self.closeLabel)
        self.loginFormLayout.addRow("", self.loginInfoBox)
        self.loginFormLayout.addRow("", self.moreOptionsLabel)
        self.loginFormLayout.addRow("", keyboard_layout)
        self.loginFormLayout.addRow("", self.securityCode)

    def open_more_options(self):
        if not self.isMoreOptionsOpen:
            self.moreOptionsLabel.setText(self.resources.get("less"))
            self.loginNew1PasswordLine.setVisible(True)
            self.loginNew2PasswordLine.setVisible(True)
        else:
            self.moreOptionsLabel.setText(self.resources.get("more"))
            self.loginNew1PasswordLine.setVisible(False)
            self.loginNew2PasswordLine.setVisible(False)

        self.isMoreOptionsOpen = not self.isMoreOptionsOpen

    def loginFromSubmitButtonOnClick(self):
        if self.loggedIn is True and self.logoutFunction is not None:
            self.loginSuccess()
            # self.logoutFunction()
        else:
            self.loginFromSubmitButton.setDisabled(True)
            if self.isMoreOptionsOpen and (
                    not self.loginNew1PasswordLine.text()
                    == self.loginNew2PasswordLine.text()):
                self.loginInfoBoxMessage(
                    self.resources.get('second_password_mismatch'), 'error')
                self.loginFromSubmitButton.setDisabled(False)

            else:
                user = database.Users()
                idx = self.loginUserNameLine.currentIndex()
                if idx == 0:
                    userName = "******"
                elif idx == 1:
                    userName = "******"
                elif idx == 2:
                    userName = "******"

                print("user : "******"res : ", res)
                print("password : "******"password_security":
                        self.setSecurityCode()

                    else:
                        self.loggedIn = True
                        self.loginInfoBoxMessage(
                            self.resources.get('logged_in'), 'info')
                        self.loginFromSubmitButton.setDisabled(False)
                        # self.loginFromSubmitButton.setText(self.resources.get('logout'))

                        if self.loginSuccess is not None:
                            self.userName = userName
                            self.loginSuccess()

    def loginInfoBoxMessage(self, text, mode):
        if mode == 'error':
            self.loginInfoBox.setStyleSheet('color: ' + self.resources.error)
        elif mode == 'warning':
            self.loginInfoBox.setStyleSheet('color: ' + self.resources.warning)
        elif mode == 'info':
            self.loginInfoBox.setStyleSheet('color: ' + self.resources.info)
        else:
            self.loginInfoBox.setStyleSheet('color: black')

        self.loginInfoBox.setText(text)

    def setLoginSuccesFunction(self, fn):
        self.loginSuccess = fn

    def setSecurityCode(self):
        newCode = int(self.securityCode.text())
        print("code :", newCode)
        newCode = newCode * 2
        newCode = newCode % 999999
        newCode = str(newCode)
        self.securityCode.setText(newCode)
        self.setNewPassword()

    def setNewPassword(self):
        user = database.Users()
        password = int(self.securityCode.text())
        password = password * 3
        password = password % 999999
        password = str(password)
        print("newpass :"******"<":
            self.current_widget.setText(self.current_widget.text() + bt.effect)
        else:
            self.current_widget.setText("")

        print(self.current_widget.text())

    def update_current_widget(self, w):
        self.current_widget = w
Exemple #9
0
    def __init__(self):
        super().__init__()
        # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.coordinateType = int(sys.argv[1])
        self.disconnectionPolicy = int(sys.argv[2])
        self.chooseIka = int(sys.argv[3])
        print("choose ika : ", self.chooseIka)
        self.disconnectTime = int(sys.argv[4])
        self.coordinateConverter = mgrs.MGRS()
        # vars
        self.isRestart = False
        self.isClosing = False
        self.isConfigDone = False
        self.socketReceive, self.socketSend = None, None
        self.cabledSocketReceive, self.cabledSocketSend = None, None
        self.lastMessage = None
        self.udpLastReceiveTime = None
        self.payloadID = None
        self.kgmControl = None
        self.kgmTest = None
        # self.ggmTest = None
        if self.chooseIka == 0:
            self.kgmTest = Com.PingTest(UKBParams.kgmIp)
        elif self.chooseIka == 1:
            self.kgmTest = Com.PingTest(UKBParams.ggmIp)
        # self.loginTab = None
        # self.loggedIn = False
        self.userPermission = 0
        self.panelTab = None
        self.serialPrefix = [0xAA, 0XBB]
        self.serialSuffix = [0xCC, 0XDD]
        self.brightnessLevels = [10, 60, 99]
        self.serialJoystick = None
        self.joystickPatternDetector = Joystick()
        self.joystickPatternDetector.setOnClicks(self.execute_joystick_action)
        self.resources = Resources()
        self.peripheral = PeripheralData()

        self.ukbCoords = None

        self.joystickLeftX = 0
        self.joystickLeftY = 0

        self.communicationProcess = BackgroundProcess(self.communication_loop,
                                                      parent=self)
        self.communicationTimer = QtCore.QTimer()
        self.communicationTimer.setInterval(40)
        self.communicationTimer.timeout.connect(
            self.execute_received_board_udp_data)

        self.init_ui()
        self.dialog = OverlayDialog(parent=self)
        self.emptyMessage = Message(None, "", None, None)
        self.pimMessage = Message(2,
                                  self.resources.get("pim_not_inserted"),
                                  None,
                                  None,
                                  _type="info")
        self.batteryIka10Message = Message(
            5, "IKA: " + self.resources.get("battery_10").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryIka30Message = Message(
            6, "IKA: " + self.resources.get("battery_30").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryUkb10Message = Message(
            4, "UKB: " + self.resources.get("battery_10").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryUkb30Message = Message(
            3, "UKB: " + self.resources.get("battery_30").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryIka10Message.success = self.set_empty_message
        self.batteryIka30Message.success = self.set_empty_message
        self.batteryUkb10Message.success = self.set_empty_message
        self.batteryUkb30Message.success = self.set_empty_message
        # self.motionDetectionMessage = Message(5, self.resources.get("motion_detected"),
        #                                       self.resources.get("ok"), None)
        self.screenShotMessage = Message(
            0, self.resources.get("screenshot_taken"), None, None)
        self.disconnectedMessage = Message(1,
                                           self.resources.get("disconnected"),
                                           None,
                                           None,
                                           _type="error")
        self.config()
        self.communicationProcess.start()
        self.communicationTimer.start()
Exemple #10
0
class Window(QtWidgets.QWidget):
    bit0 = 0b00000001
    bit1 = 0b00000010
    bit2 = 0b00000100
    bit3 = 0b00001000
    bit4 = 0b00010000
    bit5 = 0b00100000
    bit6 = 0b01000000
    bit7 = 0b10000000
    configLevel = 0

    def __init__(self):
        super().__init__()
        # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.coordinateType = int(sys.argv[1])
        self.disconnectionPolicy = int(sys.argv[2])
        self.chooseIka = int(sys.argv[3])
        print("choose ika : ", self.chooseIka)
        self.disconnectTime = int(sys.argv[4])
        self.coordinateConverter = mgrs.MGRS()
        # vars
        self.isRestart = False
        self.isClosing = False
        self.isConfigDone = False
        self.socketReceive, self.socketSend = None, None
        self.cabledSocketReceive, self.cabledSocketSend = None, None
        self.lastMessage = None
        self.udpLastReceiveTime = None
        self.payloadID = None
        self.kgmControl = None
        self.kgmTest = None
        # self.ggmTest = None
        if self.chooseIka == 0:
            self.kgmTest = Com.PingTest(UKBParams.kgmIp)
        elif self.chooseIka == 1:
            self.kgmTest = Com.PingTest(UKBParams.ggmIp)
        # self.loginTab = None
        # self.loggedIn = False
        self.userPermission = 0
        self.panelTab = None
        self.serialPrefix = [0xAA, 0XBB]
        self.serialSuffix = [0xCC, 0XDD]
        self.brightnessLevels = [10, 60, 99]
        self.serialJoystick = None
        self.joystickPatternDetector = Joystick()
        self.joystickPatternDetector.setOnClicks(self.execute_joystick_action)
        self.resources = Resources()
        self.peripheral = PeripheralData()

        self.ukbCoords = None

        self.joystickLeftX = 0
        self.joystickLeftY = 0

        self.communicationProcess = BackgroundProcess(self.communication_loop,
                                                      parent=self)
        self.communicationTimer = QtCore.QTimer()
        self.communicationTimer.setInterval(40)
        self.communicationTimer.timeout.connect(
            self.execute_received_board_udp_data)

        self.init_ui()
        self.dialog = OverlayDialog(parent=self)
        self.emptyMessage = Message(None, "", None, None)
        self.pimMessage = Message(2,
                                  self.resources.get("pim_not_inserted"),
                                  None,
                                  None,
                                  _type="info")
        self.batteryIka10Message = Message(
            5, "IKA: " + self.resources.get("battery_10").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryIka30Message = Message(
            6, "IKA: " + self.resources.get("battery_30").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryUkb10Message = Message(
            4, "UKB: " + self.resources.get("battery_10").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryUkb30Message = Message(
            3, "UKB: " + self.resources.get("battery_30").replace("\\n", "\n"),
            self.resources.get("ok"), None)
        self.batteryIka10Message.success = self.set_empty_message
        self.batteryIka30Message.success = self.set_empty_message
        self.batteryUkb10Message.success = self.set_empty_message
        self.batteryUkb30Message.success = self.set_empty_message
        # self.motionDetectionMessage = Message(5, self.resources.get("motion_detected"),
        #                                       self.resources.get("ok"), None)
        self.screenShotMessage = Message(
            0, self.resources.get("screenshot_taken"), None, None)
        self.disconnectedMessage = Message(1,
                                           self.resources.get("disconnected"),
                                           None,
                                           None,
                                           _type="error")
        self.config()
        self.communicationProcess.start()
        self.communicationTimer.start()

    def set_empty_message(self):
        self.show_dialog(self.emptyMessage)
        return 0

    def show_dialog(self, message_instance: Message):
        # self.folderListView.setDisabled(True)
        # self.toolbarView.setDisabled(True)
        print(self.dialog.id, message_instance.id)
        if self.dialog.id is None or message_instance.id is None:
            self.dialog.show_with(message_instance.id,
                                  message_instance.message,
                                  message_instance.yes, message_instance.no,
                                  message_instance.success,
                                  message_instance.fail, message_instance.type)
        elif self.dialog.id <= message_instance.id:
            self.dialog.show_with(message_instance.id,
                                  message_instance.message,
                                  message_instance.yes, message_instance.no,
                                  message_instance.success,
                                  message_instance.fail, message_instance.type)

    def config(self):
        try:
            if self.configLevel == 0:
                js = self.check_joystick()
                print("js :: ", js)
                self.serialJoystick = Com.init_serial(js[0])
                assert js is not None
                self.configLevel = 1

            if self.configLevel == 1:
                if self.chooseIka == 0:
                    self.socketReceive, self.socketSend = \
                        Com.init_sockets(UKBParams.rxPort, UKBParams.ukbIp)
                    self.panelTab.deviceNumber = 1
                else:
                    self.socketReceive, self.socketSend = \
                        Com.init_sockets(UKBParams.rx3Port, UKBParams.ukbIp)
                    self.panelTab.deviceNumber = 2
                print("device : ", self.panelTab.deviceNumber)
                self.configLevel = 2

            # self.cabledSocketReceive, self.cabledSocketSend = \
            #     Com.init_sockets(UKBParams.rxPort, UKBParams.cabledUKBIp)

            self.isConfigDone = True
            print("config success", time.time())

        except:
            self.isConfigDone = False
            print("config failed:", sys.exc_info())

    def communication_loop(self):
        if self.isConfigDone:
            try:
                #receive udp data from vehicle board
                data, addr = self.socketReceive.recvfrom(28)
                print("DATA", data)
                if len(data) == 28:
                    # self.lastMessage = None
                    print("data ", data)
                    self.lastMessage = [x for x in data]
                    self.udpLastReceiveTime = time.time()
                    #self.panelTab.set_connection_state(True) --> PanelTab içine taşındı
                    if self.dialog.id == self.disconnectedMessage.id:
                        self.show_dialog(self.emptyMessage)
                print(self.lastMessage)

            except:
                if self.udpLastReceiveTime is not None and (
                        time.time() - self.udpLastReceiveTime) > 0.5:
                    # self.panelTab.set_connection_state(False)
                    # self.show_dialog(self.disconnectedMessage)
                    print("bağlantı koptu")
            try:
                data = self.gather_udp_package()
                if self.chooseIka == 0:
                    if self.panelTab.lteButton.state == 0:
                        if self.panelTab.cabledButton.state == 0:
                            self.socketSend.sendto(
                                serial.to_bytes(data),
                                (UKBParams.ikaIp, UKBParams.txPort))
                        else:
                            self.socketSend.sendto(
                                serial.to_bytes(data),
                                (UKBParams.cabledIKAIp, UKBParams.txPort))
                    else:
                        self.socketSend.sendto(
                            serial.to_bytes(data),
                            ("5.11.133.3", UKBParams.txPort))
                else:
                    if self.panelTab.lteButton.state == 0:
                        if self.panelTab.cabledButton.state == 0:
                            self.socketSend.sendto(
                                serial.to_bytes(data),
                                (UKBParams.ika3Ip, UKBParams.txPort))
                        else:
                            self.socketSend.sendto(
                                serial.to_bytes(data),
                                (UKBParams.cabledIka3Ip, UKBParams.txPort))
                    else:
                        self.socketSend.sendto(
                            serial.to_bytes(data),
                            ("5.11.133.3", UKBParams.txPort))
            except:
                # pass
                print("send receive:", sys.exc_info())

            # try:
            #     data, addr = self.socketReceive.recvfrom(10)
            #     if len(data) == 10:
            #         self.controlMessage = None
            #         self.controlMessage = [x for x in data]
            #         self.udpControlLastReceiveTime = time.time()
            #     print("done")
            # except:
            #     if self.udpControlLastReceiveTime is not None and (time.time() - self.udpControlLastReceiveTime) > 0.5:
            #         print("control message failed")

            time.sleep(0.03)
        else:
            self.config()
            time.sleep(1)
            # self.panelTab.set_connection_state(False)
            self.show_dialog(self.disconnectedMessage)

    def execute_received_board_udp_data(self):
        # read from ika peripheral --> send to ukb
        # 0,1 => AA,BB
        # 2,3 => yaw
        # 4,5 => pitch
        # 6,7 => roll
        # 8.0 => orientation (0: up, 1: down)
        # 8.1,2,3 => payload id (0: none, 1: carry, 2: gun, 3: KGM, 4:launch)        #todo add kgm and carry
        # 8.4 => ret home (0: off, 1:on)
        # 8.5,6 => clear path 1: clear first point, 2: clear all
        # 8.7 => home failed 0 : None, 1 : Fail
        # 9 => imu flag
        # 10 => payload flag
        # 10 => 0: carry ready, 1: launch ready, 2: fuse ready, 3: fuse fired, 4: gun ready, 5: gun fired, 6,7 ::::
        # 11 => battery level (0-100)
        # 12, 13 => arm angle (0-360)
        # 14 => battery health
        # 15-18 => lat
        # 19-22 => lon
        # 23 => ck_a
        # 24 => ck_b
        # 25,26 => CC,DD
        # / for ukb (extra byte)
        # 27.0-1 => 0: ika-1, 1:ika-2, 2: ika-3
        # 27.2 => 0: kgm off, 1: kgm on
        if not self.isClosing:
            if self.lastMessage is not None:
                print("last message", self.lastMessage)
                message = self.lastMessage.copy()
                yaw = message[2] * 256 + message[3]
                pitch = message[4] * 256 + message[5]
                roll = message[6] * 256 + message[7]

                yaw = self.signed_converter_16(yaw)
                pitch = self.signed_converter_16(pitch)
                roll = self.signed_converter_16(roll)

                orientation = (message[8] & self.bit0)

                # self.panelTab.payloadType.state = (message[8] & (self.bit1 | self.bit2 | self.bit3)) >> 1
                self.payloadID = (message[8] &
                                  (self.bit1 | self.bit2 | self.bit3)) >> 1
                print("payload : ", self.payloadID)
                if self.panelTab.payloadType.state != self.payloadID:
                    self.panelTab.payloadType.state = self.payloadID
                    print("HHHHH")
                    self.panelTab.activeCarryButton.setVisible(False)
                    self.panelTab.activeLaunchButton.setVisible(False)
                    self.panelTab.readyFuseButton.setVisible(False)
                    self.panelTab.activeFuseButton.setVisible(False)
                    self.panelTab.readyGunButton.setVisible(False)
                    self.panelTab.activeGunButton.setVisible(False)
                    self.panelTab.kgmView.setVisible(False)
                    self.panelTab.ggmView.setVisible(False)
                    self.panelTab.thermal_button.setVisible(False)
                    # self.panelTab.ggmBUTTONS.setVisible(False)
                    self.panelTab.destructButton.setVisible(True)
                    # print(self.payloadType.state)
                    # print(state)
                    if self.panelTab.payloadType.state != 0:
                        self.panelTab.destructButton.setVisible(False)
                    if self.panelTab.payloadType.state == 1:
                        self.panelTab.activeCarryButton.setVisible(True)
                        self.panelTab.readyFuseButton.setVisible(True)
                        self.panelTab.activeFuseButton.setVisible(True)
                    elif self.panelTab.payloadType.state == 2:
                        self.panelTab.readyGunButton.setVisible(True)
                        self.panelTab.activeGunButton.setVisible(True)
                    elif self.panelTab.payloadType.state == 3:
                        if self.chooseIka == 0:
                            self.panelTab.isKgmOn = 1
                            self.panelTab.kgmView.setVisible(True)
                        elif self.chooseIka == 1:
                            self.panelTab.isGgmOn = 1
                            self.panelTab.ggmView.setVisible(True)
                            self.panelTab.thermal_button.setVisible(True)
                            # self.panelTab.ggmBUTTONS.setVisible(True)
                    elif self.panelTab.payloadType.state == 4:
                        self.panelTab.activeLaunchButton.setVisible(True)

                # if not self.panelTab.payloadId == (message[8] & (self.bit1 | self.bit2 | self.bit3)) >> 1:          # todo add new bits for new payloads
                #     self.panelTab.payloadId = (message[8] & (self.bit4 | self.bit5)) >> 4
                # self.panelTab.payloadFire.set_state(self.panelTab.payloadId)

                if (message[8] & self.bit6) == self.bit6:
                    self.panelTab.returnHome.set_state(0)
                #         self.panelTab.returnHome.state_update()
                # elif (message[8] & self.bit3) == 0 and self.panelTab.returnHome.previousNotifiedState == self.bit3:
                #     if self.panelTab.returnHome.state == 1:
                #         self.panelTab.returnHome.state_update()
                if (message[8] & self.bit7) == self.bit7:
                    self.panelTab.returnHome.set_state(0)
                # self.panelTab.returnHome.previousNotifiedState = (message[8] & self.bit4)

                if not self.panelTab.imuView.isHidden():
                    self.panelTab.imuView.set_angle(roll, pitch, yaw)

                if self.panelTab.flipButton.state == 1:
                    if not self.panelTab.player.isFlipped == (orientation
                                                              == 1):
                        self.panelTab.player.isFlipped = orientation == 1

                # self.peripheral.IMU_RESET_READY_FLAG = message[9] & self.bit0
                self.imuSaveDone = message[9] & self.bit0
                # self.peripheral.IMU_RESET_DETECT_FLAG = (message[9] & self.bit1) >> 1
                self.imuTurnDone = (message[9] & self.bit1) >> 1
                # self.peripheral.IMU_SAVE_ANGLE_READY_FLAG = (message[9] & self.bit2) >> 2
                # self.peripheral.IMU_SAVE_ANGLE_DETECT_FLAG = (message[9] & self.bit3)
                # self.peripheral.IMU_SAVED_ANGLE_RESET_READY_FLAG = (message[9] & self.bit4) >> 4
                # self.peripheral.IMU_SAVED_ANGLE_RESET_DETECT_FLAG = (message[9] & self.bit5) >> 5
                # self.peripheral.TURN_SAVED_ANGLE_READY_FLAG = (message[9] & self.bit6) >> 6
                # self.peripheral.TURN_SAVED_ANGEL_DETECT_FLAG = (message[9] & self.bit7) >> 1

                if self.imuSaveDone == 1:
                    self.imuSave = 0
                if self.imuTurnDone == 1:
                    self.imuTurn = 0

                self.peripheral.update_imu_status()

                self.peripheral.JUMP_READY_FLAG = message[
                    10] & self.bit0  #carryReady
                self.peripheral.JUMP_DETECT_FLAG = (
                    message[10] & self.bit1) >> 1  #launchReady

                if self.peripheral.JUMP_DETECT_FLAG == 1:
                    self.panelTab.activeLaunchButton.state = 0
                self.peripheral.FUSE_READY_FLAG = (message[10]
                                                   & self.bit2) >> 2  #gunReady
                self.peripheral.FUSE_DETECT_FLAG = (
                    message[10] & self.bit3) >> 3  #gunFired

                self.peripheral.FIRE_READY_FLAG = (
                    message[10] & self.bit4) >> 4  #fuseReady
                self.peripheral.FIRE_DETECT_FLAG = (
                    message[10] & self.bit5) >> 5  #fuseFired
                if self.peripheral.FIRE_DETECT_FLAG == 1:
                    self.panelTab.activeGunButton.state = 0
                    # self.panelTab.counter += 1

                self.peripheral.update_payload_status()

                battery_level = message[11]
                if not self.panelTab.ikaBatteryView.batteryLevel == battery_level:
                    ret = self.panelTab.ikaBatteryView.set_battery_level(
                        battery_level)

                    if ret == 10:
                        self.show_dialog(self.batteryIka10Message)

                    elif ret == 30:
                        self.show_dialog(self.batteryIka30Message)

                arm_angle = message[12] * 256 + message[13]
                self.panelTab.set_arm_angle(arm_angle)

                coordinate_str = self.coordinate_32_convert_str(message[15:19]) + ', ' + \
                                 self.coordinate_32_convert_str(message[19:23])
                if self.panelTab.cameraCombobox.currentIndex() < 2:
                    zoom_level = " x" + str(self.panelTab.player.zoomCount)
                else:
                    zoom_level = " x" + str(
                        int(self.panelTab.player.zoomCount *
                            (self.joystickPatternDetector.zoomCommand +
                             1)))  #todo GGM için özelleştir

                if self.panelTab.recordButton.state == 1:
                    isRecording = " rec"
                else:
                    isRecording = ""

                if not coordinate_str.find("0.0") > -1:
                    lat_lon = [float(x) for x in coordinate_str.split(",")]
                    self.panelTab.mapView.set_reference(
                        lat_lon[0], lat_lon[1], 17)
                    self.panelTab.mapView.move_marker("ika", lat_lon[0],
                                                      lat_lon[1])
                    if self.coordinateType == 1:
                        coordinate_str = self.coordinateConverter.toMGRS(
                            lat_lon[0], lat_lon[1])
                        # coordinate_str = coordinate_str.decode("utf-8", "ignore")
                    self.panelTab.player.overlayText = time.strftime(
                        '%d/%m/%Y %H:%M:%S'
                    ) + isRecording + zoom_level + " --" + coordinate_str

                elif self.panelTab.ukbCoordinates is not None:
                    coordinate_str = self.coordinate_32_convert_str(self.panelTab.ukbCoordinates[0:4]) + ', ' + \
                                     self.coordinate_32_convert_str(self.panelTab.ukbCoordinates[4:8])

                    if not coordinate_str.find("0.0") > -1:
                        if self.coordinateType == 1:
                            lat_lon = [
                                float(x) for x in coordinate_str.split(",")
                            ]
                            coordinate_str = self.coordinateConverter.toMGRS(
                                lat_lon[0], lat_lon[1])
                            coordinate_str = coordinate_str.decode(
                                "utf-8", "ignore")

                        self.panelTab.player.overlayText = time.strftime(
                            '%d/%m/%Y %H:%M:%S'
                        ) + isRecording + zoom_level + " --" + coordinate_str
                    else:
                        self.panelTab.player.overlayText = time.strftime(
                            '%d/%m/%Y %H:%M:%S') + isRecording + zoom_level

                else:
                    self.panelTab.player.overlayText = time.strftime(
                        '%d/%m/%Y %H:%M:%S') + isRecording + zoom_level

                if not self.panelTab.deviceNumber == message[27] & 0b000000011:
                    self.panelTab.deviceNumber = message[27] & 0b000000011
                    if self.panelTab.deviceNumber == 0:
                        self.panelTab.cameraCombobox.setDisabled(True)
                        self.panelTab.imu_map_switch_button.setVisible(False)
                        self.panelTab.armView.setVisible(False)
                        self.panelTab.armForward.setVisible(False)
                        self.panelTab.armBackward.setVisible(False)
                        self.panelTab.returnHome.setVisible(False)
                        self.panelTab.returnHomeMode.setVisible(False)
                        self.panelTab.backLed.setVisible(False)
                        self.panelTab.cabledButton.setVisible(False)

                self.panelTab.isKgmOn = (message[27] & 0b000000100) >> 2

            # handle js
            # ukb-peripheral to ukb
            # 0 => 0xAA
            # 1 => 0xBB
            # 2: analog left x
            # 3: analog left y
            # 4: analog right x
            # 5: analog right y
            # 6.0: toggle left forward (arm state 0: stop, 1: forward, 2: backward)
            # 6.1: toggle left backward (arm state 0: stop, 1: forward, 2: backward)
            # 6.2: button left back
            # 6.3: button left up
            # 6.4: button left down
            # 7.0: toggle right forward
            # 7.1: toggle right backward
            # 7.2: button right back
            # 7.3: button right up
            # 7.4: button right down
            # 7.5: power button
            # 7.6: power pim (0: not present, 1: present)
            # 8: battery level (0-100)
            # 9-12: latitude
            # 13-16: longitude
            # 17 => battery health
            # 18 => ck_a
            # 19 => ck_b
            # 20 => 0xCC
            # 21 => 0xDD

            # ukb to ukb-peripheral
            # 0: brightness 100-200

            try:
                if self.serialJoystick.in_waiting >= 22:
                    msg = self.serialJoystick.read(
                        self.serialJoystick.in_waiting)
                    self.serialJoystick.reset_input_buffer()
                    msg = [x for x in msg]
                    msg2 = msg[(len(msg) - 22):]
                    print("peri :: ", msg2)
                    if msg2[:2] == self.serialPrefix and msg2[
                            -2:] == self.serialSuffix:
                        # pimState = (msg2[7] & 0b01000000)
                        # if pimState  == 0b01000000:
                        #     msg2[2:8] =
                        self.joystickPatternDetector.parse_message(msg2[2:8])
                        # self.joystickLeftX = msg2[2]
                        # self.joystickLeftY = msg2[3]
                        battery_level = msg2[8]
                        if not self.panelTab.ukbBatteryView.batteryLevel == battery_level:
                            ret = self.panelTab.ukbBatteryView.set_battery_level(
                                battery_level)
                            if ret == 10:
                                self.show_dialog(self.batteryUkb10Message)
                            elif ret == 30:
                                self.show_dialog(self.batteryUkb30Message)
                        self.ukbCoords = msg2[9:17]
                        coordinate_str = self.coordinate_32_convert_str(msg2[9:13]) + ', ' + \
                                             self.coordinate_32_convert_str(msg2[13:17])

                        if None not in self.panelTab.mapView.clickedCoordinate:
                            lat_lon = self.panelTab.mapView.clickedCoordinate
                            self.panelTab.ukbCoordinates = self.coordinate_str_convert_32(lat_lon[0]) + \
                                                           self.coordinate_str_convert_32(lat_lon[1])
                            self.panelTab.mapView.move_marker(
                                "ukb", lat_lon[0], lat_lon[1])
                        elif coordinate_str.find("0.0") == -1:
                            self.panelTab.ukbCoordinates = msg2[9:17]
                            lat_lon = [
                                float(x) for x in coordinate_str.split(",")
                            ]
                            self.panelTab.mapView.move_marker(
                                "ukb", lat_lon[0], lat_lon[1])

                    if not self.joystickPatternDetector.powerPimState and not self.dialog.id == self.pimMessage.id:
                        self.show_dialog(self.pimMessage)

                    elif self.joystickPatternDetector.powerPimState and self.dialog.id == self.pimMessage.id:
                        self.show_dialog(self.emptyMessage)

            except:
                print("js failed")
                js = self.check_joystick()
                if js is not None:
                    self.serialJoystick = Com.init_serial(js[0])

            try:
                if self.panelTab is not None and self.serialJoystick is not None:
                    self.serialJoystick.write(
                        serial.to_bytes([
                            self.brightnessLevels[
                                self.panelTab.brightnessButton.state] + 100
                        ]))
            except:
                print("js send jailed")

    def execute_joystick_action(self, action):
        print("action", action)

        if self.panelTab is not None:
            if action == "mode_up":
                pass
            elif action == "speed_mode_up":
                self.panelTab.speedMode.state_update()
            elif action == "speed_mode_down":
                self.panelTab.speedMode.decrease_state()
            elif action == "imu_turn":
                self.panelTab.imuSaveButton = 1
                # self.panelTab.imuState = 8
            elif action == "imu_save":
                self.panelTab.imuTurnButton = 1
                # self.panelTab.imuState = 2

            # if self.panelTab.kgmView.state == 1:
            #     if action == "video_up":
            #         self.kgmControl.moveUp()
            #     elif action == "video_down":
            #         self.kgmControl.moveDown()
            # elif action == "video_right":
            #     self.panelTab.player.panValues[0] += 10
            #     # elif action == "video_left":
            #     #     self.panelTab.player.panValues[0] -= 10
            #     else:
            #         self.kgmControl.stop()

            if self.panelTab.player.videoWidth is not None and self.panelTab.player.videoHeight is not None:
                # if self.panelTab.cameraCombobox.currentIndex() < 2:
                if self.panelTab.kgmView.state != 1:
                    if action == "video_up":
                        self.panelTab.player.panValues[1] -= 10
                    elif action == "video_down":
                        self.panelTab.player.panValues[1] += 10
                    elif action == "video_right":
                        self.panelTab.player.panValues[0] += 10
                    elif action == "video_left":
                        self.panelTab.player.panValues[0] -= 10
                    elif action == "zoom_in":
                        self.panelTab.zoom("in")
                    elif action == "zoom_out":
                        self.panelTab.zoom("out")

                if action == "screen_shot":
                    self.panelTab.screenShotButton.on_click()
                elif action == "next_camera" and self.panelTab.deviceNumber > 0:
                    current_camera_index = self.panelTab.cameraCombobox.currentIndex(
                    )
                    current_camera_index += 1
                    #
                    # if self.panelTab.isKgmOn == 1:
                    #     max_cam = 2
                    # else:
                    #     max_cam = 1
                    max_cam = 1
                    if current_camera_index > max_cam:
                        current_camera_index = 0

                    self.panelTab.set_camera(current_camera_index,
                                             set_index=True)

                elif action == "previous_camera":
                    current_camera_index = self.panelTab.cameraCombobox.currentIndex(
                    )
                    current_camera_index -= 1
                    if current_camera_index < 0:
                        if self.panelTab.isKgmOn == 1:
                            current_camera_index = 3
                        else:
                            current_camera_index = 1

                    self.panelTab.set_camera(current_camera_index,
                                             set_index=True)

                elif action == "fire":
                    if self.panelTab.readyGunButton.state == 1:
                        self.panelTab.activeGunButton.state = 1
                        self.panelTab.counter += 1
                # if not self.panelTab.payloadId == 0:
                #     self.panelTab.isPayloadActive = True

        if action == "close_app":
            self.closeApp()
        elif action == "shut_down":
            self.closeApp(is_shutdown=True)

    def gather_udp_package(self):
        # from ukb to ika and ika-peripheral
        # 0 => 0xAA
        # 1 => 0xBB
        # 2 => analog left X
        # 3 => analog left Y
        # 4.0,1 => front led (0: off, 1: mid, 2: max)
        # 4.2,3 => front IR (0: off, 1: mid, 2: max)
        # 4.4,5 => back led (0: off, 1: mid, 2: max)
        # 4.6,7 => back IR (0: off, 1: mid, 2: max)
        # 5.0,1 => speed mode (0,1,2 : speed, 3: pivot)
        # 5.2,3 => arm state (0: off, 1: forward, 2:backward )
        # 5.4,5 => drive mode (0: manuel, 1: half auto, 2: auto)
        # 5.6   => auto tail adjust / auto rotate (0: off, 1: on)
        # 5.7   => return home (0: off, 1: on)
        # 6.0,1 => return home commands
        # 6.4 => clear path
        # 6.7 => thermal 0:off 1:on
        # 7 => payload flags
        # 7.0 => carry ready
        # 7.1 => launch
        # 7.2 => fuse ready
        # 7.3 => fire the fuse
        # 7.4 => gun ready
        # 7.5 => fire the gun
        # 7.6,7 => gun's arms   6 : turn left, 7 : turn right
        # 8.0,2 => camera index (0: front, 1: back, 2: KGM, 3: Gun)
        # 8.3,5 => camera command (kgm) (0: none, 1: up, 2: down, 3: right, 4: left)
        # 8.6 => 0: follow home, 1: follow path
        # 9 - 12  => lat
        # 13 - 16 => lon
        # 17.0,1 => disconnected policy (0: stop, 1: return home, 2: destruct)
        # 17.2 => 0: nothing, 1: destruct
        # 17.3-6 => camera zoom command (kgm) (zoom:0-11)
        # 18 => ck_a
        # 19 => ck_b
        # 20 => 0xCC
        # 21 => 0xDD
        # 22 => extra byte

        print("kgmTest : ", self.kgmTest.state)

        message = [0] * 23  #todo add extra byte

        message[0] = 0xAA
        message[1] = 0xBB
        message[2] = self.joystickPatternDetector.analogLeftX
        message[3] = self.joystickPatternDetector.analogLeftY
        # message[2] = self.joystickLeftX
        # message[3] = self.joystickLeftY
        message[4] = self.panelTab.frontLed.state + (
            self.panelTab.backLed.state << 4)
        if self.panelTab.irLed.state == 1:
            message[4] = message[4] << 2

        message[5] |= self.panelTab.speedMode.state

        arm_state = 0
        if self.panelTab.armForward.state == 1 and self.panelTab.armBackward.state == 0:
            arm_state = 1
        elif self.panelTab.armForward.state == 0 and self.panelTab.armBackward.state == 1:
            arm_state = 2

        if arm_state == 0:
            message[5] |= self.joystickPatternDetector.armState << 2
        else:
            message[5] |= arm_state << 2

        message[5] |= self.panelTab.driveMode.state << 4
        message[5] |= self.panelTab.autoRotate.state << 6
        message[5] |= self.kgmTest.state << 7

        message[6] |= self.panelTab.returnHome.state
        message[6] |= self.panelTab.returnHomeMode.state << 1
        if self.panelTab.returnHome.state == 0:
            message[6] |= self.panelTab.clearPath.state << 4
        else:
            message[6] |= 0 << 4
        # self.panelTab.imuState = self.peripheral.get_imu_state(self.panelTab.imuState)
        # message[6] |= self.panelTab.imuState
        #
        # message[6] |= self.joystickPatternDetector.gunTurnSpeed << 4

        message[7] |= self.panelTab.activeCarryButton.state
        message[7] |= self.panelTab.activeLaunchButton.state << 1
        message[7] |= self.panelTab.readyFuseButton.state << 2
        message[7] |= self.panelTab.activeFuseButton.state << 3
        message[7] |= self.panelTab.readyGunButton.state << 4
        message[7] |= self.panelTab.activeGunButton.state << 5
        turn_gun_left = 0
        turn_gun_right = 0
        if self.joystickPatternDetector.gunLeftCommand == 1:
            turn_gun_left = 1
        else:
            turn_gun_left = 0
        message[7] |= turn_gun_left << 6
        if self.joystickPatternDetector.gunRightCommand == 1:
            turn_gun_right = 1
        else:
            turn_gun_right = 0
        message[7] |= turn_gun_right << 7
        # message[7] |= self.panelTab.gunArmForwad.state
        # message[7] |= self.panelTab.gunArmBackward.state
        # if self.panelTab.isPayloadActive:
        #     message[7] |= self.peripheral.get_payload_state(self.panelTab.payloadId)
        #     self.panelTab.isPayloadActive = False
        # else:
        #     message[7] |= (self.peripheral.get_payload_state(0))
        if self.kgmTest.state == 0:
            self.panelTab.kgmView.state = 0

        if self.panelTab.kgmView.state != 1:
            message[8] |= self.panelTab.cameraCombobox.currentIndex()
        else:
            message[8] |= self.panelTab.kgmView.state + 2
        message[8] |= self.joystickPatternDetector.cameraCommand << 3
        camera_direction = self.joystickPatternDetector.cameraCommand
        camera_zoom = self.joystickPatternDetector.zoomCommand

        # if self.kgmTest.state == 1:
        #     if self.panelTab.kgmView.state == 1:
        #         if self.kgmControl is None:
        #             self.kgmControl = KGMControl()
        #             if not self.cameraDirection == camera_direction:
        #                 self.cameraDirection = camera_direction
        #                 if camera_direction == 1:
        #                     self.kgmControl.moveUp()
        #                 elif camera_direction == 2:
        #                     self.kgmControl.moveDown()
        #                 # elif camera_direction == 3:
        #                 #     self.kgmControl.moveRight()
        #                 # elif camera_direction == 4:
        #                 #     self.kgmControl.moveLeft()
        #                 else:
        #                     self.kgmControl.stop()
        #
        # if self.panelTab.kgmView.state > 0:
        #     if not self.kgmControl.zoomLevel == camera_zoom:
        #         self.kgmControl.zoom_to(camera_zoom)

        message[8] |= self.panelTab.imuState << 6

        # message[8] |= self.panelTab.returnHomeMode.state << 6

        if self.panelTab.returnHomeMode.state == 0:
            message[9:17] = self.ukbCoords
        else:
            if self.panelTab.ukbCoordinates is not None:
                message[9:17] = self.panelTab.ukbCoordinates

        # message[17] |= self.loginTab.disconnectionPolicyComboBox.currentIndex()
        message[17] |= self.disconnectionPolicy
        message[17] |= self.panelTab.isDestructOn << 2
        # message[17] |= self.openingWarn << 3
        message[17] |= self.joystickPatternDetector.gunTurnSpeed << 4
        print("js speed : ", self.joystickPatternDetector.gunTurnSpeed)

        ck_a, ck_b = self.checksum(message[2:-4])
        message[18] = ck_a
        message[19] = ck_b

        message[20] = 0xCC
        message[21] = 0xDD
        # message[22] |= self.panelTab.voiceButton.state
        message[22] = camera_zoom
        print("msg", message)
        return message

    # message[x] |= self.disconnectTime                                                         #todo add 3 bit for disconnect time

    @staticmethod
    def signed_converter_16(val):
        if val > 0x7fff:
            return (0xffff - val + 1) * (-1)

        else:
            return val

    @staticmethod
    def checksum(arr):
        ck_a = 0x00
        ck_b = 0x00

        for val in arr:
            ck_a += val
            ck_a = ck_a % 256
            ck_b += ck_a
            ck_b = ck_b % 256

        return ck_a, ck_b

    @staticmethod
    def coordinate_str_convert_32(coordinate_str):
        int_val = int(float(coordinate_str) * 1000000)
        if int_val < 0:
            int_val += 0xffffffff + 1

        bytes_val = [x for x in int_val.to_bytes(4, byteorder="big")]

        return bytes_val

    @staticmethod
    def coordinate_32_convert_str(bytes_val):
        val = bytes_val[0] * 256 * 256 * 256 + bytes_val[
            1] * 256 * 256 + bytes_val[2] * 256 + bytes_val[3]
        if val > 0x7fffffff:
            int_val = (0xffffffff - val + 1) * (-1)

        else:
            int_val = val

        return '%.6f' % (int_val / 1000000)

    @staticmethod
    def check_joystick():
        # js = ConnectionManager().get_tty_dev(UKBParams.joystickSerialNumber)
        js = ["/dev/ttyS0", "attached"]
        if js is not None:
            if js[1] is not None and len(js) == 2 and js[1] == "attached":
                return js
        return None

    def init_ui(self):
        # side panel
        self.sidePanel = SidePanel()
        self.sidePanel.init()

        # add widgets
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.sidePanel)
        self.setLayout(self.layout)
        # stylesheet
        self.setMyStyleSheet()
        # set first window
        self.loginSuccess()
        self.showFullScreen()

    def setMyStyleSheet(self):
        self.setContentsMargins(0, 0, 0, 0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.resources.set_color(self.sidePanel,
                                 self.resources.get_primary_color())
        self.resources.set_color(self, self.resources.get_primary_color())
        self.setStyleSheet(self.resources.styleSheet())

    def loginSuccess(self):
        self.panelTab = PanelTab(self.chooseIka)
        self.panelTab.closeButton.clicked.connect(self.closeApp)
        self.sidePanel.loadPanel(self.panelTab)

    def closeApp(self, is_shutdown=False):
        self.isClosing = True
        if self.communicationProcess is not None:
            self.communicationProcess.kill = True

        if self.communicationTimer.isActive():
            self.communicationTimer.stop()

        if self.panelTab is not None:
            self.panelTab.close_this()

        if is_shutdown:
            subprocess.call("sudo shutdown now", shell=True)
        else:
            self.close()
class OverlayDialog(QtWidgets.QWidget):
    def __init__(self, parent=None, margin=None):
        super(OverlayDialog, self).__init__(parent=parent)
        self.id = None
        self.isOpen = False
        self.setFixedSize(300, 200)
        self.successFn = None
        self.failFn = None
        self.resources = Resources()

        self.messageLabel = QtWidgets.QLabel()
        self.messageLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.messageLabel.setText("")
        self.messageLabel.setWordWrap(True)
        layout2 = QtWidgets.QVBoxLayout()
        layout2.addWidget(self.messageLabel)
        layout2.setAlignment(QtCore.Qt.AlignCenter)

        self.yesButton = QtWidgets.QPushButton("")
        self.noButton = QtWidgets.QPushButton("")
        self.yesButton.clicked.connect(self.yes)
        self.noButton.clicked.connect(self.no)

        layout1 = QtWidgets.QHBoxLayout()
        layout1.addWidget(self.yesButton)
        layout1.addWidget(self.noButton)
        widget1 = QtWidgets.QWidget()
        widget1.setLayout(layout1)
        layout2.addWidget(widget1)
        layout2.setSpacing(0)
        # layout1.setContentsMargins(0, 0, 0, 0)

        self.setLayout(layout2)

        self.setMyStyleSheet()

        if margin is None:
            self.paddingLeft = 5
            self.paddingTop = 5
        else:
            self.paddingLeft = margin[0]
            self.paddingTop = margin[1]

    def show_with(self,
                  _id,
                  message,
                  yes_string,
                  no_string,
                  success_fn=None,
                  fail_fn=None,
                  message_type=None):
        self.id = _id
        if _id is not None:
            self.isOpen = True
            self.successFn = success_fn
            self.failFn = fail_fn
            self.messageLabel.setText(message)

            if message_type is not None:
                if message_type == "info":
                    self.messageLabel.setStyleSheet("color: " +
                                                    self.resources.info)
                elif message_type == "warning":
                    self.messageLabel.setStyleSheet("color: " +
                                                    self.resources.warning)
                elif message_type == "error":
                    self.messageLabel.setStyleSheet("color: " +
                                                    self.resources.error)
            else:
                self.messageLabel.setStyleSheet("color: " +
                                                self.resources.info)

            if yes_string is not None:
                self.yesButton.setText(yes_string)
                self.yesButton.setVisible(True)
            else:
                self.yesButton.setVisible(False)

            if no_string is not None:
                self.noButton.setText(no_string)
                self.noButton.setVisible(True)
            else:
                self.noButton.setVisible(False)

            self.setVisible(True)
            # self.setFocus()
        else:
            self.close_this()

    def close_this(self):
        self.isOpen = False
        self.setVisible(False)

    def setMyStyleSheet(self):
        self.resources.set_color(self, self.resources.get_primary_color())
        # self.resources.set_color(self, QtGui.QColor(255, 0, 0))
        self.setStyleSheet(self.resources.styleSheet())

    def yes(self):
        print("yes..")
        ret = 0
        if self.successFn is not None:
            ret = self.successFn()

        if ret is None or ret == 0:
            self.close_this()

    def no(self):
        ret = 0
        if self.failFn is not None:
            ret = self.failFn()

        if ret is None or ret == 0:
            self.close_this()
            # self.parent().recordsPlayerView.folderListView.setDisabled(False)
            # self.parent().recordsPlayerView.toolbarView.setDisabled(False)

    def update_position(self):
        if hasattr(self.parent(), 'viewport'):
            parent_rect = self.parent().viewport().rect()
        else:
            parent_rect = self.parent().rect()

        if not parent_rect:
            return

        x = self.parent().width() - self.width()
        x = int(x / 2)
        y = self.parent().height() - self.height()
        y = int(y / 2)
        print("self.height()", self.parent().height(), self.height(), y)
        print("self.width()", self.parent().width(), self.width(), x)
        self.setGeometry(x, y, self.width(), self.height())

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.update_position()
class LauncherTab(QtWidgets.QWidget):
    def __init__(self, user_permission, parent=None):
        super().__init__(parent=parent)
        self.isAnAppRunning = False
        self.resources = Resources()
        layout = QtWidgets.QVBoxLayout(self)
        # layout.set(QtCore.Qt.RightToLeft)
        # layout.setAlignment(QtCore.Qt.AlignRight)
        layout.setContentsMargins(10, 10, 10, 10)

        disk_usage_info_label = QtWidgets.QLabel("")
        # disk_usage_info_label.setFixedSize(400, 30)

        disk_progress_bar = DiskProgressBar(label=disk_usage_info_label)
        # disk_progress_bar.setFixedSize(100, 30)

        layout2 = QtWidgets.QHBoxLayout()

        panel_app = self.create_menu_item(
            "Panel", self.launch_to_panel,
            UKBParams.dirResources + "dashboard-3-128.png")
        records_app = self.create_menu_item(
            "Kayıtlar", self.launch_to_records,
            UKBParams.dirResources + "film-2-128.png")
        tile_importer_app = self.create_menu_item(
            "Harita Yükle", self.launch_to_tile_importer,
            UKBParams.dirResources + "internet-128.png")
        # thermal_test_app = self.create_menu_item("Termal Test", self.launch_to_thermal_test, UKBParams.dirResources + "internet-128.png")
        close_app = self.create_menu_item(
            "Kapat", self.launch_to_close,
            UKBParams.dirResources + "power-128.png")
        info_app = self.create_menu_item(
            None, self.launch_to_info,
            UKBParams.dirResources + "info-2-32.png")
        info_app.setFixedSize(50, 50)
        # info_app = PicButton(UKBParams.dirResources + "info-2-32.png")
        # info_app.clicked.connect(self.launch_to_info)

        layout2.addWidget(panel_app)
        if user_permission > 0:
            layout2.addWidget(records_app)
        if SysParams.tag == "ukb-7":
            layout2.addWidget(tile_importer_app)
            # layout2.addWidget(thermal_test_app)
        layout2.addWidget(close_app)
        layout2.setSpacing(5)
        layout2.setContentsMargins(0, 0, 0, 0)

        self.infoBox = QtWidgets.QLabel("Hazır")
        self.infoBox.setMaximumHeight(40)
        self.infoBox.setAlignment(QtCore.Qt.AlignCenter)

        self.chooseIkaComboBox = QtWidgets.QComboBox()
        self.chooseIkaComboBox.addItem("Komodo")
        self.chooseIkaComboBox.addItem("Ejder")

        self.destructTimeComboBox = QtWidgets.QComboBox()
        self.destructTimeComboBox.addItem("0")
        self.destructTimeComboBox.addItem("15")
        self.destructTimeComboBox.addItem("30")
        self.destructTimeComboBox.addItem("45")
        self.destructTimeComboBox.addItem("60")

        self.coordinateTypeComboBox = QtWidgets.QComboBox()
        self.coordinateTypeComboBox.addItem(
            self.resources.get("decimal_coord"))
        self.coordinateTypeComboBox.addItem(
            self.resources.get("military_coord"))

        self.disconnectionPolicyComboBox = QtWidgets.QComboBox()
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("connection_loss_rule"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_return_home"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_destruct").replace(
                "\\n", "\n"))
        # self.disconnectionPolicyComboBox.setFixedWidth(100)

        self.failedHomeActioonPolicyComboBox = QtWidgets.QComboBox()
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("home_fail_rule"))
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("if_return_failed_do_nothing"))
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("if_return_failed_destruct"))

        # info_app = QtWidgets.QPushButton()
        # info_app.clicked.connect(self.launch_to_info)

        layout.setAlignment(QtCore.Qt.AlignCenter)
        layout.addLayout(
            self.layout_packer(
                [info_app, disk_usage_info_label, disk_progress_bar]))
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(layout2)
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addWidget(self.infoBox)
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(
            self.layout_packer(
                [self.chooseIkaComboBox, self.destructTimeComboBox]))
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(
            self.layout_packer([
                self.coordinateTypeComboBox, self.disconnectionPolicyComboBox
            ]))
        layout.addWidget(QtWidgets.QLabel(""))

    def set_free(self):
        self.isAnAppRunning = False
        self.infoBox.setText("Hazır")

    def launch_to_panel(self):
        if not self.isAnAppRunning:
            self.isAnAppRunning = True
            self.infoBox.setText("Açılıyor...")
            QtCore.QTimer.singleShot(10000, self.set_free)
            time.sleep(0.2)
            self.launch = Thread(target=self.launch_to_panel_text)
            self.launch.start()
            # subprocess.Popen("sh /home/pi/ukb/ukb.sh " + str(arg1) + " " + str(arg2) + " " + str(arg3) + " " + str(arg4), stdout=subprocess.PIPE,
            #                  shell=True)

    def launch_to_panel_text(self):
        arg1 = self.coordinateTypeComboBox.currentIndex()
        arg2 = self.disconnectionPolicyComboBox.currentIndex()
        arg3 = self.chooseIkaComboBox.currentIndex()
        arg4 = self.destructTimeComboBox.currentIndex()  # choose robot
        os.system("sh /home/pi/ukb/ukb.sh " + str(arg1) + " " + str(arg2) +
                  " " + str(arg3) + " " + str(arg4))

    # def launch_to_panel(self):
    #     arg1 = self.coordinateTypeComboBox.currentIndex()
    #     arg2 = self.disconnectionPolicyComboBox.currentIndex()
    #     arg3 = self.chooseIkaComboBox.currentIndex()
    #     arg4 = self.destructTimeComboBox.currentIndex()# choose robot
    #     if not self.isAnAppRunning:
    #         self.isAnAppRunning = True
    #         subprocess.Popen("sh /home/pi/ukb/ukb.sh " + str(arg1) + " " + str(arg2) + " " + str(arg3) + " " + str(arg4), stdout=subprocess.PIPE,
    #                          shell=True)
    #         self.infoBox.setText("Açılıyor...")
    #         QtCore.QTimer.singleShot(10000, self.set_free)

    # def launch_to_panel_text(self):
    #     arg1 = self.coordinateTypeComboBox.currentIndex()
    #     arg2 = self.disconnectionPolicyComboBox.currentIndex()
    #     arg3 = self.chooseIkaComboBox.currentIndex()
    #     arg4 = self.destructTimeComboBox.currentIndex()# choose robot
    #     os.system("sh /home/pi/ukb/ukb.sh " + str(arg1) + " " + str(arg2) + " " + str(arg3) + " " + str(arg4))

    def launch_to_records(self):
        if not self.isAnAppRunning:
            self.isAnAppRunning = True
            subprocess.Popen(
                "python3 /home/pi/records-player/records-player-mvc.py",
                stdout=subprocess.PIPE,
                shell=True)

            self.infoBox.setText("Açılıyor...")
            QtCore.QTimer.singleShot(4000, self.set_free)

    def launch_to_tile_importer(self):
        if not self.isAnAppRunning:
            self.isAnAppRunning = True
            subprocess.Popen("python3 /home/pi/tile-importer/TiffImporter.py",
                             stdout=subprocess.PIPE,
                             shell=True)

            self.infoBox.setText("Açılıyor...")
            QtCore.QTimer.singleShot(2000, self.set_free)

    # def launch_to_thermal_test(self):
    #     if not self.isAnAppRunning:
    #         self.isAnAppRunning = True
    #         subprocess.Popen("python3 /home/pi/thermal-test/thermal-test.py", stdout=subprocess.PIPE,
    #                          shell=True)
    #
    #         self.infoBox.setText("Açılıyor...")
    #         QtCore.QTimer.singleShot(2000, self.set_free)

    def launch_to_close(self):
        if not self.isAnAppRunning:
            self.isAnAppRunning = True
            subprocess.Popen("sudo shutdown now",
                             stdout=subprocess.PIPE,
                             shell=True)

            self.infoBox.setText("UKB Kapatılıyor...")
            QtCore.QTimer.singleShot(3000, self.set_free)

    def launch_to_info(self):
        if not self.isAnAppRunning:
            self.isAnAppRunning = True
            subprocess.Popen(
                "python3 /home/pi/user-manual/user-manual-main.py",
                stdout=subprocess.PIPE,
                shell=True)
            self.infoBox.setText("Açılıyor...")
            QtCore.QTimer.singleShot(2000, self.set_free)

    @staticmethod
    def create_menu_item(name, on_click_fn, icon_path):
        item = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout(item)
        icon = PicButton(QtGui.QPixmap(icon_path))
        icon.setFixedSize(130, 130)
        icon.clicked.connect(on_click_fn)

        button = QtWidgets.QPushButton(name)
        button.clicked.connect(on_click_fn)

        if name is None:
            button.setVisible(False)
            icon.setFixedSize(50, 50)

        layout.addWidget(icon)
        layout.addWidget(button)
        item.setFixedSize(150, 200)
        item.setStyleSheet("QWidget:hover{border : 2px solid red}")
        return item

    @staticmethod
    def layout_packer(ws):
        layout = QtWidgets.QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)
        for w in ws:
            layout.addWidget(w)

        return layout
Exemple #13
0
class GstCvPlayer(TractableLabel):
    def __init__(self, video_source_str, save_dir=None, parent=None):
        super().__init__(parent=parent, pan_values=[0, 0])
        self.setScaledContents(True)
        self.softPlay = True
        self.isMotionEnabledDetection = False
        self.isMotionDetected = False
        self.lastMotionTime = time.time()

        # gunCam = GunCamera()
        # self.flipTransform = QtGui.QTransform()
        # self.flipTransform.rotate(180)
        self.videoFlipElement = None
        self.overlayText = ""

        self.active_window = None
        self.videoWidth = None
        self.videoHeight = None
        self.zoomCount = 1
        self.maxZoom = 10
        self.isFlipped = False
        self.currentFlipMode = 0
        self.panValues = [0, 0]
        self.prevPanValues = [0, 0]
        self.demandedState = "play"
        self.isSurfaceScaled = False
        self.lastSampleTime = time.time()
        self.videoSourceStr = video_source_str

        # self.isGunCamera = gunCam.cameraState

        self.pipe = None
        self.appSrc = None
        self.appSink = None
        self.lastSample = None
        self.previousSample = None
        self.isClosing = False
        self.arr = None
        # self.isEOSDone = False
        self.pixmap = None

        self.set_video_src(video_source_str)

        self.setContentsMargins(0, 0, 0, 0)

        self.scaleHeight = self.geometry().size().height() - 0

        self.saveDir = save_dir
        self.isRecordEnabled = False
        self.isRecorderSetUp = False
        self.fourcc = None
        self.videoWriter = None
        if save_dir is not None:
            # self.isRecordEnabled = True
            self.fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            self.videoWriter = None

        self.videoCheckTimer = QtCore.QTimer()
        self.videoCheckTimer.setInterval(250)
        self.videoCheckTimer.timeout.connect(self.video_check_2)
        self.videoCheckTimer.start()

        self.resources = Resources()
        self.motionMessagePopup = MessagePopup(
            self.resources.get("motion_detected"), addCloseButton=True)

    def video_check_2(self):
        if time.time() - self.lastSampleTime > 2:
            self.lastSampleTime = time.time()
            print("Video time out. Refreshing..")
            self.set_video_src(self.videoSourceStr)

        # motion detection
        if self.isMotionEnabledDetection and not self.motionMessagePopup.isOpen and (
                time.time() -
                self.lastMotionTime) > 10 and self.previousSample is not None:

            gray_1 = cv2.cvtColor(self.lastSample, cv2.COLOR_BGRA2GRAY)
            gray_1 = cv2.GaussianBlur(gray_1, (25, 25), 0)
            delta = cv2.absdiff(gray_1.astype("float"),
                                self.previousSample.astype("float"))
            self.previousSample = gray_1
            mean = delta.mean()
            print(mean)
            if mean > 3:
                print("True ", delta.mean(), time.time())
                self.isMotionDetected = True
                self.lastMotionTime = time.time()
                self.previousSample = None

            if self.isMotionDetected:
                self.isMotionDetected = False
                self.motionMessagePopup.openThis()

        elif self.previousSample is None and self.lastSample is not None:
            gray_1 = cv2.cvtColor(self.lastSample, cv2.COLOR_BGRA2GRAY)
            self.previousSample = cv2.GaussianBlur(gray_1, (25, 25), 0)

    def video_check(self, last_sample):
        qImage = qimage2ndarray.array2qimage(last_sample)
        self.pixmap = QtGui.QPixmap(qImage)

        if not self.isSurfaceScaled:
            self.isSurfaceScaled = True
            self.scaleHeight = self.geometry().size().height() - 100

        if self.softPlay:
            if self.isFlipped and self.currentFlipMode == 0:
                self.currentFlipMode = 2
                self.videoFlipElement.set_property("method",
                                                   self.currentFlipMode)
            elif not self.isFlipped and self.currentFlipMode == 2:
                self.currentFlipMode = 0
                self.videoFlipElement.set_property("method",
                                                   self.currentFlipMode)
            # if self.isFlipped:
            #     self.setPixmap(pixmap.transformed(self.flipTransform).scaledToHeight(self.scaleHeight))
            # else:
            # self.setPixmap(pixmap.scaledToHeight(self.scaleHeight))
            # self.setPixmap(pixmap)
            self.update()
        if self.isRecordEnabled:
            if not self.isRecorderSetUp:
                if self.saveDir is not None and self.videoWidth is not None and self.videoHeight is not None:
                    self.videoWriter = cv2.VideoWriter(
                        self.saveDir, self.fourcc, 15,
                        (self.videoWidth, self.videoHeight), True)
                    self.isRecorderSetUp = True

            if self.videoWriter is not None:
                # h, w, d = numpy.shape(self.lastSample)
                # if not (h == self.firstVideoHeight and w == self.firstVideoHeight):
                #     numpy.pad(self.lastSample, ((0, h - self.videoHeight), (0, w - self.videoWidth)), 'constant')

                self.videoWriter.write(
                    cv2.cvtColor(last_sample, cv2.COLOR_RGBA2BGR))

    def gun_camera_state(self, state):
        if state == 3:
            self.isGunCamera = 1
        else:
            self.isGunCamera = 0

    def paintEvent(self, event):
        if self.pixmap is not None:
            painter = QPainter(self)
            painter.drawPixmap(event.rect(), self.pixmap)
            painter.end()

            # if self.isGunCamera == 1:
            painter = QtGui.QPainter(self)
            painter.setPen(QPen(QtCore.Qt.red, 1, QtCore.Qt.SolidLine))
            painter.drawLine(220, 270, 520, 270)  # X axis
            painter.drawLine(370, 120, 370, 420)  # Y axis
            painter.drawEllipse(350, 250, 40, 40)
            painter.drawEllipse(330, 230, 80, 80)
            painter.drawEllipse(310, 210, 120, 120)
            # painter.drawEllipse(370, 240, 160, 160)
            painter.end()
            # else:
            #     pass

    def update_last_sample(self, sink, data):
        # t0 = time.time()
        # print("start", t0)
        self.lastSampleTime = time.time()
        sample = sink.emit("pull-sample")
        last_sample = self.get_last_sample_as_np(sample)

        h, w, d = numpy.shape(last_sample)
        if self.videoWidth is None and w == 640:
            self.videoHeight, self.videoWidth, depth = numpy.shape(last_sample)
        else:
            if self.videoWidth is None:
                self.videoHeight, self.videoWidth = 480, 640
            if not self.videoWidth == w:
                last_sample = cv2.resize(last_sample,
                                         (self.videoWidth, self.videoHeight),
                                         interpolation=cv2.INTER_LINEAR)
        # print(numpy.shape(last_sample))
        if self.active_window is None:
            self.active_window = [0, 0, self.videoWidth, self.videoHeight]
        pan_x = 0
        pan_y = 0
        if self.active_window[0] + self.panValues[0] >= 0 and \
                self.active_window[2] + self.panValues[0] <= self.videoWidth:
            pan_x = self.panValues[0]
            self.prevPanValues[0] = self.panValues[0]
        elif self.active_window[0] + self.panValues[0] < 0:
            pan_x = -self.active_window[0]
            self.panValues[0] = pan_x
            self.prevPanValues[0] = self.panValues[0]
        elif self.active_window[2] + self.panValues[0] > self.videoWidth:
            pan_x = self.videoWidth - self.active_window[2]
            self.panValues[0] = pan_x
            self.prevPanValues[0] = self.panValues[0]
        else:
            self.panValues[0] = self.prevPanValues[0]
            pan_x = self.prevPanValues[0]

        if self.active_window[1] + self.panValues[1] >= 0 and \
                self.active_window[3] + self.panValues[1] <= self.videoHeight:
            pan_y = self.panValues[1]
            self.prevPanValues[1] = self.panValues[1]
        elif self.active_window[1] + self.panValues[1] < 0:
            pan_y = -self.active_window[1]
            self.panValues[1] = pan_y
            self.prevPanValues[1] = self.panValues[1]
        elif self.active_window[3] + self.panValues[1] > self.videoHeight:
            pan_y = self.videoHeight - self.active_window[3]
            self.panValues[1] = pan_y
            self.prevPanValues[1] = self.panValues[1]
        else:
            self.panValues[1] = self.prevPanValues[1]
            pan_y = self.prevPanValues[1]

        last_sample = last_sample[self.active_window[1] +
                                  pan_y:self.active_window[3] + pan_y,
                                  self.active_window[0] +
                                  pan_x:self.active_window[2] + pan_x, :]

        # if self.isFlipped:
        #     last_sample = numpy.rot90(last_sample, k=2)

        last_sample = cv2.resize(last_sample,
                                 (self.videoWidth, self.videoHeight),
                                 interpolation=cv2.INTER_LINEAR)

        # if self.lastSample is not None:
        #     self.previousSample = self.lastSample.copy()

        self.lastSample = last_sample
        # text overlay
        shift = 30
        for text in self.overlayText.split("--"):
            cv2.putText(last_sample, text, (10, shift),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0, 255), 2,
                        cv2.LINE_AA)
            shift += 30

        # update surface
        self.video_check(last_sample)
        # print("stop", time.time() - t0)
        return Gst.FlowReturn.OK

    @staticmethod
    def get_last_sample_as_np(sample):
        buf = sample.get_buffer()
        (result, map_info) = buf.map(Gst.MapFlags.READ)
        caps = sample.get_caps()
        arr = numpy.ndarray((caps.get_structure(0).get_value('height'),
                             caps.get_structure(0).get_value('width'), 4),
                            buffer=map_info.data,
                            dtype='B')

        buf.unmap(map_info)
        return arr

    def zoom_in(self):
        if self.videoWidth is not None and self.videoHeight is not None:
            if self.zoomCount < self.maxZoom:
                self.zoomCount += 1
                self.zoom()
            else:
                self.zoomCount = self.maxZoom

    def zoom_out(self):
        if self.videoWidth is not None and self.videoHeight is not None:
            if self.zoomCount > 1:
                self.zoomCount -= 1
                self.zoom()

    def reset_zoom(self):
        if self.videoWidth is not None and self.videoHeight is not None:
            self.zoomCount = 1
            self.active_window = [0, 0, self.videoWidth, self.videoHeight]
            self.panValues[0] = 0
            self.panValues[1] = 0

    def zoom(self):
        if self.videoWidth is not None and self.videoHeight is not None:
            temp = [
                self.videoWidth * (self.zoomCount - 1) / self.zoomCount / 2,
                self.videoHeight * (self.zoomCount - 1) / self.zoomCount / 2,
                self.videoWidth - self.videoWidth *
                (self.zoomCount - 1) / self.zoomCount / 2, self.videoHeight -
                self.videoHeight * (self.zoomCount - 1) / self.zoomCount / 2
            ]

            self.active_window = [int(x) for x in temp]

    def flip_surface(self):
        self.isFlipped = not self.isFlipped

    def pan_image(self):
        self.panValues = [x + 10 for x in self.panValues]

    def start(self):
        self.pipe.set_state(Gst.State.PLAYING)

    def stop(self):
        self.pipe.set_state(Gst.State.PAUSED)

    def close_player(self):
        if self.videoCheckTimer.isActive():
            self.videoCheckTimer.stop()

        if self.motionMessagePopup.isOpen:
            self.motionMessagePopup.closeThis()

        if self.pipe is not None:
            self.isClosing = True
            self.pipe.set_state(Gst.State.NULL)
            # self.pipe.send_event(Gst.Event.new_eos())
            if self.isRecorderSetUp:
                self.videoWriter.release()

    def set_video_src(self, video_source_str):
        if self.pipe is not None:
            self.pipe.set_state(Gst.State.NULL)
            # self.pipe.send_event(Gst.Event.new_eos())
        #
        # if self.pipe is None or refresh:
        pipe_str = video_source_str + \
                   '! videoconvert ! videoscale ' \
                   '! video/x-raw, format=RGBA ' \
                   '! videoflip method=0 name=flip ' \
                   '! appsink name=asink emit-signals=1 drop=true max-buffers=0 '

        print(pipe_str)
        self.pipe = Gst.parse_launch(pipe_str)
        self.appSrc = self.pipe.get_by_name('src')
        self.appSink = self.pipe.get_by_name('asink')
        self.appSink.connect("new-sample", self.update_last_sample,
                             self.appSink)
        self.videoFlipElement = self.pipe.get_by_name('flip')
        bus = self.pipe.get_bus()
        bus.add_signal_watch()
        bus.enable_sync_message_emission()
        bus.connect("message::error", self.on_error)
        # bus.connect("message::eos", self.on_eos)

        self.videoSourceStr = video_source_str
        if self.demandedState == "play":
            self.start()
        else:
            self.stop()

    def on_error(self, bus, msg):
        err, dbg = msg.parse_error()
        print("ERROR:", msg.src.get_name(), ":", err.message)

    # def on_eos(self, bus, msg):
    #     print("End-Of-Stream reached")
    #     if not self.isClosing:
    #         self.pipe.set_state(Gst.State.NULL)
    #         self.set_video_src(self.videoSourceStr, refresh=True)

    def screen_shot(self, save_dir):
        print("save_dir", save_dir)
        if self.lastSample is not None:
            cv2.imwrite(save_dir,
                        cv2.cvtColor(self.lastSample, cv2.COLOR_RGBA2BGRA))
            return True
        return False
    def __init__(self,
                 message,
                 timeout=None,
                 platform=None,
                 error=False,
                 pause=None,
                 progressFn=None,
                 addCloseButton=False):
        super().__init__()
        print("message initted", message)
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        # self.setWindowFlag(QtCore.Qt.Popup)

        if addCloseButton:
            self.setWindowTitle("Bilgi")
            f = QtCore.Qt.WindowStaysOnTopHint
            self.setWindowFlags(f)
        else:
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                                | QtCore.Qt.FramelessWindowHint)

        self.isSizeFixed = False

        self.isOpen = False
        self.error = error
        self.resources = Resources()
        self.layout = QtWidgets.QVBoxLayout()
        self.messageLabel = QtWidgets.QLabel()
        self.messageLabel.setText(message)
        self.messageLabel.setWordWrap(True)

        self.setMyStyleSheet()

        self.layout.addWidget(self.messageLabel)

        if addCloseButton:
            closeButton = QtWidgets.QPushButton(self.resources.get("close_3"))
            closeButton.clicked.connect(self.closeThis)

            self.layout.addWidget(closeButton)

        self.setLayout(self.layout)

        if progressFn is not None:
            self.progress = threading.Timer(interval=1, function=progressFn)
            self.progress.daemon = True
            self.progress.start()

        if pause is not None:
            self.isOpen = True
            self.show()
            time.sleep(float(pause / 1000))
            self.closeMessagePopupSc()

        elif timeout is not None:
            self.timer = threading.Timer(interval=float(timeout / 1000),
                                         function=self.closeMessagePopupSc)
            self.timer.daemon = True
            self.timer.start()
            self.isOpen = True
            self.show()

        # else:
        #     self.exec_()

        if progressFn is not None:
            progressFn()
class MessagePopup(QtWidgets.QDialog):
    def __init__(self,
                 message,
                 timeout=None,
                 platform=None,
                 error=False,
                 pause=None,
                 progressFn=None,
                 addCloseButton=False):
        super().__init__()
        print("message initted", message)
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        # self.setWindowFlag(QtCore.Qt.Popup)

        if addCloseButton:
            self.setWindowTitle("Bilgi")
            f = QtCore.Qt.WindowStaysOnTopHint
            self.setWindowFlags(f)
        else:
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                                | QtCore.Qt.FramelessWindowHint)

        self.isSizeFixed = False

        self.isOpen = False
        self.error = error
        self.resources = Resources()
        self.layout = QtWidgets.QVBoxLayout()
        self.messageLabel = QtWidgets.QLabel()
        self.messageLabel.setText(message)
        self.messageLabel.setWordWrap(True)

        self.setMyStyleSheet()

        self.layout.addWidget(self.messageLabel)

        if addCloseButton:
            closeButton = QtWidgets.QPushButton(self.resources.get("close_3"))
            closeButton.clicked.connect(self.closeThis)

            self.layout.addWidget(closeButton)

        self.setLayout(self.layout)

        if progressFn is not None:
            self.progress = threading.Timer(interval=1, function=progressFn)
            self.progress.daemon = True
            self.progress.start()

        if pause is not None:
            self.isOpen = True
            self.show()
            time.sleep(float(pause / 1000))
            self.closeMessagePopupSc()

        elif timeout is not None:
            self.timer = threading.Timer(interval=float(timeout / 1000),
                                         function=self.closeMessagePopupSc)
            self.timer.daemon = True
            self.timer.start()
            self.isOpen = True
            self.show()

        # else:
        #     self.exec_()

        if progressFn is not None:
            progressFn()

    def openThis(self):
        self.isOpen = True
        self.show()
        # self.exec_()

    def closeThis(self):
        self.close()
        self.isOpen = False

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.isOpen = False

    def setMyStyleSheet(self):
        self.resources.set_color(self, self.resources.get_primary_color())
        self.setStyleSheet(self.resources.styleSheet())
        if not self.error:
            self.messageLabel.setStyleSheet(
                "QLabel{font: 50px bold; color : " +
                self.resources.secondaryColor + ";}")

        else:
            self.messageLabel.setStyleSheet(
                "QLabel{font: 50px bold; color : " + self.resources.error +
                ";}")

    def closeMessagePopupSc(self):
        self.close()
        self.isOpen = False

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.WindowStateChange:
            if self.isMinimized() or self.isMaximized():
                self.showNormal()
    def __init__(self, user_permission, parent=None):
        super().__init__(parent=parent)
        self.isAnAppRunning = False
        self.resources = Resources()
        layout = QtWidgets.QVBoxLayout(self)
        # layout.set(QtCore.Qt.RightToLeft)
        # layout.setAlignment(QtCore.Qt.AlignRight)
        layout.setContentsMargins(10, 10, 10, 10)

        disk_usage_info_label = QtWidgets.QLabel("")
        # disk_usage_info_label.setFixedSize(400, 30)

        disk_progress_bar = DiskProgressBar(label=disk_usage_info_label)
        # disk_progress_bar.setFixedSize(100, 30)

        layout2 = QtWidgets.QHBoxLayout()

        panel_app = self.create_menu_item(
            "Panel", self.launch_to_panel,
            UKBParams.dirResources + "dashboard-3-128.png")
        records_app = self.create_menu_item(
            "Kayıtlar", self.launch_to_records,
            UKBParams.dirResources + "film-2-128.png")
        tile_importer_app = self.create_menu_item(
            "Harita Yükle", self.launch_to_tile_importer,
            UKBParams.dirResources + "internet-128.png")
        # thermal_test_app = self.create_menu_item("Termal Test", self.launch_to_thermal_test, UKBParams.dirResources + "internet-128.png")
        close_app = self.create_menu_item(
            "Kapat", self.launch_to_close,
            UKBParams.dirResources + "power-128.png")
        info_app = self.create_menu_item(
            None, self.launch_to_info,
            UKBParams.dirResources + "info-2-32.png")
        info_app.setFixedSize(50, 50)
        # info_app = PicButton(UKBParams.dirResources + "info-2-32.png")
        # info_app.clicked.connect(self.launch_to_info)

        layout2.addWidget(panel_app)
        if user_permission > 0:
            layout2.addWidget(records_app)
        if SysParams.tag == "ukb-7":
            layout2.addWidget(tile_importer_app)
            # layout2.addWidget(thermal_test_app)
        layout2.addWidget(close_app)
        layout2.setSpacing(5)
        layout2.setContentsMargins(0, 0, 0, 0)

        self.infoBox = QtWidgets.QLabel("Hazır")
        self.infoBox.setMaximumHeight(40)
        self.infoBox.setAlignment(QtCore.Qt.AlignCenter)

        self.chooseIkaComboBox = QtWidgets.QComboBox()
        self.chooseIkaComboBox.addItem("Komodo")
        self.chooseIkaComboBox.addItem("Ejder")

        self.destructTimeComboBox = QtWidgets.QComboBox()
        self.destructTimeComboBox.addItem("0")
        self.destructTimeComboBox.addItem("15")
        self.destructTimeComboBox.addItem("30")
        self.destructTimeComboBox.addItem("45")
        self.destructTimeComboBox.addItem("60")

        self.coordinateTypeComboBox = QtWidgets.QComboBox()
        self.coordinateTypeComboBox.addItem(
            self.resources.get("decimal_coord"))
        self.coordinateTypeComboBox.addItem(
            self.resources.get("military_coord"))

        self.disconnectionPolicyComboBox = QtWidgets.QComboBox()
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("connection_loss_rule"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_return_home"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_destruct").replace(
                "\\n", "\n"))
        # self.disconnectionPolicyComboBox.setFixedWidth(100)

        self.failedHomeActioonPolicyComboBox = QtWidgets.QComboBox()
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("home_fail_rule"))
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("if_return_failed_do_nothing"))
        self.failedHomeActioonPolicyComboBox.addItem(
            self.resources.get("if_return_failed_destruct"))

        # info_app = QtWidgets.QPushButton()
        # info_app.clicked.connect(self.launch_to_info)

        layout.setAlignment(QtCore.Qt.AlignCenter)
        layout.addLayout(
            self.layout_packer(
                [info_app, disk_usage_info_label, disk_progress_bar]))
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(layout2)
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addWidget(self.infoBox)
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(
            self.layout_packer(
                [self.chooseIkaComboBox, self.destructTimeComboBox]))
        layout.addWidget(QtWidgets.QLabel(""))
        layout.addLayout(
            self.layout_packer([
                self.coordinateTypeComboBox, self.disconnectionPolicyComboBox
            ]))
        layout.addWidget(QtWidgets.QLabel(""))
Exemple #17
0
    def __init__(self, parent=None):
        super(LoginView, self).__init__(parent=parent)

        self.loggedIn = False
        self.resources = Resources()

        if SysParams.tag == "ukb-7":
            self.iconContainer = QWidget()
            self.iconContainer.setContentsMargins(0, 0, 0, 0)
            layout = QHBoxLayout()
            layout.setSpacing(0)
            layout.setContentsMargins(0, 0, 0, 0)
            self.icon = QLabel()
            self.icon = PicButton(
                QPixmap(UKBParams.dirResources + self.iconName))
            width = 100
            r = 1 / 1
            self.icon.setFixedSize(width, int(width * r))
            layout.addWidget(self.icon)
            self.iconContainer.setLayout(layout)

        # define widgets
        self.loginUserNameLine = QComboBox()
        self.loginUserNameLine.addItem(self.resources.get("admin"))
        self.loginUserNameLine.addItem(self.resources.get("user_2"))

        self.loginPasswordLine = MyLineEdit()
        self.loginPasswordLine.setEchoMode(QLineEdit.Password)
        self.loginPasswordLine.setPlaceholderText(
            self.resources.get("password"))
        self.loginPasswordLine.mousePressed = self.update_current_widget
        self.current_widget = self.loginPasswordLine

        self.loginNew1PasswordLine = MyLineEdit()
        self.loginNew1PasswordLine.setEchoMode(QLineEdit.Password)
        self.loginNew1PasswordLine.setPlaceholderText(
            self.resources.get("new_password"))
        self.loginNew1PasswordLine.mousePressed = self.update_current_widget
        self.loginNew1PasswordLine.setVisible(False)

        self.loginNew2PasswordLine = MyLineEdit()
        self.loginNew2PasswordLine.setEchoMode(QLineEdit.Password)
        self.loginNew2PasswordLine.setPlaceholderText(
            self.resources.get("new_password_again"))
        self.loginNew2PasswordLine.mousePressed = self.update_current_widget
        self.loginNew2PasswordLine.setVisible(False)

        self.moreOptionsLabel = ClickAbleLabel()
        self.moreOptionsLabel.setText(self.resources.get("more"))
        self.moreOptionsLabel.clickedFn = self.open_more_options

        self.closeLabel = ClickAbleLabel()
        self.closeLabel.setText(self.resources.get("close_2"))
        self.closeLabel.setVisible(False)

        self.coordinateTypeComboBox = QComboBox()
        self.coordinateTypeComboBox.addItem(
            self.resources.get("decimal_coord"))
        self.coordinateTypeComboBox.addItem(
            self.resources.get("military_coord"))

        self.disconnectionPolicyComboBox = QComboBox()
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("connection_loss_rule"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_return_home"))
        self.disconnectionPolicyComboBox.addItem(
            self.resources.get("if_disconnected_destruct"))

        self.loginFromSubmitButton = QPushButton(self.resources.get('login'))
        # self.loginFromSubmitButton.clicked.connect(self.loginFromSubmitButtonOnClick)

        self.loginInfoBox = QLabel("")
        # self.loginInfoBox.setFont(QtGui.QFont("Times", 16, QtGui.QFont.Bold))

        # keyboard
        keyboard_layout = QHBoxLayout()
        keyboard_layout.setSpacing(5)

        for n, ch in enumerate("0123456789<"):
            bt = MyButton(ch)
            bt.effect = ch
            bt.setOnClick(self.virtual_keyboard)
            bt.setMaximumWidth(50)

            keyboard_layout.addWidget(bt)

        # temp
        self.loginPasswordLine.setText('123456')

        # define forms
        self.loginFormLayoutWidget = QFrame()
        self.loginFormLayout = QFormLayout(self.loginFormLayoutWidget)
        zeroLabel = QLabel("")
        zeroLabel.setFixedSize(0, 20)
        if SysParams.tag == "ukb-7":
            self.loginFormLayout.addRow("", self.iconContainer)
        self.loginFormLayout.addRow("", self.loginUserNameLine)
        self.loginFormLayout.addRow("", self.loginPasswordLine)
        self.loginFormLayout.addRow("", self.loginNew1PasswordLine)
        self.loginFormLayout.addRow("", self.loginNew2PasswordLine)
        # self.loginFormLayout.addRow("", self.coordinateTypeComboBox)
        # self.loginFormLayout.addRow("", self.disconnectionPolicyComboBox)
        self.loginFormLayout.addRow("", self.loginFromSubmitButton)
        self.loginFormLayout.addRow("", self.closeLabel)
        self.loginFormLayout.addRow("", self.loginInfoBox)
        self.loginFormLayout.addRow("", self.moreOptionsLabel)
        self.loginFormLayout.addRow("", keyboard_layout)

        # define layout
        self.layout = QVBoxLayout()

        # style
        self.setContentsMargins(50, 5, 50, 0)  # left, top, right, bottom
        self.layout.setSpacing(1)
        self.loginFormLayout.setContentsMargins(0, 0, 0, 0)

        # add to layout
        self.layout.addWidget(self.loginFormLayoutWidget)
        self.setLayout(self.layout)
Exemple #18
0
    def __init__(self, video_source_str, save_dir=None, parent=None):
        super().__init__(parent=parent, pan_values=[0, 0])
        self.setScaledContents(True)
        self.softPlay = True
        self.isMotionEnabledDetection = False
        self.isMotionDetected = False
        self.lastMotionTime = time.time()

        # gunCam = GunCamera()
        # self.flipTransform = QtGui.QTransform()
        # self.flipTransform.rotate(180)
        self.videoFlipElement = None
        self.overlayText = ""

        self.active_window = None
        self.videoWidth = None
        self.videoHeight = None
        self.zoomCount = 1
        self.maxZoom = 10
        self.isFlipped = False
        self.currentFlipMode = 0
        self.panValues = [0, 0]
        self.prevPanValues = [0, 0]
        self.demandedState = "play"
        self.isSurfaceScaled = False
        self.lastSampleTime = time.time()
        self.videoSourceStr = video_source_str

        # self.isGunCamera = gunCam.cameraState

        self.pipe = None
        self.appSrc = None
        self.appSink = None
        self.lastSample = None
        self.previousSample = None
        self.isClosing = False
        self.arr = None
        # self.isEOSDone = False
        self.pixmap = None

        self.set_video_src(video_source_str)

        self.setContentsMargins(0, 0, 0, 0)

        self.scaleHeight = self.geometry().size().height() - 0

        self.saveDir = save_dir
        self.isRecordEnabled = False
        self.isRecorderSetUp = False
        self.fourcc = None
        self.videoWriter = None
        if save_dir is not None:
            # self.isRecordEnabled = True
            self.fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            self.videoWriter = None

        self.videoCheckTimer = QtCore.QTimer()
        self.videoCheckTimer.setInterval(250)
        self.videoCheckTimer.timeout.connect(self.video_check_2)
        self.videoCheckTimer.start()

        self.resources = Resources()
        self.motionMessagePopup = MessagePopup(
            self.resources.get("motion_detected"), addCloseButton=True)
class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.loginTab = None
        self.launcherTab = None
        self.loggedIn = False
        self.userPermission = 0
        self.resources = Resources()
        self.init_ui()

    def init_ui(self):
        # side panel
        self.sidePanel = SidePanel()
        self.sidePanel.init()

        # add widgets
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.sidePanel)
        self.setLayout(self.layout)
        # stylesheet
        self.setMyStyleSheet()
        # set first window
        self.callLogintab()
        self.showFullScreen()
        # self.showMaximized()

    def setMyStyleSheet(self):
        self.setContentsMargins(0, 0, 0, 0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.resources.set_color(self.sidePanel,
                                 self.resources.get_primary_color())
        self.resources.set_color(self, self.resources.get_primary_color())
        self.setStyleSheet(self.resources.styleSheet())

    def callLogintab(self):
        if self.loginTab is None:
            self.loginTab = LoginTab()
            self.loginTab.setLoginSuccesFunction(self.loginSucces)
            self.loginTab.closeLabel.clickedFn = self.closeApp
            # self.loginTab.setLogoutFunction(self.closeApp)

        self.sidePanel.loadPanel(self.loginTab)

    def loginSucces(self):
        # if self.joystickPatternDetector.powerPimState:
        self.loggedIn = True
        if self.loginTab.userName == "admin":
            self.userPermission = 1
        else:
            self.userPermission = 0
        self.launcherTab = LauncherTab(self.userPermission)
        # self.panelTab.closeButton.clicked.connect(self.closeApp)
        self.sidePanel.loadPanel(self.launcherTab)
        # if self.userPermission == 1:
        # self.communicationProcess.start()
        # else:
        #     self.loginTab.loginInfoBoxMessage(self.resources.get('pim_not_inserted'), 'error')

    def closeApp(self, is_shutdown=False):
        # if self.communicationProcess is not None:
        #     self.communicationProcess.kill = True
        # if self.panelTab is not None:
        #     self.panelTab.close_this()

        if is_shutdown:
            subprocess.call("sudo shutdown now", shell=True)
        else:
            self.close()