Source code for meterReading_04a

#!/usr/bin/env python

import DatabaseManager
import os              # for the 'cls' command to clear the screen
import datetime        # for date.today, timedelta and date.weekday functions
import webbrowser
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import *

[docs]class TabbedWindow(QWidget): def __init__(self, text): QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) label1 = QLabel(text[0]) label2 = QLabel(text[1]) tabwidget = QTabWidget() tabwidget.addTab(label1, "Gas") tabwidget.addTab(label2, "Electricity") layout.addWidget(tabwidget, 0, 0)
[docs]class WindowTable(QWidget): def __init__(self, winTitle, row, column, content): super().__init__() self.title = winTitle self.left = 600 self.top = 400 self.width = 600 self.height = 400 self.initUI(row, column, content)
[docs] def initUI(self, row, column, content): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.createTable(row, column, content) # Add box layout, add table to box layout and add box layout to widget self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) # Show widget self.show()
[docs] def createTable(self, rowCount, columnCount, content): # Create table self.tableWidget = QTableWidget() self.tableWidget.setRowCount(rowCount) self.tableWidget.setColumnCount(columnCount) count = 0 for row in content: index = 0 try: print(row[index]) self.tableWidget.setItem(count,index, QTableWidgetItem(row[index])) index += 1 except IndexError: break count += 1 self.tableWidget.move(0,0) # table selection change self.tableWidget.doubleClicked.connect(self.on_click)
[docs] @pyqtSlot() def on_click(self): print("\n") for currentQTableWidgetItem in self.tableWidget.selectedItems(): print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
[docs]def cls(): # defining a function to clear the screen os.system('cls' if os.name=='nt' else 'clear')
[docs]def dateSuffix(date): if date == 1 or date == 21 or date == 31: string= "st " elif date == 2 or date == 22: string = "nd " elif date == 3 or date == 23: string = "rd " else: string = "th " return string
[docs]def getReadings(result, fuelFlag): listOfReadings = [] record = {} for x in result: if x[2] == fuelFlag: date = x[1] yearday = int(date.strftime("%j")) year = int(date.strftime("%Y")) month = (date.strftime("%b")) week = int(date.strftime("%W")) day = int(date.strftime("%d")) reading = x[3] record = (day, week, month, year, yearday, reading) listOfReadings.append(record) return listOfReadings
[docs]def formatReadings(readings, fuelString): printout = [] for x in readings: count = readings.index(x) + 1 try: previous_entry = readings[count] string = dateSuffix(x[0]) if x[3] > previous_entry[3]: if (previous_entry[3]%4) == 0: # looking for leap years - fails with 2100, 2200, 2300, 2500, etc days = int(366 + x[4] - previous_entry[4]) else: days = int(365 + x[4] - previous_entry[4]) else: days = x[4] - previous_entry[4] units_used_per_week = int(7 * (x[5] - previous_entry[5])/days) day = str(x[3]) + " Week " + str(x[1]) + ":\t" + str(x[0]) + string + str(x[2] + "\t") thisRow = [(str(x[3]), str(x[1]), str(x[5]), str(units_used_per_week))] printout.append(thisRow) except IndexError: break return printout
[docs]def window(text): app = QApplication(sys.argv) """ You have to pass a list of strings to QApplication; it could be an empty list. sys.argv is a list in Python, which contains the command-line arguments passed to the script. In this instance all it seems to do is pass the name of the script (e.g. meterReading_04a.py) Not sure how/why this helps, but perhaps all will become clear! """ widget = QWidget() textLabel0 = QLabel(widget) textLabel0.setText(text[0]) textLabel0.move(110,85) textLabel1 = QLabel(widget) textLabel1.setText(text[1]) textLabel1.move(110,185) widget.setGeometry(50,50,1020,300) widget.setWindowTitle("Dud's Python Script to Record Electricity and Gas Meter Readings") widget.show() exitCode = app.exec_()
[docs]def main(): cls() zeropi = { 'user': 'andrew', 'password': 'password123', 'host': 'zeropi', 'port': '3306', 'database': 'meterReadings', 'raise_on_warnings': True } localhost = { 'user': 'andrew', 'password': 'password123', 'host': 'localhost', 'port': '3306', 'raise_on_warnings': True } dB = DatabaseManager.DbMan(localhost, 'meterReadingsBackup2020082') while dB.status == "Connected": text = [] elecReadings = [] gasReadings = [] sqlQuery = "SELECT * FROM Readings ORDER BY readingID DESC LIMIT 12" result = dB.query(sqlQuery) elecReadings = getReadings(result, 0) gasReadings = getReadings(result, 1) gastext = formatReadings(gasReadings, "Gas") electext = formatReadings(elecReadings, "Electricity") winTitle = "Data from the " + dB.database + " database hosted on " + dB.host text.append(gastext) text.append(electext) app = QApplication([winTitle]) window = TabbedWindow(text) window.show() row = 5 column = 5 content = [(1, 2), (3, 4)] ex = WindowTable(winTitle, row, column, content) app.exec_() print("Buggered!")
if __name__ == '__main__': print("Running the main loop") main() print("Finished the main loop")