Skip to content

Commit

Permalink
Threading protos
Browse files Browse the repository at this point in the history
  • Loading branch information
kubasaw committed Nov 26, 2019
1 parent 9d0d1e8 commit 70d6486
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 29 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ venv.bak/

# Test config files
*.json

# Test snippets
test*.py
37 changes: 22 additions & 15 deletions car/motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@
from scipy.integrate import solve_ivp
from scipy.interpolate import interp1d
import json
import struct


class motionParam(object):
def __init__(self, value):
self.__value=value
self.__value = value

@property
def val(self):
return self.__value

@property
def export(self):
return (self.__class__.__name__,self.val)
return (self.__class__.__name__, self.val)


class track(motionParam):

Expand Down Expand Up @@ -86,10 +89,10 @@ class constants():

def __init__(self):
self.__constDict = dict()

def get(self, param):
return self.__constDict[param].val

def ret(self, param):
return self.__constDict[param]

Expand All @@ -99,19 +102,18 @@ def toJSON(self, file=None):
else:
return json.dumps(self.__constDict, default=lambda x: x.export, indent=4)

def fromJSON (self, js):
if isinstance(js,str):
data=json.loads(js)
def fromJSON(self, js):
if isinstance(js, str):
data = json.loads(js)
else:
data=json.load(js)
data = json.load(js)

temp = dict()
for key, [valClass, val] in data.items():
temp[key] = globals()[valClass](val)


temp=dict()
for key, [valClass,val] in data.items():
temp[key]=globals()[valClass](val)
self.__constDict = temp

self.__constDict=temp


class motion:
"""Car motion class
Expand Down Expand Up @@ -148,6 +150,11 @@ def getSimDistance(self):
"""
return self.__state[0]

def getCanBytes(self):
distance = int(self.getSimDistance())
speed = int(self.getSimSpeed()*360)
return speed.to_bytes(2,'little')+distance.to_bytes(2,'little')

def getSimSpeed(self):
"""Returns actual vehicle speed
Expand Down
2 changes: 1 addition & 1 deletion gui/mainWindow.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'gui\mainWindow.ui'
# Form implementation generated from reading ui file 'mainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
Expand Down
48 changes: 35 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,22 @@
import gui
import car

import time

_translate = QCoreApplication.translate

class SimulationTicker(QThread):

signal = pyqtSignal()

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

def run(self):
while not self.isInterruptionRequested():
self.signal.emit()
self.sleep(1)


class Simulator(QtWidgets.QMainWindow, gui.Ui_MainWindow):
def __init__(self):
Expand All @@ -24,7 +38,7 @@ def __init__(self):

self.setupUi(self)
self.populateFields()
self.engineField.setText("0")
self.engineField.setText("1")

for file in os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lang')):
if file.startswith('carSim_') and file.endswith('.qm'):
Expand All @@ -48,12 +62,21 @@ def on_makeStepButton_clicked(self):
try:
self.__car.setThrottle(self.engineField.text())
self.__car.makeStep()
motionMessage=can.Message(arbitration_id=0x18,is_extended_id=False,data=self.__car.getCanBytes()[:])
#print(motionMessage)
self.__canbus.send(motionMessage)
except Exception as e:
QtWidgets.QMessageBox.critical(
self, _translate("Dialog", "Error"), str(e))

self.populateFields()

def populateFields(self):
self.timeField.setText(f"{self.__car.getSimTime():.2f}")
self.positionField.setText(f"{self.__car.getSimDistance():.2f}")
self.speedField.setText(f"{self.__car.getSimSpeed():.2f}")
self.fuelField.setText(f"{self.__car.getSimFuel():.2f}")

@pyqtSlot()
def on_actionAbout_triggered(self):
self.AboutDialog = QtWidgets.QDialog()
Expand All @@ -62,12 +85,6 @@ def on_actionAbout_triggered(self):
self.AboutDialog.setAttribute(Qt.WA_DeleteOnClose)
self.AboutDialog.exec_()

def populateFields(self):
self.timeField.setText(f"{self.__car.getSimTime():.2f}")
self.positionField.setText(f"{self.__car.getSimDistance():.2f}")
self.speedField.setText(f"{self.__car.getSimSpeed():.2f}")
self.fuelField.setText(f"{self.__car.getSimFuel():.2f}")

@pyqtSlot()
def on_actionExport_Settings_triggered(self):
filename, _ = QtWidgets.QFileDialog.getSaveFileName(
Expand All @@ -89,6 +106,7 @@ def on_actionImport_Settings_triggered(self):
@pyqtSlot()
def on_refreshAvailablePorts_clicked(self):
ports = serial.tools.list_ports.comports()
self.availablePorts.clear()
for port, desc, hwid in sorted(ports):
self.availablePorts.addItem(desc,port)

Expand All @@ -98,25 +116,29 @@ def on_refreshAvailablePorts_clicked(self):
def on_connectPort_clicked(self, state):
if state:
try:
self.__canbus = can.interface.Bus(bustype=self.canInterfaceTypes.currentText(), channel=self.availablePorts.currentData())
tx_msg = can.Message(arbitration_id=0x01, data=[
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], is_extended_id=False)
self.__canbus.send(tx_msg)
self.__canbusNotifier=can.Notifier(self.__canbus,[car.canFrameAppender(self.canReceived.appendPlainText)])
self.__canbus = can.ThreadSafeBus(interface=self.canInterfaceTypes.currentText(), channel=self.availablePorts.currentData())
self.__canbusNotifier=can.Notifier(self.__canbus,[car.canFrameAppender(self.canReceived.appendPlainText)],None)
except Exception as e:
self.connectPort.setChecked(False)
QtWidgets.QMessageBox.critical(self, _translate("Dialog", "Error"), str(e))
else:
self.connectPort.setText(_translate("MainWindow", "Disconnect"))
self.canInterfaceTypes.setEnabled(False)
self.availablePorts.setEnabled(False)
self.refreshAvailablePorts.setEnabled(False)
self.__tickerThread=SimulationTicker()
self.__tickerThread.signal.connect(self.on_makeStepButton_clicked)
self.__tickerThread.start()

else:
self.connectPort.setText(_translate("MainWindow", "Connect"))
self.__canbusNotifier.stop()
self.__tickerThread.requestInterruption()
self.__tickerThread.wait()
#self.__canbusNotifier.stop(0)
self.__canbus.shutdown()
self.canInterfaceTypes.setEnabled(True)
self.availablePorts.setEnabled(True)
self.refreshAvailablePorts.setEnabled(True)


if __name__ == "__main__":
Expand Down

0 comments on commit 70d6486

Please sign in to comment.