473,788 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

wx.Dialog subclass gets dbServer instance

bartonc
6,596 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. #Boa:Dialog:TiltCalibrate
  2.  
  3. import wx
  4.  
  5. import Multiply
  6. from PMD import DefaultMultiplier
  7. from time import sleep
  8. from string import digits
  9. from wxdbtools import MySQLInsert, MySQLUpdate, MySQLSelect
  10.  
  11. SlopeChan = 0
  12. GradeChan = 1
  13. DistChann = 2
  14.  
  15. CalPhaseButtonText = ["Begin Calibration", "Calibrate Grade", "Calibrate X-Slope", "Can\'t Calibrate"]
  16. CalPhasePromptText = ["Set data collection vehicle in starting position:",
  17.                       "Rotate the vehicle 180 degrees (in place):",
  18.                       "Roll the vehicle forward until rear wheels are at starting position",
  19.                       "Invalid data has been received. Check PMD Setup for further information"]
  20.  
  21. HETAP_table_sql =    """CREATE TABLE  `HETAP_Setup`.`setup` (
  22.                           `setupID` int(4) unsigned NOT NULL auto_increment,
  23.                           `xctSerNum` varchar(45) NOT NULL default '',
  24.                           `xAxisSensitivity` decimal(5,3) default NULL,
  25.                           `yAxisSensitivity` decimal(5,3) default NULL,
  26.                           `xAxisOffset` decimal(7,6) default NULL,
  27.                           `yAxisOffset` decimal(7,6) default NULL,
  28.                           `zAxisSensitivity` decimal(7,6) default NULL,
  29.                           PRIMARY KEY  (`setupID`)
  30.                         ) ENGINE=InnoDB DEFAULT CHARSET=latin1;"""
  31.  
  32. def create(parent):
  33.     return TiltCalibrate(parent)
  34.  
  35. [wxID_TILTCALIBRATE, wxID_TILTCALIBRATECALIBRATEBUTTON,
  36.  wxID_TILTCALIBRATECANCELBUTTON, wxID_TILTCALIBRATEDONEBUTTON,
  37.  wxID_TILTCALIBRATEGRADEOFFSETTEXTCTRL, wxID_TILTCALIBRATEGRADESENSETEXTCTRL,
  38.  wxID_TILTCALIBRATEGRADETEXTCTRL, wxID_TILTCALIBRATESERNUMCOMBOBOX,
  39.  wxID_TILTCALIBRATESLOPEOFFSETTEXTCTRL, wxID_TILTCALIBRATESLOPESENSETEXTCTRL,
  40.  wxID_TILTCALIBRATESLOPETEXTCTRL, wxID_TILTCALIBRATESTATICBITMAP1,
  41.  wxID_TILTCALIBRATESTATICTEXT1, wxID_TILTCALIBRATESTATICTEXT2,
  42.  wxID_TILTCALIBRATESTATICTEXT3, wxID_TILTCALIBRATESTATICTEXT4,
  43.  wxID_TILTCALIBRATESTATICTEXT5, wxID_TILTCALIBRATESTATICTEXT6,
  44.  wxID_TILTCALIBRATESTATICTEXT7, wxID_TILTCALIBRATESTATICTEXT8,
  45.  wxID_TILTCALIBRATESTATICTEXT9,
  46. ] = [wx.NewId() for _init_ctrls in range(21)]
  47.  
  48. class TiltCalibrate(wx.Dialog):
  49.     def _init_ctrls(self, prnt):
  50.         # generated method, don't edit
  51.        # instantiate widgets
  52.  
  53.  
  54.     def __init__(self, parent):
  55.         self._init_ctrls(parent)
  56.  
  57.         self.publisher = self.Subscribe(parent)
  58.  
  59. ##        self.widgetList = [self.gradeSenseTextCtrl, self.slopeSenseTextCtrl,
  60. ##                           ]
  61.  
  62.         self.dbServer = parent.GetDBServer()
  63.         self.CheckDatabase()
  64.  
  65.         self.calibPhase = 0
  66.         self.bitmapList = []
  67.         self.GetCalibBitmaps()
  68.  
  69.         self.staticBitmap1.SetBitmap(self.bitmapList[0])
  70.         self.FillFromDB()
  71.  
  72.         self.SetupMultipliers()
  73.  
  74.     def CheckDatabase(self):
  75.         dbServer = self.dbServer
  76.         if not dbServer.DBExists("HETAP_Setup".lower()):
  77.             dbServer.Execute("CREATE DATABASE HETAP_Setup")
  78.             dbServer.Execute(HETAP_table_sql)
  79.             self.db_is_new = True   # probably don't need this flag
  80.         else:
  81.             self.db_is_new = False
  82.         print "db_is_new = ", self.db_is_new
  83.  
  84.     def FillFromDB(self):
  85.         varList = []
  86.         cursor = self.dbServer.Execute("SELECT * FROM `HETAP_Setup`.`setup`")
  87.         if cursor.rowcount:
  88.             rows = cursor.fetchall()
  89.             for i in range(4):
  90.                 try:
  91.                     varList.append(float(rows[0][i+2]))
  92.                 except TypeError:
  93.                     varList.append(0)
  94.             for row in rows:
  95.                 self.sernumComboBox.Append(row[1])
  96.         self.gradeSense = varList[0]/1000 or Multiply.DefaultTiltSense
  97.         self.slopeSense = varList[1]/1000 or Multiply.DefaultTiltSense
  98.         self.gradeOffset = varList[2] or Multiply.DefaultOffset
  99.         self.slopeOffset = varList[3] or Multiply.DefaultOffset
  100.         self.ShowOffsets()
  101.  
  102.     def Subscribe(self, dataSource):
  103.         publisher = dataSource.GetPublisher()
  104.         publisher.RegisterClientCallback(self.Update)
  105.         return publisher
  106.  
  107.     def SetupMultipliers(self):
  108.         ## Create multipliers and submit them to the publisher
  109.         self.gradeMultiplier = gm = Multiply.CrossbowMultiplier(GradeChan, self.gradeOffset, self.gradeSense)
  110.         self.slopeMultiplier = sm = Multiply.CrossbowMultiplier(SlopeChan, self.slopeOffset, self.slopeSense)
  111.         self.SubmitMultipliers(gm, sm)
  112.  
  113.     def SubmitMultipliers(self, gradeMult, slopeMult):
  114.         self.publisher.SetMultiplier(gradeMult)
  115.         self.publisher.SetMultiplier(slopeMult)
  116.  
  117.     def ResetMultipliers(self):
  118.         gradeMult = DefaultMultiplier(0)
  119.         slopeMult = DefaultMultiplier(1)
  120.         self.SubmitMultipliers(gradeMult, slopeMult)
  121.         self.staticText3.SetLabel("Old calibration data is being reset")
  122.         sleep(2)
  123.  
  124.     def Update(self, dataList):
  125.         i = self.calibPhase
  126.         try:
  127.             # Publisher sent valid data to us
  128.             self.grade = grade = dataList[GradeChan]
  129.             self.slope = slope = dataList[SlopeChan]
  130.             if i == 3:    # From waiting to begin phase
  131.                 self.calibPhase = 0
  132.                 self.SetWidgetText()
  133.         except TypeError:
  134.             # Publisher can't get valid data
  135.             if i == 3:
  136.                 return
  137.             self.slope = slope = 0
  138.             self.grade = grade = 0
  139.             self.calibPhase = 3     # Set phase to waiting
  140.             self.SetWidgetText()
  141.         # Upadate calibration display regardless
  142.         self.gradeTextCtrl.SetValue("%.1f %%" %grade)
  143.         self.slopeTextCtrl.SetValue("%.1f %%" %slope)
  144.  
  145.     def GetCalibBitmaps(self):
  146.         for i in range(4):
  147.             filename = "calib%d.bmp" %i
  148.             bitmap = wx.Bitmap(filename, wx.BITMAP_TYPE_BMP)
  149.             self.bitmapList.append(bitmap)
  150.  
  151.     def SetWidgetText(self):
  152.         """Caller must ensure calibration phase is set correctly."""
  153.         i = self.calibPhase
  154.         buttonText = CalPhaseButtonText[i]
  155.         staticText = CalPhasePromptText[i]
  156.         self.CalibrateButton.SetLabel(buttonText)
  157.         self.staticText3.SetLabel(staticText)
  158.         self.staticBitmap1.SetBitmap(self.bitmapList[i])
  159.  
  160.     def NextPhase(self, i):
  161.         i += 1
  162.         self.calibPhase = i * bool(i % 3)
  163.  
  164.     def PostWarning(self, msg):
  165.         wx.MessageBox(msg, "Error", wx.OK|wx.ICON_EXCLAMATION, self)
  166.  
  167.     def ShowOffsets(self):
  168.         self.gradeOffsetTextCtrl.SetValue("%.3f V" %self.gradeOffset)
  169.         self.slopeOffsetTextCtrl.SetValue("%.3f V" %self.slopeOffset)
  170.  
  171.     def OnCalibrateButton(self, event):
  172.         i = self.calibPhase
  173.         self.NextPhase(i)
  174.         resultList = self.publisher.GetRawData()
  175.         if i == 3:
  176.             return
  177.         if i == 0:
  178.             self.p0Grade = resultList[GradeChan]
  179.             self.p0Slope = resultList[SlopeChan]
  180.         elif i == 1:
  181.             p1Grade = resultList[GradeChan]
  182.             self.gradeOffset = gradeOffset = (self.p0Grade + p1Grade) / 2.0
  183.             # print self.p0Grade, p1Grade, gradeOffset
  184.             self.gradeMultiplier.InitMultiplier(gradeOffset, self.gradeSense)
  185.         elif i == 2:
  186.             p1Slope = resultList[SlopeChan]
  187.             self.slopeOffset = slopeOffset = (self.p0Slope + p1Slope) / 2.0
  188.             # print self.p0Slope, p1Slope, slopeOffset
  189.             self.slopeMultiplier.InitMultiplier(slopeOffset, self.slopeSense)
  190.         self.SetWidgetText()
  191.         self.ShowOffsets()
  192.  
  193.     def OnTextCtrlChar(self, event):
  194.         event.Skip()
  195.  
  196.     def OnDoneButton(self, event):
  197.         sernum = self.sernumComboBox.GetValue()
  198.         if not sernum:
  199.             self.PostWarning("Serial Number field is blank")
  200.             return
  201.         try:
  202.             gradeSense = float(self.gradeSenseTextCtrl.GetValue())
  203.         except ValueError:
  204.             self.PostWarning("X (Grade) sensitivity field has a bad value in it")
  205.             return
  206.         try:
  207.             slopeSense = float(self.slopeSenseTextCtrl.GetValue())
  208.         except ValueError:
  209.             self.PostWarning("Y (X-Slope) sensitivity field has a bad value in it")
  210.             return
  211.         query = MySQLSelect("`HETAP_Setup`.`setup`", xctSerNum=sernum)
  212.         cursor = self.dbServer.Execute(query)
  213.         nRows = cursor.rowcount
  214.         if nRows:
  215.             query = MySQLUpdate("`HETAP_Setup`.`setup`", dict(xAxisSensitivity=gradeSense,
  216.                                 yAxisSensitivity=slopeSense, xAxisOffset=self.gradeOffset,
  217.                                 yAxisOffset=self.slopeOffset), {}, xctSerNum=sernum)
  218.         else:
  219.             query = MySQLInsert("`HETAP_Setup`.`setup`", {}, xctSerNum=sernum,
  220.                                 xAxisSensitivity=gradeSense, yAxisSensitivity=slopeSense,
  221.                                 xAxisOffset=self.gradeOffset, yAxisOffset=self.slopeOffset)
  222.         self.dbServer.Execute(query)
  223.         self.Hide()
  224.  
  225.     def OnCancelButton(self, event):
  226.         self.Hide()
Dec 3 '06 #1
0 1608

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2426
by: Gerry Sutton | last post by:
Hi All! I have noticed a strange behavior when using a constant identifier to initialize an instance list variable in a base class and then trying to modifying the list in subclasses by using either the list.extend method or even by having the subclass create a whole new list in the variable. The following example illustrates the situation.
1
1654
by: flupke | last post by:
I'm using wxPython and design the gui via wxglade. One of the gui components is a simple dialog class that gets displayed when a user exits the program. I want to use the same dialog but with a different text for closing certain dialogs in the program. (it's a pure "do you want to exit <insert screen name>" dialog) What would i better use, knowing the rest of the gui is in a resource (xrc) file:
0
1453
by: Ian | last post by:
I have sub-classed the Page class in order to provide some base properties and methods that every page on my site will need access to. I would like to have these things show up in the Simple Binding window of the DataBindings dialog. I then found this site (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxurfDataBindingsDialogBox.asp) which says: The tree view displays these objects: the Page object; any...
8
1679
by: Lou Pecora | last post by:
I've been scanning Python in a Nutshell, but this seems to be either undoable or so subtle that I don't know how to do it. I want to subclass a base class that is returned from a Standard Library function (particularly, subclass file which is returned from open). I would add some extra functionality and keep the base functions, too. But I am stuck. E.g.
1
5003
by: s.lipnevich | last post by:
Hi All, Is anything wrong with the following code? class Superclass(object): def __new__(cls): # Questioning the statement below return super(Superclass, cls).__new__(Subclass) class Subclass(Superclass): pass
0
5663
bartonc
by: bartonc | last post by:
#Boa:Dialog:DBConnectDialog import wx import wxdbtools as db def create(parent): return DBConnectDialog(parent) =
0
7697
bartonc
by: bartonc | last post by:
#Boa:Dialog:DBConnectDialog import wx ##"""Given a set if login specs, create a dbServer instance and ## ensure that there is a valid, open connection to the database. ## If not, set the dbConnect to None. ## spec: dict(UserName=name, Password=pswd, ServerName=host) ## Allow names to be set with Default Holder. Consiter Dictionary ## or even a tuple? (name, pswd, host)"""
0
5240
bartonc
by: bartonc | last post by:
from MySQLdb import * from time import time class DBServer: def __init__(self, master): self.master = master def Login(self, servername, username, password): #, database="" """Attempt to create a database login. If successful, return an open connection. Otherwise, return None."""
2
4049
by: Glen | last post by:
Hello, I've written a script in python and put together a simple QFrame with a QTextBrowser with Designer. I've translated the C++ into python using puic4. The .py file is called outputWin.py. My Script and its functions are in cnt.py. Finally, my main is in pball.py which follows here: import sys from PyQt4 import Qt, QtCore from outputWin import * from cnt import *
0
10173
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4070
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.