1234
This commit is contained in:
parent
19070199f0
commit
383577a288
123
ElectronicCalculator.py
Normal file
123
ElectronicCalculator.py
Normal file
@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Mon Jan 18 07:10:02 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
def Rseries(R):
|
||||
Rsum = 0
|
||||
for i in range(0,len(R)):
|
||||
Rsum += R[i]
|
||||
return Rsum
|
||||
|
||||
def Rparalel(R):
|
||||
Rsum = 0
|
||||
for i in range(0,len(R)):
|
||||
Rsum += (1/R[i])
|
||||
return 1/Rsum
|
||||
|
||||
def VoltageDiv(U,R1,R2,Rload = float('inf')):
|
||||
Rl = [R2,Rload]
|
||||
R2 = Rparalel(Rl)
|
||||
Uout = U*(R2/(R1+R2))
|
||||
Imax = (U*(R1/(R1+R2)))/R1
|
||||
return Uout,Imax
|
||||
|
||||
def RC(R,C):
|
||||
tau = R*C
|
||||
f = 1/(2*3.14159*tau)
|
||||
return(tau,f)
|
||||
|
||||
def RCfreqresponse(R,C):
|
||||
ann3dbf, ann3dbV = 0,0
|
||||
tau,f0 = RC(R,C)
|
||||
|
||||
f = -4#pow(10,-4)
|
||||
Vout = []
|
||||
Fout = []
|
||||
db3 = []
|
||||
impedance = []
|
||||
for i in range(0,1200):
|
||||
impedance.append(1/(2*math.pi*C)+R)
|
||||
db3.append(1/pow(2,0.5))
|
||||
Vout.append(abs(1/pow(1+pow((2*3.14159*pow(10,f))*C*R,2),0.5)))
|
||||
Fout.append(pow(10,f))
|
||||
if pow(10,f) < f0:
|
||||
pass
|
||||
elif (pow(10,f) >= f0) and ann3dbf != 0:
|
||||
ann3dbf = pow(10,f)
|
||||
ann3dbV = abs(1/pow(1+pow((2*3.14159*pow(10,f))/(1/f0),2),0.5))
|
||||
#Vout.append(1/(1+2*3.14159*f*R*C))
|
||||
f += 0.01
|
||||
|
||||
|
||||
plt.plot(Fout,Vout)
|
||||
plt.plot(Fout,db3,color="red")
|
||||
plt.xscale('log')
|
||||
plt.xlabel("Frequency")
|
||||
plt.ylabel("Voltage")
|
||||
plt.title('RC frequency response')
|
||||
plt.grid(True)
|
||||
plt.text(x=pow(10,5), y=1, s="Tau = "+str(round(tau,5)))
|
||||
plt.text(x=pow(10,5), y=0.95, s="f0 = "+str(round(f0,2))+"Hz")
|
||||
print(f0)
|
||||
plt.show()
|
||||
|
||||
while True:
|
||||
print("What do you want to calculate?")
|
||||
print(" 1: Rseries format: R1,R2,R3,...")
|
||||
print(" 2: Rparalel format: R1,R2,R3,...")
|
||||
print(" 3: Voltage divider format: U,R1,R2,Rload")
|
||||
print(" 4: RC filter format: R,C")
|
||||
print(" 5: RC frequency response format: R,C")
|
||||
inp = input(": ")
|
||||
if inp == "1":
|
||||
x = input("Resistor values: ")
|
||||
x = x.split(",")
|
||||
xint = []
|
||||
for i in range(0,len(x)):
|
||||
xint.append(float(x[i]))
|
||||
print(str(Rseries(xint))+"Ω")
|
||||
elif inp == "2":
|
||||
x = input("Resistor values: ")
|
||||
x = x.split(",")
|
||||
xint = []
|
||||
for i in range(0,len(x)):
|
||||
xint.append(float(x[i]))
|
||||
print(str(Rparalel(xint))+"Ω")
|
||||
elif inp == "3":
|
||||
x = input("Voltage divider params: ")
|
||||
x = x.split(",")
|
||||
xint = []
|
||||
for i in range(0,len(x)):
|
||||
xint.append(float(x[i]))
|
||||
if len(xint) == 3:
|
||||
vdiv = VoltageDiv(xint[0],xint[1],xint[2])
|
||||
else:
|
||||
vdiv = VoltageDiv(xint[0],xint[1],xint[2],xint[3])
|
||||
print(str(vdiv[0])+"V, "+str(vdiv[1])+"A")
|
||||
elif inp == "4":
|
||||
x = input("RC values: ")
|
||||
x = x.split(",")
|
||||
xint = []
|
||||
for i in range(0,len(x)):
|
||||
xint.append(float(x[i]))
|
||||
rc = RC(xint[0],xint[1])
|
||||
print(str(rc[1])+"Hz")
|
||||
elif inp == "5":
|
||||
x = input("RC values: ")
|
||||
x = x.split(",")
|
||||
xint = []
|
||||
for i in range(0,len(x)):
|
||||
xint.append(float(x[i]))
|
||||
RCfreqresponse(xint[0],xint[1])
|
||||
elif inp == "exit":
|
||||
break
|
||||
else:
|
||||
pass
|
||||
print("")
|
138
GTK-examples/AppendWidgetsAndRWthem.py
Normal file
138
GTK-examples/AppendWidgetsAndRWthem.py
Normal file
@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Fri Mar 19 22:04:11 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
|
||||
import threading
|
||||
#from multiprocessing import Process, Queue
|
||||
import queue
|
||||
import gi
|
||||
from time import sleep
|
||||
|
||||
gi.require_version('Gtk', '3.0')
|
||||
gi.require_version('GLib', '2.0')
|
||||
|
||||
from gi.repository import Gtk, GLib
|
||||
|
||||
IsEnded = 0
|
||||
counter = 0
|
||||
rows = []
|
||||
|
||||
def do_work(com_queue):
|
||||
global counter
|
||||
while True:
|
||||
counter += 1
|
||||
com_queue.put(str(counter))
|
||||
sleep(0.1)
|
||||
print("A")
|
||||
|
||||
if IsEnded != 0:
|
||||
break
|
||||
# continue
|
||||
|
||||
#from multiprocessing import Process, Queue
|
||||
|
||||
class MainGUI(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="Append")
|
||||
self.com_queue = queue.Queue()
|
||||
self.worker_thread = None
|
||||
self.liststore = None
|
||||
|
||||
self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
|
||||
self.add(self.vbox)
|
||||
|
||||
self.box = Gtk.Box(spacing=6)
|
||||
#self.add(self.box)
|
||||
self.vbox.pack_start(self.box, True, True, 0)
|
||||
|
||||
self.textArea = Gtk.Entry()
|
||||
self.textArea.set_text("Ready")
|
||||
#self.textbuffer = self.textArea.get_buffer()
|
||||
#self.textbuffer.set_text("Ready: \n", 9)
|
||||
self.box.pack_start(self.textArea, True, True, 0)
|
||||
|
||||
self.button1 = Gtk.Button(label="Add")
|
||||
self.button1.connect("clicked", self.addRow)
|
||||
self.box.pack_start(self.button1, True, True, 0)
|
||||
|
||||
self.button2 = Gtk.Button(label="List")
|
||||
self.button2.connect("clicked", self.butt)
|
||||
self.box.pack_start(self.button2, True, True, 0)
|
||||
|
||||
self.tid = None
|
||||
self.proc = None
|
||||
|
||||
def launch_worker_thread(self):
|
||||
#self.proc = Process(target=do_work, args=(self.com_queue,))
|
||||
#self.proc.start()
|
||||
|
||||
self.worker_thread = threading.Thread(target=do_work, args=(self.com_queue,))
|
||||
self.worker_thread.start()
|
||||
try:
|
||||
self.tid = GLib.timeout_add(1, self.check_queue, None) # run check_queue every 1 second
|
||||
except:
|
||||
print("Error")
|
||||
|
||||
def butt(self, widget):
|
||||
global rows
|
||||
print(rows)
|
||||
for row in rows:
|
||||
row[2].set_text("3")
|
||||
|
||||
#print(row.nlabel.get_text())
|
||||
|
||||
def addRow(self, widget, varType="uint8_t", varName="x", value="10"):
|
||||
global rows
|
||||
|
||||
nbox = Gtk.Box(spacing=6)
|
||||
self.vbox.pack_start(nbox, True, True, 0)
|
||||
|
||||
nlabel = Gtk.Label(label=varType+" "+varName+":")
|
||||
nbox.pack_start(nlabel, True, True, 0)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_text(value)
|
||||
nentry.connect("activate", self.printContent, varType, varName,)
|
||||
nbox.pack_start(nentry, True, True, 0)
|
||||
|
||||
nbox.show_all()
|
||||
rowContent = [len(rows), nlabel, nentry]
|
||||
rows.append(rowContent)
|
||||
|
||||
def printContent(self, widget, vt, vn):
|
||||
print(vt+" "+vn+": "+widget.get_text())
|
||||
|
||||
def butt2(self, widget):
|
||||
global IsEnded
|
||||
IsEnded = 1
|
||||
|
||||
def prn(self, ignored):
|
||||
print("B")
|
||||
GLib.idle_add(self.update_treeview, "update")
|
||||
|
||||
def check_queue(self, ignored):
|
||||
if self.tid is not None:
|
||||
#if self.worker_thread.is_alive():
|
||||
try:
|
||||
update = self.com_queue.get(False)
|
||||
GLib.idle_add(self.update_treeview, update) # send tuple
|
||||
except queue.Empty:
|
||||
pass
|
||||
return True # to keep timeout running
|
||||
else:
|
||||
return False # to end timeout
|
||||
|
||||
def update_treeview(self, update):
|
||||
text_end = self.textbuffer.get_end_iter()
|
||||
self.textbuffer.insert(text_end, str(update)) # here update the treeview model with tuple
|
||||
|
||||
if __name__ == "__main__":
|
||||
gui = MainGUI()
|
||||
gui.connect("destroy", Gtk.main_quit)
|
||||
gui.show_all()
|
||||
Gtk.main()
|
||||
IsEnded = 1
|
BIN
GTK-examples/Icons/SerialPort.png
Normal file
BIN
GTK-examples/Icons/SerialPort.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 47 KiB |
161
GTK-examples/ListAndConnectToPort.py
Normal file
161
GTK-examples/ListAndConnectToPort.py
Normal file
@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Sun Mar 21 10:06:43 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
from serial.tools import list_ports
|
||||
import serial
|
||||
import gi
|
||||
from time import sleep
|
||||
import threading
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import Gtk
|
||||
|
||||
ser = ""
|
||||
baud = 19200
|
||||
readPortEnable = False
|
||||
handshakeMsg = b'Hello\n'
|
||||
|
||||
|
||||
def readPort():
|
||||
global readPortEnable
|
||||
file = open("PORT_DATA.csv","w")
|
||||
file.write("AQ_START\n")
|
||||
file.close()
|
||||
while readPortEnable == True:
|
||||
with open("PORT_DATA.csv","a") as file:
|
||||
s = ser.read(255)
|
||||
print(s)
|
||||
file.write(s.decode())
|
||||
sleep(2)
|
||||
|
||||
|
||||
class ComboBoxWindow(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="ComboBox Example")
|
||||
|
||||
self.set_border_width(10)
|
||||
|
||||
self.portList = Gtk.ListStore(str)
|
||||
self.baudList = Gtk.ListStore(str)
|
||||
|
||||
box = Gtk.Box(spacing=6)
|
||||
|
||||
self.port_combo = Gtk.ComboBox.new_with_model_and_entry(self.portList)
|
||||
self.port_combo.connect("changed", self.on_name_combo_changed)
|
||||
self.port_combo.set_entry_text_column(0)
|
||||
self.refresh("ignore")
|
||||
try:
|
||||
self.port_combo.set_active(0)
|
||||
except:
|
||||
pass
|
||||
box.pack_start(self.port_combo, False, False, 0)
|
||||
|
||||
self.baud_combo = Gtk.ComboBox.new_with_model_and_entry(self.baudList)
|
||||
self.baud_combo.connect("changed", self.baud_change)
|
||||
self.baud_combo.set_entry_text_column(0)
|
||||
|
||||
bauds = ["9600",
|
||||
"19200",
|
||||
"38400",
|
||||
"57600",
|
||||
"115200",
|
||||
"250000",
|
||||
"500000",
|
||||
"1000000"
|
||||
]
|
||||
|
||||
for baud in bauds:
|
||||
self.baudList.append([baud])
|
||||
|
||||
self.baud_combo.set_active(1)
|
||||
box.pack_start(self.baud_combo, False, False, 0)
|
||||
|
||||
button1 = Gtk.Button()
|
||||
button1.connect("clicked", self.refresh)
|
||||
button1.set_image(Gtk.Image.new_from_icon_name("view-refresh",1))
|
||||
box.pack_start(button1, True, True, 0)
|
||||
|
||||
button2 = Gtk.Button(label="Connect")
|
||||
button2.set_image(Gtk.Image.new_from_icon_name("Connect",1))
|
||||
button2.connect("clicked", self.connect_disconnect)
|
||||
box.pack_start(button2, True, True, 0)
|
||||
|
||||
self.add(box)
|
||||
|
||||
def refresh(self, widget):
|
||||
ports = list_ports.comports()
|
||||
self.portList.clear()
|
||||
for port in ports:
|
||||
self.portList.append([port[0]])
|
||||
|
||||
def baud_change(self, combo):
|
||||
global baud
|
||||
tree_iter = combo.get_active_iter()
|
||||
if tree_iter is not None:
|
||||
model = combo.get_model()
|
||||
baud = model[tree_iter][0]
|
||||
print("Selected Baud: %s" % (baud))
|
||||
else:
|
||||
entry = combo.get_child()
|
||||
print("Entered Baud: %s" % entry.get_text())
|
||||
|
||||
def connect_disconnect(self, butt):
|
||||
global ser, baud, readPortEnable, handshakeMsg
|
||||
if butt.get_label() == "Connect":
|
||||
self.port_combo.set_sensitive(False)
|
||||
self.baud_combo.set_sensitive(False)
|
||||
|
||||
tree_iter = self.port_combo.get_active_iter()
|
||||
model = self.port_combo.get_model()
|
||||
port = model[tree_iter][0]
|
||||
ser = serial.Serial(port, baud, timeout=1)
|
||||
print("Connecting to:"+ port)
|
||||
butt.set_label("Disconnect")
|
||||
ser.write(b'Hello\n')
|
||||
while(ser.readline() != handshakeMsg):
|
||||
sleep(0.5)
|
||||
|
||||
readPortEnable = True
|
||||
self.Port_thread = threading.Thread(target=readPort)
|
||||
self.Port_thread.start()
|
||||
else:
|
||||
ser.close()
|
||||
self.port_combo.set_sensitive(True)
|
||||
self.baud_combo.set_sensitive(True)
|
||||
readPortEnable = False
|
||||
print("Disconnecting")
|
||||
butt.set_label("Connect")
|
||||
|
||||
def on_name_combo_changed(self, combo):
|
||||
tree_iter = combo.get_active_iter()
|
||||
if tree_iter is not None:
|
||||
model = combo.get_model()
|
||||
port = model[tree_iter][0]
|
||||
print("Selected Port: %s" % (port))
|
||||
else:
|
||||
entry = combo.get_child()
|
||||
print("Entered: %s" % entry.get_text())
|
||||
|
||||
def on_country_combo_changed(self, combo):
|
||||
tree_iter = combo.get_active_iter()
|
||||
if tree_iter is not None:
|
||||
model = combo.get_model()
|
||||
country = model[tree_iter][0]
|
||||
print("Selected: country=%s" % country)
|
||||
|
||||
def on_currency_combo_changed(self, combo):
|
||||
text = combo.get_active_text()
|
||||
if text is not None:
|
||||
print("Selected: currency=%s" % text)
|
||||
|
||||
|
||||
win = ComboBoxWindow()
|
||||
win.connect("destroy", Gtk.main_quit)
|
||||
win.show_all()
|
||||
Gtk.main()
|
||||
|
||||
|
5
GTK-examples/MONITOR_DATA.csv
Normal file
5
GTK-examples/MONITOR_DATA.csv
Normal file
@ -0,0 +1,5 @@
|
||||
V,uint8_t,blinkTime,254,0x20000034
|
||||
V,uint32_t,irc_pulses_per_revolution,17080,0x20000018
|
||||
R,reg,TIM8->PSC,499,0x40010428
|
||||
V,float,comp,29.50,0x20000014
|
||||
V,int32_t,testVar,-30,0x20000038
|
|
572
GTK-examples/MonitorPrototype.py
Normal file
572
GTK-examples/MonitorPrototype.py
Normal file
@ -0,0 +1,572 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Mon Mar 22 11:33:14 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
|
||||
from serial.tools import list_ports
|
||||
import serial
|
||||
import gi
|
||||
from time import sleep
|
||||
import threading
|
||||
import os
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
gi.require_version('GLib', '2.0')
|
||||
|
||||
from gi.repository import Gtk, GLib, Gdk
|
||||
|
||||
|
||||
HANDSHAKE_MSG = b'Hello\n'
|
||||
VAR_DESIGNATOR = "V"
|
||||
REG_DESIGNATOR = "R"
|
||||
CSV_FILE = "MONITOR_DATA.csv"
|
||||
|
||||
|
||||
ser = None
|
||||
baud = 19200
|
||||
readPortEnable = False
|
||||
readCsvEnable = False
|
||||
rows = []
|
||||
csvContent = []
|
||||
csvContentOverArr = ""
|
||||
testCsvFile = "test.csv"
|
||||
csvGenCsvContent = ""
|
||||
firsCsvRead = True
|
||||
csvIsWrite = False
|
||||
csvIsRead = False
|
||||
|
||||
|
||||
def CsvGen(dataForCsv):#vyroba csv pro tabulku promennych, nutno dodat dekodovana data
|
||||
global csvGenCsvContent, csvIsRead, csvIsWrite, csvContentOverArr
|
||||
|
||||
newCsvGenContent = []
|
||||
Passed = False
|
||||
|
||||
dataForCsv = csvContentOverArr + dataForCsv
|
||||
rawData = dataForCsv.split('\n')
|
||||
csvGenLine = csvGenCsvContent.split('\n')
|
||||
csvContentOverArr = rawData[-1]
|
||||
rawData.remove(rawData[-1])
|
||||
rawDataLen = len(rawData)
|
||||
for line in rawData:
|
||||
splitted = line.split(',')
|
||||
try:
|
||||
#csvGenLine = csvGenCsvContent.split('\n')
|
||||
VarPos = [i for i, s in enumerate(csvGenLine) if ","+splitted[2]+"," in s]
|
||||
if VarPos != []:
|
||||
csvGenLineParts = csvGenLine[VarPos[0]].split(",")
|
||||
csvGenLineParts[3] = splitted[3]
|
||||
string = ""
|
||||
for j in csvGenLineParts:
|
||||
string += j+','
|
||||
string = string[:-1]
|
||||
csvGenLine[VarPos[0]] = string
|
||||
else:
|
||||
csvGenLine.append(line)
|
||||
csvGenCsvContent = ""
|
||||
except:
|
||||
pass
|
||||
|
||||
for l in csvGenLine:
|
||||
if l != "":
|
||||
csvGenCsvContent += l
|
||||
csvGenCsvContent += '\n'
|
||||
else:
|
||||
pass
|
||||
|
||||
while csvIsRead == True:
|
||||
pass
|
||||
csvIsWrite = True
|
||||
with open(CSV_FILE,'w') as dataFile:
|
||||
dataFile.write(csvGenCsvContent)
|
||||
dataFile.close()
|
||||
csvIsWrite = False
|
||||
|
||||
|
||||
#Funkce bezici na pozadi
|
||||
def readPort():#Cte data ze serioveho portu
|
||||
global readPortEnable
|
||||
print("MSG: READ_PORT_START")
|
||||
file = open("PORT_DATA.log","w")
|
||||
file.write("AQ_START\n")
|
||||
file.close()
|
||||
while readPortEnable == True:
|
||||
with open("PORT_DATA.log","a") as file:
|
||||
s = ser.read(10000)
|
||||
data = s.decode()
|
||||
CsvGen(data)
|
||||
file.write(data)
|
||||
file.close()
|
||||
|
||||
#sleep(1)
|
||||
print("MSG: READ_PORT_EXIT")
|
||||
|
||||
def readCsv():#Cte csv vygenerovane CsvGen()
|
||||
global csvContent, testCsvFile, csvIsRead, csvIsWrite
|
||||
|
||||
#while readCsvEnable == True:
|
||||
while csvIsWrite == True:
|
||||
pass
|
||||
csvIsRead = True
|
||||
with open(CSV_FILE,"r") as file:
|
||||
content = file.read()
|
||||
lines = content.split("\n")
|
||||
csvContent = lines
|
||||
file.close()
|
||||
csvIsRead = False
|
||||
|
||||
MainGUI.ApplyCsv()
|
||||
|
||||
if readCsvEnable == True :
|
||||
return True
|
||||
else:
|
||||
print("MSG: READ_CSV_EXIT")
|
||||
return False
|
||||
|
||||
def get_resource_path(rel_path):
|
||||
dir_of_py_file = os.path.dirname(__file__)
|
||||
rel_path_to_resource = os.path.join(dir_of_py_file, rel_path)
|
||||
abs_path_to_resource = os.path.abspath(rel_path_to_resource)
|
||||
return abs_path_to_resource
|
||||
|
||||
class MainGUI(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="Monitor")
|
||||
self.set_icon_from_file(get_resource_path("Icons/SerialPort.png"))
|
||||
self.set_resizable(False)
|
||||
|
||||
#self.set_border_width(10)
|
||||
|
||||
self.tid = None
|
||||
|
||||
self.portList = Gtk.ListStore(str)
|
||||
self.baudList = Gtk.ListStore(str)
|
||||
|
||||
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
|
||||
self.add(vbox)
|
||||
|
||||
box = Gtk.Box(spacing=6)
|
||||
vbox.pack_start(box, False, False, 0)
|
||||
|
||||
self.port_combo = Gtk.ComboBox.new_with_model_and_entry(self.portList)
|
||||
self.port_combo.connect("changed", self.on_name_combo_changed)
|
||||
self.port_combo.set_entry_text_column(0)
|
||||
self.refresh("ignore")
|
||||
try:
|
||||
self.port_combo.set_active(0)
|
||||
except:
|
||||
pass
|
||||
box.pack_start(self.port_combo, False, False, 0)
|
||||
|
||||
self.baud_combo = Gtk.ComboBox.new_with_model_and_entry(self.baudList)
|
||||
self.baud_combo.connect("changed", self.baud_change)
|
||||
self.baud_combo.set_entry_text_column(0)
|
||||
|
||||
bauds = ["9600",
|
||||
"19200",
|
||||
"38400",
|
||||
"57600",
|
||||
"115200",
|
||||
"250000",
|
||||
"500000",
|
||||
"1000000"
|
||||
]
|
||||
|
||||
for baud in bauds:
|
||||
self.baudList.append([baud])
|
||||
|
||||
self.baud_combo.set_active(1)
|
||||
box.pack_start(self.baud_combo, False, False, 0)
|
||||
|
||||
button1 = Gtk.Button()
|
||||
button1.connect("clicked", self.refresh)
|
||||
button1.set_image(Gtk.Image.new_from_icon_name("view-refresh",1))
|
||||
button1.set_size_request(20,20)
|
||||
button1.set_halign(Gtk.Align.END)
|
||||
box.pack_start(button1, True, False, 0)
|
||||
|
||||
button2 = Gtk.Button(label="Connect")
|
||||
button2.set_image(Gtk.Image.new_from_icon_name("Connect",1))
|
||||
button2.connect("clicked", self.connect_disconnect)
|
||||
box.pack_start(button2, True, True, 0)
|
||||
|
||||
tabs = Gtk.Notebook()
|
||||
vbox.pack_start(tabs, False, False, 0)
|
||||
|
||||
varScroll = Gtk.ScrolledWindow()
|
||||
varScroll.set_min_content_height(600)
|
||||
self.variable_tab = Gtk.Grid()
|
||||
varScroll.add_with_viewport(self.variable_tab)
|
||||
tabs.append_page(varScroll, Gtk.Label("Variables"))#self.variable_tab
|
||||
|
||||
regScroll = Gtk.ScrolledWindow()
|
||||
regScroll.set_min_content_height(600)
|
||||
self.register_tab = Gtk.Grid()
|
||||
regScroll.add_with_viewport(self.register_tab)
|
||||
tabs.append_page(regScroll, Gtk.Label("Registers"))
|
||||
|
||||
#self.addRow("ignore")
|
||||
|
||||
|
||||
def refresh(self, widget):
|
||||
CsvGen("none")
|
||||
ports = list_ports.comports()
|
||||
self.portList.clear()
|
||||
for port in ports:
|
||||
self.portList.append([port[0]])
|
||||
try:
|
||||
self.port_combo.set_active(0)
|
||||
except:
|
||||
pass
|
||||
|
||||
def baud_change(self, combo):
|
||||
global baud
|
||||
tree_iter = combo.get_active_iter()
|
||||
if tree_iter is not None:
|
||||
model = combo.get_model()
|
||||
baud = model[tree_iter][0]
|
||||
print("Selected Baud: %s" % (baud))
|
||||
else:
|
||||
entry = combo.get_child()
|
||||
print("Entered Baud: %s" % entry.get_text())
|
||||
|
||||
def connect_disconnect(self, butt):
|
||||
global ser, baud, readPortEnable, HANDSHAKE_MSG, readCsvEnable, firsCsvRead
|
||||
if butt.get_label() == "Connect":
|
||||
try:
|
||||
for i in range(0,len(rows)):
|
||||
self.variable_tab.remove_row(0)
|
||||
self.register_tab.remove_row(0)
|
||||
except:
|
||||
pass
|
||||
firsCsvRead = True
|
||||
|
||||
self.port_combo.set_sensitive(False)
|
||||
self.baud_combo.set_sensitive(False)
|
||||
|
||||
tree_iter = self.port_combo.get_active_iter()
|
||||
model = self.port_combo.get_model()
|
||||
port = model[tree_iter][0]
|
||||
ser = serial.Serial(port, baud, timeout=1)
|
||||
print("Connecting to:"+ port)
|
||||
butt.set_label("Disconnect")
|
||||
ser.write(b'Hello\n')
|
||||
try:
|
||||
os.remove(CSV_FILE)
|
||||
except:
|
||||
print("MSG: NO MONITOR FILE TO REMOVE")
|
||||
open(CSV_FILE, 'w').close()
|
||||
# while(ser.readline() != HANDSHAKE_MSG):
|
||||
# sleep(0.5)
|
||||
|
||||
readPortEnable = True
|
||||
Port_thread = threading.Thread(target=readPort)
|
||||
Port_thread.start()
|
||||
|
||||
readCsvEnable = True
|
||||
GLib.timeout_add_seconds(1, readCsv)
|
||||
print("MSG: READ_CSV_START")
|
||||
#Csv_thread = threading.Thread(target=readCsv)
|
||||
#Csv_thread.start()
|
||||
|
||||
self.tid = GLib.timeout_add_seconds(1, self.addRow, None)
|
||||
else:
|
||||
ser.close()
|
||||
self.port_combo.set_sensitive(True)
|
||||
self.baud_combo.set_sensitive(True)
|
||||
readPortEnable = False
|
||||
readCsvEnable = False
|
||||
for row in rows:
|
||||
row[3].set_editable(False)
|
||||
print("Disconnecting")
|
||||
butt.set_label("Connect")
|
||||
|
||||
def on_name_combo_changed(self, combo):
|
||||
tree_iter = combo.get_active_iter()
|
||||
if tree_iter is not None:
|
||||
model = combo.get_model()
|
||||
port = model[tree_iter][0]
|
||||
print("Selected Port: %s" % (port))
|
||||
else:
|
||||
entry = combo.get_child()
|
||||
print("Entered: %s" % entry.get_text())
|
||||
|
||||
def addRow(self, widget):
|
||||
global rows, csvContent, testCsvFile, firsCsvRead
|
||||
iteration = 0
|
||||
csvContentIsNone = True
|
||||
|
||||
with open(CSV_FILE,"r") as file:
|
||||
content = file.read()
|
||||
lines = content.split("\n")
|
||||
file.close()
|
||||
|
||||
if firsCsvRead == False:
|
||||
for line in lines:
|
||||
x = line.split(',')
|
||||
y = csvContent[iteration].split(',')
|
||||
if csvContent[iteration] == "":
|
||||
y = [0,0]
|
||||
if line == "":
|
||||
#print("BLANK_LINE!")
|
||||
iteration += 1
|
||||
pass
|
||||
else:
|
||||
if x[1] == y[1]:
|
||||
#print("DUPE")
|
||||
iteration += 1
|
||||
else:
|
||||
print("EDIT")
|
||||
try:
|
||||
csvContent.append(line)
|
||||
inLine = line.split(",")
|
||||
if inLine[0] == "V":
|
||||
varType = inLine[1]
|
||||
varName = inLine[2]
|
||||
value = inLine[3]
|
||||
address = inLine[4]
|
||||
|
||||
typeLabel = Gtk.Label(label=varType, halign=Gtk.Align.START)
|
||||
f = Gtk.Frame()
|
||||
f.add(typeLabel)
|
||||
self.variable_tab.attach(f,0,iteration,1,1)
|
||||
nameLabel = Gtk.Label(label=varName+":", halign=Gtk.Align.END)
|
||||
f = Gtk.Frame()
|
||||
f.add(nameLabel)
|
||||
self.variable_tab.attach(f,1,iteration,1,1)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_hexpand(False)
|
||||
nentry.set_text(value)
|
||||
nentry.set_editable(False)
|
||||
self.variable_tab.attach(nentry,2,iteration,1,1)
|
||||
|
||||
edit = Gtk.Entry()
|
||||
edit.set_hexpand(False)
|
||||
edit.set_placeholder_text("Edit")
|
||||
edit.set_max_length(16)
|
||||
edit.connect("activate", self.SendData)
|
||||
self.variable_tab.attach(edit,3,iteration,1,1)
|
||||
|
||||
self.variable_tab.show_all()
|
||||
rowContent = [len(rows),typeLabel, nameLabel, nentry, edit, address]
|
||||
rows.append(rowContent)
|
||||
elif inLine[0] == "R":
|
||||
varType = inLine[1]
|
||||
varName = inLine[2]
|
||||
value = inLine[3]
|
||||
value = int(value)
|
||||
value = str(hex(value))
|
||||
address = inLine[4]
|
||||
|
||||
typeLabel = Gtk.Label(label=varType, halign=Gtk.Align.START)
|
||||
f = Gtk.Frame()
|
||||
f.add(typeLabel)
|
||||
self.register_tab.attach(f,0,iteration,1,1)
|
||||
nameLabel = Gtk.Label(label=varName+":", halign=Gtk.Align.END)
|
||||
f = Gtk.Frame()
|
||||
f.add(nameLabel)
|
||||
self.register_tab.attach(f,1,iteration,1,1)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_hexpand(False)
|
||||
nentry.set_text(value)
|
||||
nentry.set_editable(False)
|
||||
self.register_tab.attach(nentry,2,iteration,1,1)
|
||||
|
||||
edit = Gtk.Entry()
|
||||
edit.set_hexpand(False)
|
||||
edit.set_placeholder_text("Edit")
|
||||
edit.set_max_length(10)
|
||||
edit.connect("activate", self.SendData)
|
||||
self.register_tab.attach(edit,3,iteration,1,1)
|
||||
|
||||
self.register_tab.show_all()
|
||||
rowContent = [len(rows),typeLabel, nameLabel, nentry, edit, address]
|
||||
rows.append(rowContent)
|
||||
else:
|
||||
print("VAR_CLASS_ERROR!")
|
||||
|
||||
iteration += 1
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
csvContent = []
|
||||
rows = []
|
||||
print(lines)
|
||||
for line in lines:
|
||||
if line == "":
|
||||
print("BLANK_LINE!")
|
||||
iteration += 1
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
csvContent.append(line)
|
||||
inLine = line.split(",")
|
||||
if inLine[0] == "V":
|
||||
varType = inLine[1]
|
||||
varName = inLine[2]
|
||||
value = inLine[3]
|
||||
address = inLine[4]
|
||||
|
||||
typeLabel = Gtk.Label(label=varType, halign=Gtk.Align.START)
|
||||
f = Gtk.Frame()
|
||||
f.add(typeLabel)
|
||||
self.variable_tab.attach(f,0,iteration,1,1)
|
||||
nameLabel = Gtk.Label(label=varName+":", halign=Gtk.Align.END)
|
||||
f = Gtk.Frame()
|
||||
f.add(nameLabel)
|
||||
self.variable_tab.attach(f,1,iteration,1,1)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_hexpand(False)
|
||||
nentry.set_text(value)
|
||||
nentry.set_editable(False)
|
||||
self.variable_tab.attach(nentry,2,iteration,1,1)
|
||||
|
||||
edit = Gtk.Entry()
|
||||
edit.set_hexpand(False)
|
||||
edit.set_placeholder_text("Edit")
|
||||
edit.set_max_length(16)
|
||||
edit.connect("activate", self.SendData)
|
||||
self.variable_tab.attach(edit,3,iteration,1,1)
|
||||
|
||||
self.variable_tab.show_all()
|
||||
rowContent = [len(rows),typeLabel, nameLabel, nentry, edit, address]
|
||||
rows.append(rowContent)
|
||||
elif inLine[0] == "R":
|
||||
varType = inLine[1]
|
||||
varName = inLine[2]
|
||||
value = inLine[3]
|
||||
value = int(value)
|
||||
value = str(hex(value))
|
||||
address = inLine[4]
|
||||
|
||||
typeLabel = Gtk.Label(label=varType, halign=Gtk.Align.START)
|
||||
f = Gtk.Frame()
|
||||
f.add(typeLabel)
|
||||
self.register_tab.attach(f,0,iteration,1,1)
|
||||
nameLabel = Gtk.Label(label=varName+":", halign=Gtk.Align.END)
|
||||
f = Gtk.Frame()
|
||||
f.add(nameLabel)
|
||||
self.register_tab.attach(f,1,iteration,1,1)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_hexpand(False)
|
||||
nentry.set_text(value)
|
||||
nentry.set_editable(False)
|
||||
self.register_tab.attach(nentry,2,iteration,1,1)
|
||||
|
||||
edit = Gtk.Entry()
|
||||
edit.set_hexpand(False)
|
||||
edit.set_placeholder_text("Edit")
|
||||
edit.set_max_length(10)
|
||||
edit.connect("activate", self.SendData)
|
||||
self.register_tab.attach(edit,3,iteration,1,1)
|
||||
|
||||
self.register_tab.show_all()
|
||||
rowContent = [len(rows),typeLabel, nameLabel, nentry, edit, address]
|
||||
rows.append(rowContent)
|
||||
else:
|
||||
print("VAR_CLASS_ERROR!")
|
||||
|
||||
iteration += 1
|
||||
except:
|
||||
pass
|
||||
#GLib.idle_add(self.Void)
|
||||
firsCsvRead = False
|
||||
return readCsvEnable
|
||||
|
||||
def ApplyCsv():
|
||||
global csvContent, rows
|
||||
values = []
|
||||
isReg = False
|
||||
iteration = 0
|
||||
for content in csvContent:
|
||||
try:
|
||||
bits = content.split(",")
|
||||
if bits[0] == 'V':
|
||||
values.append(bits[3])
|
||||
elif bits[0] == 'R':
|
||||
isReg = True
|
||||
x = int(bits[3])
|
||||
x = str(hex(x))
|
||||
values.append(x)
|
||||
except:
|
||||
pass
|
||||
for row in rows:
|
||||
row[3].set_text(values[iteration])
|
||||
iteration += 1
|
||||
|
||||
def SendData(self, entry):
|
||||
global ser
|
||||
serMsg = "A"
|
||||
value = entry.get_text()
|
||||
numValue = 0
|
||||
|
||||
print("MSG: ENTERED="+value)
|
||||
for row in rows:
|
||||
if row[4] == entry:
|
||||
if row[1].get_text() == "uint8_t":
|
||||
serMsg += '0'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 256
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "int8_t":
|
||||
serMsg += '1'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 256
|
||||
if numValue > 127:
|
||||
numValue -= 256
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "uint16_t":
|
||||
serMsg += '2'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 65536
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "int16_t":
|
||||
serMsg += '3'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 65536
|
||||
if numValue > (65536/2)-1:
|
||||
numValue -= 65536
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "uint32_t":
|
||||
serMsg += '4'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 4294967296
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "int32_t":
|
||||
serMsg += '5'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 4294967296
|
||||
if numValue > (4294967296/2)-1:
|
||||
numValue -= 4294967296
|
||||
value = str(numValue)
|
||||
elif row[1].get_text() == "float":
|
||||
serMsg += '6'
|
||||
elif row[1].get_text() == "reg":
|
||||
serMsg += '7'
|
||||
numValue = int(value)
|
||||
numValue = numValue % 4294967296
|
||||
value = str(numValue)
|
||||
|
||||
serMsg += row[5]
|
||||
serMsg += value
|
||||
serMsg += "\n"
|
||||
print("MSG: SERIAL WRITE: "+serMsg)
|
||||
|
||||
ser.write(serMsg.encode())
|
||||
|
||||
def Void(self):
|
||||
print("Void")
|
||||
return True
|
||||
|
||||
|
||||
win = MainGUI()
|
||||
win.connect("destroy", Gtk.main_quit)
|
||||
win.show_all()
|
||||
Gtk.main()
|
1
GTK-examples/PORT_DATA.csv
Normal file
1
GTK-examples/PORT_DATA.csv
Normal file
@ -0,0 +1 @@
|
||||
AQ_START
|
|
2424
GTK-examples/PORT_DATA.log
Normal file
2424
GTK-examples/PORT_DATA.log
Normal file
File diff suppressed because it is too large
Load Diff
57
GTK-examples/Plot.py
Normal file
57
GTK-examples/Plot.py
Normal file
@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Tue Mar 23 15:56:31 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('GTK3Agg') # or 'GTK3Cairo'
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
import gi
|
||||
gi.require_version('Gtk', '3.0')
|
||||
from gi.repository import Gtk
|
||||
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot([1, 2, 3], 'ro-', label='easy as 1 2 3')
|
||||
ax.plot([1, 4, 9], 'gs--', label='easy as 1 2 3 squared')
|
||||
ax.legend()
|
||||
|
||||
manager = fig.canvas.manager
|
||||
# you can access the window or vbox attributes this way
|
||||
toolbar = manager.toolbar
|
||||
vbox = manager.vbox
|
||||
|
||||
# now let's add a button to the toolbar
|
||||
button = Gtk.Button(label='Click me')
|
||||
button.show()
|
||||
button.connect('clicked', lambda button: print('hi mom'))
|
||||
|
||||
toolitem = Gtk.ToolItem()
|
||||
toolitem.show()
|
||||
toolitem.set_tooltip_text('Click me for fun and profit')
|
||||
toolitem.add(button)
|
||||
|
||||
pos = 8 # where to insert this in the toolbar
|
||||
toolbar.insert(toolitem, pos)
|
||||
|
||||
# now let's add a widget to the vbox
|
||||
label = Gtk.Label()
|
||||
label.set_markup('Drag mouse over axes for position')
|
||||
label.show()
|
||||
vbox.pack_start(label, False, False, 0)
|
||||
vbox.reorder_child(toolbar, -1)
|
||||
|
||||
def update(event):
|
||||
if event.xdata is None:
|
||||
label.set_markup('Drag mouse over axes for position')
|
||||
else:
|
||||
label.set_markup(
|
||||
f'<span color="#ef0000">x,y=({event.xdata}, {event.ydata})</span>')
|
||||
|
||||
fig.canvas.mpl_connect('motion_notify_event', update)
|
||||
|
||||
plt.show()
|
160
GTK-examples/ReadAndApplyCsv.py
Normal file
160
GTK-examples/ReadAndApplyCsv.py
Normal file
@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Sat Mar 20 09:44:07 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
|
||||
import threading
|
||||
#from multiprocessing import Process, Queue
|
||||
import queue
|
||||
import gi
|
||||
from time import sleep
|
||||
|
||||
gi.require_version('Gtk', '3.0')
|
||||
gi.require_version('GLib', '2.0')
|
||||
|
||||
from gi.repository import Gtk, GLib
|
||||
|
||||
IsEnded = 0
|
||||
rows = []
|
||||
csvContent = []
|
||||
csvFile = ""
|
||||
|
||||
def do_work():
|
||||
global csvContent
|
||||
while True:
|
||||
with open(csvFile,"r") as file:
|
||||
content = file.read()
|
||||
print(content)
|
||||
lines = content.split("\n")
|
||||
csvContent = lines
|
||||
file.close()
|
||||
|
||||
sleep(1)
|
||||
if IsEnded != 0:
|
||||
break
|
||||
|
||||
class MainGUI(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="Append")
|
||||
self.com_queue = queue.Queue()
|
||||
self.worker_thread = None
|
||||
self.liststore = None
|
||||
|
||||
self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
|
||||
self.add(self.vbox)
|
||||
|
||||
self.box = Gtk.Box(spacing=6)
|
||||
self.vbox.pack_start(self.box, True, True, 0)
|
||||
|
||||
self.textArea = Gtk.Entry()
|
||||
self.textArea.set_text("test.csv")
|
||||
self.box.pack_start(self.textArea, True, True, 0)
|
||||
|
||||
self.button1 = Gtk.Button(label="Load")
|
||||
self.button1.connect("clicked", self.addRow)
|
||||
self.box.pack_start(self.button1, True, True, 0)
|
||||
|
||||
self.button2 = Gtk.Button(label="Update")
|
||||
self.button2.connect("clicked", self.ApplyCsv)
|
||||
self.box.pack_start(self.button2, True, True, 0)
|
||||
|
||||
self.nbox = Gtk.Grid()
|
||||
self.vbox.pack_start(self.nbox, True, True, 0)
|
||||
|
||||
self.tid = None
|
||||
self.proc = None
|
||||
|
||||
|
||||
|
||||
def launch_worker_thread(self):
|
||||
self.worker_thread = threading.Thread(target=do_work)
|
||||
self.worker_thread.start()
|
||||
|
||||
def butt(self, widget):
|
||||
global rows
|
||||
print(rows)
|
||||
for row in rows:
|
||||
row[3].set_text("3")
|
||||
|
||||
def addRow(self, widget):
|
||||
global rows, csvContent, csvFile
|
||||
iteration = 0
|
||||
csvFile = self.textArea.get_text()
|
||||
|
||||
with open(self.textArea.get_text(),"r") as file:
|
||||
content = file.read()
|
||||
print(content)
|
||||
lines = content.split("\n")
|
||||
csvContent = lines
|
||||
file.close()
|
||||
for line in lines:
|
||||
try:
|
||||
inLine = line.split(",")
|
||||
print(inLine)
|
||||
varType = inLine[0]
|
||||
varName = inLine[1]
|
||||
value = inLine[2]
|
||||
|
||||
typeLabel = Gtk.Label(label=varType, halign=Gtk.Align.START)
|
||||
f = Gtk.Frame()
|
||||
f.add(typeLabel)
|
||||
self.nbox.attach(f,0,iteration,1,1)
|
||||
nameLabel = Gtk.Label(label=varName+":", halign=Gtk.Align.END)
|
||||
f = Gtk.Frame()
|
||||
f.add(nameLabel)
|
||||
self.nbox.attach(f,1,iteration,1,1)
|
||||
#nlabel = Gtk.Label(label=varType+" "+varName+":")
|
||||
#nbox.pack_start(nlabel, True, True, 0)
|
||||
|
||||
nentry = Gtk.Entry()
|
||||
nentry.set_hexpand(False)
|
||||
nentry.set_text(value)
|
||||
nentry.connect("activate", self.printContent, varType, varName,)
|
||||
self.nbox.attach(nentry,2,iteration,3,1)
|
||||
#nbox.pack_start(nentry, True, True, 0)
|
||||
|
||||
self.nbox.show_all()
|
||||
#rowContent = [len(rows), nlabel, nentry]
|
||||
rowContent = [len(rows),typeLabel, nameLabel, nentry]
|
||||
rows.append(rowContent)
|
||||
|
||||
iteration += 1
|
||||
except:
|
||||
pass
|
||||
|
||||
self.launch_worker_thread()
|
||||
|
||||
def printContent(self, widget, vt, vn):
|
||||
print(vt+" "+vn+": "+widget.get_text())
|
||||
|
||||
def ApplyCsv(self, widget):
|
||||
global csvContent
|
||||
values = []
|
||||
iteration = 0
|
||||
for content in csvContent:
|
||||
try:
|
||||
bits = content.split(",")
|
||||
values.append(bits[2])
|
||||
except:
|
||||
pass
|
||||
for row in rows:
|
||||
row[3].set_text(values[iteration])
|
||||
iteration += 1
|
||||
|
||||
def butt2(self, widget):
|
||||
global IsEnded
|
||||
IsEnded = 1
|
||||
|
||||
def prn(self, ignored):
|
||||
print("B")
|
||||
GLib.idle_add(self.update_treeview, "update")
|
||||
|
||||
if __name__ == "__main__":
|
||||
gui = MainGUI()
|
||||
gui.connect("destroy", Gtk.main_quit)
|
||||
gui.show_all()
|
||||
Gtk.main()
|
||||
IsEnded = 1
|
33
GTK-examples/addRemoveWidget.py
Normal file
33
GTK-examples/addRemoveWidget.py
Normal file
@ -0,0 +1,33 @@
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import Gtk
|
||||
|
||||
class MyWindow(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="Hello World")
|
||||
|
||||
self.box = Gtk.Box(spacing=6)
|
||||
self.add(self.box)
|
||||
|
||||
self.button1 = Gtk.Button(label="Hello")
|
||||
self.button1.connect("clicked", self.on_button1_clicked)
|
||||
self.box.pack_start(self.button1, True, True, 0)
|
||||
|
||||
|
||||
def on_button1_clicked(self, widget):
|
||||
print("Hello")
|
||||
self.button2 = Gtk.Button(label="Goodbye")
|
||||
self.button2.connect("clicked", self.on_button2_clicked)
|
||||
self.box.pack_start(self.button2, True, True, 0)
|
||||
self.button2.show_all()
|
||||
|
||||
def on_button2_clicked(self, widget):
|
||||
print("Goodbye")
|
||||
self.button2.hide()
|
||||
|
||||
win = MyWindow()
|
||||
win.connect("destroy", Gtk.main_quit)
|
||||
win.show_all()
|
||||
Gtk.main()
|
||||
|
106
GTK-examples/fileAppend.py
Normal file
106
GTK-examples/fileAppend.py
Normal file
@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Thu Mar 18 18:06:34 2021
|
||||
|
||||
@author: angoosh
|
||||
"""
|
||||
import threading
|
||||
#from multiprocessing import Process, Queue
|
||||
import queue
|
||||
import gi
|
||||
from time import sleep
|
||||
|
||||
gi.require_version('Gtk', '3.0')
|
||||
gi.require_version('GLib', '2.0')
|
||||
|
||||
from gi.repository import Gtk, GLib
|
||||
|
||||
IsEnded = 0
|
||||
counter = 0
|
||||
|
||||
def do_work(com_queue):
|
||||
global counter
|
||||
while True:
|
||||
counter += 1
|
||||
com_queue.put(str(counter))
|
||||
sleep(0.1)
|
||||
print("A")
|
||||
|
||||
if IsEnded != 0:
|
||||
break
|
||||
# continue
|
||||
|
||||
|
||||
class MainGUI(Gtk.Window):
|
||||
def __init__(self):
|
||||
Gtk.Window.__init__(self, title="Append")
|
||||
self.com_queue = queue.Queue()
|
||||
self.worker_thread = None
|
||||
self.liststore = None
|
||||
|
||||
self.box = Gtk.Box(spacing=6)
|
||||
self.add(self.box)
|
||||
|
||||
self.textArea = Gtk.TextView()
|
||||
self.textbuffer = self.textArea.get_buffer()
|
||||
self.textbuffer.set_text("Ready: \n")
|
||||
self.box.pack_start(self.textArea, True, True, 0)
|
||||
|
||||
self.button1 = Gtk.Button(label="Start")
|
||||
self.button1.connect("clicked", self.butt)
|
||||
self.box.pack_start(self.button1, True, True, 0)
|
||||
|
||||
self.button2 = Gtk.Button(label="Stop")
|
||||
self.button2.connect("clicked", self.butt2)
|
||||
self.box.pack_start(self.button2, True, True, 0)
|
||||
|
||||
self.tid = None
|
||||
self.proc = None
|
||||
#self.state = mp.Value('i', 0)
|
||||
# more gui initialization...
|
||||
|
||||
def launch_worker_thread(self):
|
||||
#self.proc = Process(target=do_work, args=(self.com_queue,))
|
||||
#self.proc.start()
|
||||
|
||||
self.worker_thread = threading.Thread(target=do_work, args=(self.com_queue,))
|
||||
self.worker_thread.start()
|
||||
try:
|
||||
self.tid = GLib.timeout_add(1, self.check_queue, None) # run check_queue every 1 second
|
||||
except:
|
||||
print("Error")
|
||||
|
||||
def butt(self, widget):
|
||||
self.launch_worker_thread()
|
||||
|
||||
def butt2(self, widget):
|
||||
global IsEnded
|
||||
IsEnded = 1
|
||||
|
||||
def prn(self, ignored):
|
||||
print("B")
|
||||
GLib.idle_add(self.update_treeview, "update")
|
||||
|
||||
def check_queue(self, ignored):
|
||||
if self.tid is not None:
|
||||
#if self.worker_thread.is_alive():
|
||||
try:
|
||||
update = self.com_queue.get(False)
|
||||
GLib.idle_add(self.update_treeview, update) # send tuple
|
||||
except queue.Empty:
|
||||
pass
|
||||
return True # to keep timeout running
|
||||
else:
|
||||
return False # to end timeout
|
||||
|
||||
def update_treeview(self, update):
|
||||
text_end = self.textbuffer.get_end_iter()
|
||||
self.textbuffer.insert(text_end, str(update)) # here update the treeview model with tuple
|
||||
|
||||
if __name__ == "__main__":
|
||||
gui = MainGUI()
|
||||
gui.connect("destroy", Gtk.main_quit)
|
||||
gui.show_all()
|
||||
Gtk.main()
|
||||
IsEnded = 1
|
102
GTK-examples/liveProgressBar.py
Normal file
102
GTK-examples/liveProgressBar.py
Normal file
@ -0,0 +1,102 @@
|
||||
import multiprocessing as mp
|
||||
import time
|
||||
|
||||
import gi
|
||||
gi.require_version('Gtk', '3.0')
|
||||
from gi.repository import Gtk, GLib
|
||||
|
||||
|
||||
def really_looong_operation(state):
|
||||
"""
|
||||
Do something that will block your app for a long time
|
||||
"""
|
||||
# tick every 200 milliseconds
|
||||
tick = 1
|
||||
state.value = 0
|
||||
for k in range(100):
|
||||
# In real life this might be invert a huge matrix or whatever...
|
||||
time.sleep(tick)
|
||||
state.value = k + 1
|
||||
# Final activity...
|
||||
time.sleep(2*tick)
|
||||
|
||||
|
||||
class PBarDemo(Gtk.Window):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(title="Progressing...")
|
||||
self.connect("destroy", Gtk.main_quit)
|
||||
self.set_border_width(10)
|
||||
|
||||
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
|
||||
self.add(vbox)
|
||||
|
||||
self.pbar = Gtk.ProgressBar()
|
||||
self.pbar.set_show_text(True)
|
||||
vbox.pack_start(self.pbar, True, True, 0)
|
||||
|
||||
self.switch = Gtk.Switch()
|
||||
self.switch.connect("notify::active", self.on_start_stop)
|
||||
vbox.pack_start(self.switch, True, True, 0)
|
||||
|
||||
self.tid = None
|
||||
self.proc = None
|
||||
self.state = mp.Value('i', 0)
|
||||
# Guarantee the start state
|
||||
self._stop()
|
||||
|
||||
def _stop(self):
|
||||
# Guarantee that everything is in "stop mode"
|
||||
if self.tid is not None:
|
||||
#GObject.source_remove(self.tid)
|
||||
GLib.source_remove(self.tid)
|
||||
|
||||
if self.proc is not None and self.proc.is_alive():
|
||||
self.proc.terminate()
|
||||
self.tid = None
|
||||
self.proc = None
|
||||
self.pbar.set_fraction(0.0)
|
||||
self.pbar.set_text('Ready...')
|
||||
|
||||
def on_start_stop(self, switch, prop):
|
||||
# Check this is the right property
|
||||
if prop.name != "active":
|
||||
return
|
||||
|
||||
self._stop()
|
||||
if not switch.get_active():
|
||||
return
|
||||
# Launch the activity... depending of what you want to do,
|
||||
# it might be better to use a pool of workers or other tricks
|
||||
self.proc = mp.Process(target=really_looong_operation, args=(self.state,))
|
||||
self.proc.start()
|
||||
# And the timer that update the progressbar
|
||||
#self.tid = GObject.timeout_add(250, self.running, None)
|
||||
self.tid = GLib.timeout_add(250, self.running, None)
|
||||
self.pbar.set_text("0%")
|
||||
|
||||
def running(self, ignored):
|
||||
value = self.state.value
|
||||
if value >= 100:
|
||||
# Stop working at 100%
|
||||
self.proc.join()
|
||||
self._stop()
|
||||
self.switch.set_active(False)
|
||||
# Return false to stop the timer
|
||||
return False
|
||||
else:
|
||||
frac = value / 100
|
||||
self.pbar.set_fraction(frac)
|
||||
self.pbar.set_text(f"{frac:.0%}")
|
||||
|
||||
# Return True so this timer is considered active
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
win = PBarDemo()
|
||||
win.show_all()
|
||||
try:
|
||||
Gtk.main()
|
||||
except:
|
||||
exit()
|
5
GTK-examples/seialTest.py
Normal file
5
GTK-examples/seialTest.py
Normal file
@ -0,0 +1,5 @@
|
||||
import serial
|
||||
ser = serial.Serial('/dev/ttyUSB0') # open serial port
|
||||
print(ser.name) # check which port was really used
|
||||
ser.write(b'hello') # write a string
|
||||
ser.close() # close port
|
7
GTK-examples/test.csv
Normal file
7
GTK-examples/test.csv
Normal file
@ -0,0 +1,7 @@
|
||||
V,uint8_t,x,10
|
||||
V,int,y,86248
|
||||
V,float,variable,123.98
|
||||
V,int,fresh,10
|
||||
V,float,ser,1593.2
|
||||
V,int,dzes,1273
|
||||
R,float,derw,127
|
|
Loading…
x
Reference in New Issue
Block a user