Browse Source

Addded a ghetto button selection dialog

curiousmuch 7 years ago
parent
commit
2eff285f80
5 changed files with 223 additions and 68 deletions
  1. 96 20
      IdeasXWSCBackend.py
  2. 74 17
      IdeasXWSCView.py
  3. 3 0
      ParsingTools.py
  4. 31 18
      Qt/encoderconfigurationdialog.ui
  5. 19 13
      encoderconfigurationdialog.py

+ 96 - 20
IdeasXWSCBackend.py

@@ -80,6 +80,7 @@ class IdeasXWSCNetworkThread(QObject):
         self._dataParser = IdeasXMessages.DataMessage()
         self._commandParser = IdeasXMessages.CommandMessage()
         self._parserTools = ParsingTools()
+        self.keyEmulator = IdeasXKeyEmulator()
         
         # MQTT Client Object
         self._mqttc = mqtt.Client(self.__clientID, clean_session=True, userdata=None, protocol='MQTTv311')
@@ -126,6 +127,7 @@ class IdeasXWSCNetworkThread(QObject):
         try: 
             self._dataParser.ParseFromString(msg.payload)
             print("GPIO States: " + bin(self._dataParser.button))
+            #self.__keyEmulator.emulateKey( self._parserTools.getModuleIDfromTopic(msg.topic),self._dataParser.button)
         except: 
             self.printError("Failure to parse message")
             if self.__debug:
@@ -288,15 +290,71 @@ class IdeasXWSCNetworkThread(QObject):
     def printInfo(self, msgStr):
         print("WSC: " + msgStr)
         
-class IdeasXDeviceTypes():
-    def __init__(self): 
-        self.encoder = 'encoder'
-        self.actuator = 'actuator'
-                
+
+from pykeyboard import PyKeyboard
+        
+class IdeasXKeyEmulator():
+    def __init__(self):
+        self.__system = sys.platform
+        self.printInfo("Detected system is " + self.__system) 
+        self.__k = PyKeyboard() 
+        self.switchOne = 0
+        self.switchTwo = 1
+        self.switchAdaptive = 2
+        self.__assignedKeys = {'default': {self.switchOne: ["1", True], 
+                                           self.switchTwo: ["2", True], 
+                                           self.switchAdaptive: ["3", True]}}
+        self.__activeEncoders = []
         
+    def activateEncoder(self, encoder):
+        if encoder not in self.__activeEncoders: 
+            self.__activeEncoders.append(encoder)
+
+    def deactivateEncoder(self, encoder):
+        if encoder in self.__activeEncoders:
+            self.__activeEncoders.pop(encoder)
+        
+    def assignKey(self, encoder, switch, key, active=True):
+        if switch not in [self.switchOne, self.switchTwo, self.switchAdaptive]:  
+            raise ValueError("Must be IdeasXKeyEmulator() provided switch")
+                        
+        if encoder not in self.__assignedKeys.keys(): 
+            self.__assignedKeys[encoder] = self.__assignedKeys['default']
+        self.__assignedKeys[encoder][switch] = [key, active]
+        if active == False: 
+            self.__k.release_key(key)
+        
+    def getAssignedKey(self, encoder, switch):
+        if encoder not in self.__assignedKeys.keys(): 
+            encoder = 'default'
+        return self.__assignedKeys[encoder][switch]
+        
+    def emulateKey(self, encoder, buttonPayload, deviceType=None):
+        '''
+             This is horrible and needs to be improved
+        '''
+        if encoder in self.__activeEncoders or True: 
+            if encoder not in self.__assignedKeys.keys(): 
+                encoder = 'default'
+            assignedKeys = self.__assignedKeys[encoder]
+            
+            for switch in [self.switchOne, self.switchTwo, self.switchAdaptive]:  
+                if (buttonPayload&(1<<switch)!=0):
+                    self.__k.press_key(assignedKeys[switch][0])
+                else: 
+                    self.__k.release_key(assignedKeys[switch][0])
 
+            
+    def printInfo(self, msg):
+        print("EM: " + msg)    
+        
+    
+    #def emulatePress(self, buttonPayload):
+        
+        
+        
 if __name__ == "__main__": 
-    Host = "ideasx.duckdns.org"
+    Host = "ideasx.dnuckdns.org"
 #    Host = "192.168.0.101"
 #    Host = "10.42.0.1"
     Port = 1883 
@@ -307,19 +365,37 @@ if __name__ == "__main__":
     cmdArg = None;
     cmdTest = False; 
     
+    encodeId = '23:34'
     
-    wsc = WorkstationClientClass()
-        
-    if cmdTest: 
-        wsc.cmdStartWorkstationClient(Host, Port, KeepAlive)
-    else: 
-        wsc.guiStartWorkstationClient(Host, Port, KeepAlive)
-        time.sleep(3)
-        wsc.activateEncoder('18:fe:34:f1:f2:8d')
-        print(wsc.subscribedEncoders)
-        time.sleep(2)
-        wsc.deactivateEncoder('18:fe:34:f1:f2:8d')
-        print(wsc.subscribedEncoders)
-        time.sleep(10)
-        wsc.killWSC()
+    km = IdeasXKeyEmulator()
+    
+    km.activateEncoder(encodeId)
+    km.emulateKey(encodeId, 1)
+    time.sleep(0.1)
+    km.emulateKey(encodeId, 0) 
+    time.sleep(0.1)
+
+    km.emulateKey(encodeId, 2)
+    time.sleep(0.1)
+    km.emulateKey(encodeId, 0)
+    time.sleep(0.1)
+    km.emulateKey(encodeId, 4)
+    time.sleep(0.1)
+    km.emulateKey(encodeId, 0)
+    
+    
+#     wsc = WorkstationClientClass()
+#         
+#     if cmdTest: 
+#         wsc.cmdStartWorkstationClient(Host, Port, KeepAlive)
+#     else: 
+#         wsc.guiStartWorkstationClient(Host, Port, KeepAlive)
+#         time.sleep(3)
+#         wsc.activateEncoder('18:fe:34:f1:f2:8d')
+#         print(wsc.subscribedEncoders)
+#         time.sleep(2)
+#         wsc.deactivateEncoder('18:fe:34:f1:f2:8d')
+#         print(wsc.subscribedEncoders)
+#         time.sleep(10)
+#         wsc.killWSC()
         

+ 74 - 17
IdeasXWSCView.py

@@ -8,6 +8,26 @@ from IdeasXWSCBackend import IdeasXWSCNetworkThread
 from ParsingTools import ParsingTools
 from encoderconfigurationdialog import Ui_SwitchConfigDialog
 
+
+class IdeasXSwitchDialog(QtWidgets.QDialog):
+    
+    def __init__(self, switch, assignedKey): 
+        super(IdeasXSwitchDialog, self).__init__()
+        self.__ui = Ui_SwitchConfigDialog()
+        self.__ui.setupUi(self)
+        self.__ui.buttonApply.clicked.connect(self.submitOnClose)
+        self.key = assignedKey[0]
+        self.enable = assignedKey[1]
+        self.switch = switch
+        
+        self.__ui.checkSwitchEnable.setChecked(self.enable)
+        self.__ui.lineSwitchKey.setText(self.key)
+        
+    def submitOnClose(self):
+        self.key = self.__ui.lineSwitchKey.text() 
+        self.enable = self.__ui.checkSwitchEnable.isChecked()
+        self.accept()
+
 class IdeasXDeviceManager():
     def __init__(self, deviceClass, wsc): 
         self.__devices = {} 
@@ -53,7 +73,8 @@ class IdeasXEncoder(QtWidgets.QWidget):
         # This should become a static variable for the class
         self.__pathToIcon = {'network': './icon/network/', 
                              'battery': './icon/battery/', 
-                             'battery_charging': './icon/battery/'
+                             'battery_charging': './icon/battery/',
+                             'switch': './icon/switch/'
                             }
         self.__icon = {'network': ['network-wireless-offline-symbolic.png',
                                    'network-wireless-signal-weak-symbolic.png',
@@ -69,7 +90,13 @@ class IdeasXEncoder(QtWidgets.QWidget):
                                              'battery-caution-charging-symbolic.png', 
                                              'battery-low-charging-symbolic.png', 
                                              'battery-good-charging-symbolic.png', 
-                                             'battery-full-charged-symbolic.png']
+                                             'battery-full-charged-symbolic.png'],
+                        'switch': ['switch-one-enabled.png', 
+                                   'switch-one-disabled.png', 
+                                   'switch-two-enabled.png', 
+                                   'switch-two-disabled.png', 
+                                   'switch-adpative-enabled.png', 
+                                   'switch-adaptive-disabled.png']
                        }
         self.__deviceType = 'encoder'
         self.__wsc = wsc
@@ -82,28 +109,58 @@ class IdeasXEncoder(QtWidgets.QWidget):
 
         self.setupMenu()
         self.__ui.buttonActivate.clicked.connect(self.activateEncoder)
-        self.__ui.buttonSwitchOne.clicked.connect(self.openSwitchDialog)
-        self.__ui.buttonSwitchTwo.clicked.connect(self.openSwitchDialog)
-
-    def openSwitchDialog(self):
-        dialog = QtWidgets.QDialog()
-        dialog.ui = Ui_SwitchConfigDialog()
-        dialog.ui.setupUi(dialog)
-        dialog.exec_()
-             
+        self.__ui.buttonSwitchOne.clicked.connect(lambda: self.openSwitchDialog(self.__wsc.keyEmulator.switchOne,
+                                                                                 self.__wsc.keyEmulator.getAssignedKey(self.__strModuleID, self.__wsc.keyEmulator.switchOne)))
+        self.__ui.buttonSwitchTwo.clicked.connect(lambda: self.openSwitchDialog(self.__wsc.keyEmulator.switchTwo,
+                                                                                self.__wsc.keyEmulator.getAssignedKey(self.__strModuleID, self.__wsc.keyEmulator.switchTwo)))
+    
+    def openSwitchDialog(self, switch, assignedKey):
+        dialog = IdeasXSwitchDialog(switch, assignedKey)
+        if dialog.exec_():                
+            if dialog.key != None or len(dialog.key) == 1: 
+                self.__wsc.keyEmulator.assignKey(self.__strModuleID, dialog.switch, dialog.key, dialog.enable)
+                
+                # Think of a better way to do this
+                if dialog.enable: 
+                    if switch == self.__wsc.keyEmulator.switchOne: 
+                        self.__ui.buttonSwitchOne.setIcon(self.setupSwitchIcon(self.__icon['switch'][0]))
+                        
+                    if switch == self.__wsc.keyEmulator.switchTwo:
+                        self.__ui.buttonSwitchTwo.setIcon(self.setupSwitchIcon(self.__icon['switch'][2]))
+                        
+                    if switch == self.__wsc.keyEmulator.switchAdaptive:
+                        self.__ui.buttonSwitchAdaptive.setIcon(self.setupSwitchIcon(self.__icon['switch'][4]))
+                        
+                if dialog.enable == False: 
+                    if switch == self.__wsc.keyEmulator.switchOne: 
+                        self.__ui.buttonSwitchOne.setIcon(self.setupSwitchIcon(self.__icon['switch'][1]))
+                        
+                    if switch == self.__wsc.keyEmulator.switchTwo:
+                        self.__ui.buttonSwitchTwo.setIcon(self.setupSwitchIcon(self.__icon['switch'][3]))
+                        
+                    if switch == self.__wsc.keyEmulator.switchAdaptive:
+                        self.__ui.buttonSwitchAdaptive.setIcon(self.setupSwitchIcon(self.__icon['switch'][5]))
+                        
+    def setupSwitchIcon(self, path):
+        icon = QtGui.QIcon()
+        iconPath = self.__pathToIcon['switch']
+        iconPath = iconPath + path
+        icon.addPixmap(QtGui.QPixmap(iconPath), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+        return icon
+              
     def setupMenu(self):
         shutdownAction = QtWidgets.QAction('Shutdown Encoder', self)
         shutdownAction.triggered.connect(lambda: self.__wsc.shutdownDevice(self.__strModuleID, None))
         
         deviceMenu = QtWidgets.QMenu()
-        deviceMenu.addSection("General Actions")
-        deviceMenu.addAction("Pair Encoder with Actuator")
-        deviceMenu.addAction("Train Adaptive Switch")
-        deviceMenu.addAction("Configure Module")
+        #deviceMenu.addSection("General Actions")
+        #deviceMenu.addAction("Pair Encoder with Actuator")
+        #deviceMenu.addAction("Train Adaptive Switch")
+        #deviceMenu.addAction("Configure Module")
         deviceMenu.addSection("Encoder Commands")
         deviceMenu.addAction(shutdownAction)
-        deviceMenu.addAction("Restart Encoder")
-        deviceMenu.addAction("Update Firmware")
+        #deviceMenu.addAction("Restart Encoder")
+       # deviceMenu.addAction("Update Firmware")
         
         self.__ui.buttonMenu.setPopupMode(2)
         self.__ui.buttonMenu.setMenu(deviceMenu)

+ 3 - 0
ParsingTools.py

@@ -13,6 +13,9 @@ class ParsingTools():
     def calculateSOC(self, raw_SOC):
         return raw_SOC.to_bytes(2, 'big')[0]
     
+    def getModuleIDfromTopic(self, topic):
+        return topic.split('/')[2]
+    
 class FieldGenerator():
     def generateMACID(self):
         import numpy as np

+ 31 - 18
Qt/encoderconfigurationdialog.ui

@@ -7,7 +7,7 @@
     <x>0</x>
     <y>0</y>
     <width>217</width>
-    <height>110</height>
+    <height>190</height>
    </rect>
   </property>
   <property name="windowTitle">
@@ -19,22 +19,8 @@
      <property name="title">
       <string>Switch Configuration:</string>
      </property>
-     <layout class="QFormLayout" name="formLayout">
-      <item row="0" column="1">
-       <widget class="QCheckBox" name="checkSwitchEnable">
-        <property name="text">
-         <string>Enable</string>
-        </property>
-       </widget>
-      </item>
-      <item row="1" column="1">
-       <widget class="QSpinBox" name="spinLatchTime">
-        <property name="suffix">
-         <string> sec.</string>
-        </property>
-       </widget>
-      </item>
-      <item row="0" column="0">
+     <layout class="QGridLayout" name="gridLayout">
+      <item row="1" column="0" colspan="2">
        <widget class="QLineEdit" name="lineSwitchKey">
         <property name="text">
          <string/>
@@ -47,13 +33,40 @@
         </property>
        </widget>
       </item>
-      <item row="1" column="0">
+      <item row="2" column="0">
        <widget class="QLabel" name="labelLatch">
         <property name="text">
          <string>Latching Delay:</string>
         </property>
        </widget>
       </item>
+      <item row="4" column="1">
+       <widget class="QPushButton" name="buttonApply">
+        <property name="text">
+         <string>Apply</string>
+        </property>
+       </widget>
+      </item>
+      <item row="0" column="0" colspan="2">
+       <widget class="QCheckBox" name="checkSwitchEnable">
+        <property name="text">
+         <string>Enable Switch</string>
+        </property>
+       </widget>
+      </item>
+      <item row="3" column="0" colspan="2">
+       <widget class="QSpinBox" name="spinLatchTime">
+        <property name="suffix">
+         <string> seconds</string>
+        </property>
+        <property name="maximum">
+         <number>60</number>
+        </property>
+        <property name="singleStep">
+         <number>1</number>
+        </property>
+       </widget>
+      </item>
      </layout>
     </widget>
    </item>

+ 19 - 13
encoderconfigurationdialog.py

@@ -11,27 +11,32 @@ from PyQt5 import QtCore, QtGui, QtWidgets
 class Ui_SwitchConfigDialog(object):
     def setupUi(self, SwitchConfigDialog):
         SwitchConfigDialog.setObjectName("SwitchConfigDialog")
-        SwitchConfigDialog.resize(217, 110)
+        SwitchConfigDialog.resize(217, 190)
         self.verticalLayout = QtWidgets.QVBoxLayout(SwitchConfigDialog)
         self.verticalLayout.setObjectName("verticalLayout")
         self.groupBox = QtWidgets.QGroupBox(SwitchConfigDialog)
         self.groupBox.setObjectName("groupBox")
-        self.formLayout = QtWidgets.QFormLayout(self.groupBox)
-        self.formLayout.setObjectName("formLayout")
-        self.checkSwitchEnable = QtWidgets.QCheckBox(self.groupBox)
-        self.checkSwitchEnable.setObjectName("checkSwitchEnable")
-        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.checkSwitchEnable)
-        self.spinLatchTime = QtWidgets.QSpinBox(self.groupBox)
-        self.spinLatchTime.setObjectName("spinLatchTime")
-        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.spinLatchTime)
+        self.gridLayout = QtWidgets.QGridLayout(self.groupBox)
+        self.gridLayout.setObjectName("gridLayout")
         self.lineSwitchKey = QtWidgets.QLineEdit(self.groupBox)
         self.lineSwitchKey.setText("")
         self.lineSwitchKey.setClearButtonEnabled(True)
         self.lineSwitchKey.setObjectName("lineSwitchKey")
-        self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.lineSwitchKey)
+        self.gridLayout.addWidget(self.lineSwitchKey, 1, 0, 1, 2)
         self.labelLatch = QtWidgets.QLabel(self.groupBox)
         self.labelLatch.setObjectName("labelLatch")
-        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.labelLatch)
+        self.gridLayout.addWidget(self.labelLatch, 2, 0, 1, 1)
+        self.buttonApply = QtWidgets.QPushButton(self.groupBox)
+        self.buttonApply.setObjectName("buttonApply")
+        self.gridLayout.addWidget(self.buttonApply, 4, 1, 1, 1)
+        self.checkSwitchEnable = QtWidgets.QCheckBox(self.groupBox)
+        self.checkSwitchEnable.setObjectName("checkSwitchEnable")
+        self.gridLayout.addWidget(self.checkSwitchEnable, 0, 0, 1, 2)
+        self.spinLatchTime = QtWidgets.QSpinBox(self.groupBox)
+        self.spinLatchTime.setMaximum(60)
+        self.spinLatchTime.setSingleStep(1)
+        self.spinLatchTime.setObjectName("spinLatchTime")
+        self.gridLayout.addWidget(self.spinLatchTime, 3, 0, 1, 2)
         self.verticalLayout.addWidget(self.groupBox)
 
         self.retranslateUi(SwitchConfigDialog)
@@ -41,8 +46,9 @@ class Ui_SwitchConfigDialog(object):
         _translate = QtCore.QCoreApplication.translate
         SwitchConfigDialog.setWindowTitle(_translate("SwitchConfigDialog", "Dialog"))
         self.groupBox.setTitle(_translate("SwitchConfigDialog", "Switch Configuration:"))
-        self.checkSwitchEnable.setText(_translate("SwitchConfigDialog", "Enable"))
-        self.spinLatchTime.setSuffix(_translate("SwitchConfigDialog", " sec."))
         self.lineSwitchKey.setPlaceholderText(_translate("SwitchConfigDialog", "Enter Keystroke"))
         self.labelLatch.setText(_translate("SwitchConfigDialog", "Latching Delay:"))
+        self.buttonApply.setText(_translate("SwitchConfigDialog", "Apply"))
+        self.checkSwitchEnable.setText(_translate("SwitchConfigDialog", "Enable Switch"))
+        self.spinLatchTime.setSuffix(_translate("SwitchConfigDialog", " seconds"))