Re: [Tutor] Tkinter and threading

2016-06-02 Thread Marco Soldavini
Thanks for you answers!

On Thu, Jun 2, 2016 at 6:39 PM, Peter Otten <__pete...@web.de> wrote:

>> For example a state machine with a var state which can have some
>> discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
>> and a text element on the gui that reports that state.
>>
>> So a button cause a transition > the python loop (not the gui loop)
>> detects the transition and changes the state var value > the gui
>> refresh its value on screen.
>>
>> I wrote some code to try it without threading but it does not give the
>> expected result as it seems the button update status action is already
>> triggered. I am missing some basic point here
>
> Indeed your problem has nothing to do with threads.
>>


Yes i know it could be done without threads, but for study reason i
want to separate the logic from representation (the HMI). That's how
usually program industrial machines. HMI serves only to display and
change variables, not to execute logic.

I want to build a mockup of a machine I saw at work, with statuses and alarms.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Tkinter and threading

2016-06-02 Thread Marco Soldavini
Hello,
probably this is a very naive question, but I've read some stuff on
Tkinter and its infinite loop.

Then about how can i bind actions to elements, for example buttons.

What if I want to run another loop beside the graphical interface in
the same python script?

For example a state machine with a var state which can have some
discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
and a text element on the gui that reports that state.

So a button cause a transition > the python loop (not the gui loop)
detects the transition and changes the state var value > the gui
refresh its value on screen.

I wrote some code to try it without threading but it does not give the
expected result as it seems the button update status action is already
triggered. I am missing some basic point here

from Tkinter import *

state = "STOPPED"

root = Tk()

myContainer1 = Frame(root)
myContainer1.pack()
label1=Label(myContainer1, text=state, font = "Helvetica 16 bold italic")
label1.pack()

def change(new_state):
label1.config(text=new_state)

button1 = Button(myContainer1, text="START")
button1.bind("", change("START"))
button1.pack()
button2 = Button(myContainer1)
button2["text"]= "STOP"
button2.pack()
root.mainloop()


Thanks
marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] XML and ElementTree

2016-04-25 Thread Marco Soldavini
I've a few questions about parsing XML. I wrote some code that works
but I want to know which are the most intelligent data structures to
parse data to

Consider that my XML file is something like the following:




1
XXX

   
   
   
   
   
   







So root element can have station child element from 1 to n
Each station element have unique child elements apart from groups
which may have more group child element each with a few tags

Now I want to parse this xml file and get the tag values into
variables in python
I could have 1 station element or 2 or 3
I could append all data in a long list, but is this good?
Could it be better to build a dictionary for each station element and
then build a list of dictionary
Which method you suggest to find data and use it after parsing it?

If later in the program I want to access a variable value I want to do
it with the xml tag name and not with an index like Settings[10] for
example but something like Settings['tag']

But what if I have more than one structure like station which has the same keys?

Following is part of my code for now.
Thanks!
marco


try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET


# Settings XML File Parsing

tree = ET.parse('settingstest.xml')
root = tree.getroot()

stations = len(root)
print "Found ",stations, " stations configured in settings file"

Settings = []
for station in root:
   StationId = station.find('StationId')
   Settings.append(StationId)
   .
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ImportError: No module named...

2016-04-18 Thread Marco Soldavini
Yeah, I spotted the mistake. There was a file left in the folder named
reportlab.pyc which I could not see from the pycharm interface.

Thanks!

On Mon, Apr 18, 2016 at 1:47 AM, Danny Yoo  wrote:
>
>> But I get the following error code on line 1
>>
>> ImportError: No module named pdfgen
>>
>
> Is reportlab.pdfgen a standard part of that package's installation?
>
> You might want to check for possible conflicts with other things called
> reportlab.  Do you have any files in the current directory that are called
> "reportlab"?
>
> You might also try the following:
>
> ###
> import reportlab
> print(reportlab.__file__)
> ###
>
> which hopefully should point to the expected path.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] ImportError: No module named...

2016-04-17 Thread Marco Soldavini
I am running this configuration

Win7 64 bit
Python 2.7.9
PyCharm Community Edition 4.5.4
Reportlab-2.8.win32-py2.7

I am try to running this simple example code

from reportlab.pdfgen import canvas
from reportlab.platypus import Image

im = Image ("logo.jpg")
c = canvas.Canvas("hello.pdf")
c.drawString(100,750,"Welcome to Reportlab!")
c.save()

But I get the following error code on line 1

ImportError: No module named pdfgen


I've checked my install and I have reportlab under
C:\Python27\Lib\site-packages\reportlab

I don't understand why this was working last time and now it doesn't anymore.
It could be an install problem?

Thanks
Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello! Questions

2016-02-19 Thread Marco Soldavini
On Fri, Feb 19, 2016 at 3:32 PM, Peter Otten <__pete...@web.de> wrote:

>
>
> Also, after reading http://openopc.sourceforge.net/api.html I wonder if it
> wouldn't be better to go with the timestamp provided by the server
>
>   bool1.append(opc.read(".watchdog"))
>

yes but my next step is to load some of this data up to SQL and the
timestamp provided by the opc was difficult to manage into a TIME field. I
manage to insert the appended data instead with the timestamp generated
with my code.

I'll work more on that to see if it is possible to get the original
timestamp. I don't require high precision just something around the second
is ok.


>
> With a slight modification of Alan's suggestion you could write to a list
> of
> dicts instead of a dict of lists like so:
>
> # outside the loop
> WANTED = [".watchdog", ".analog1", ".analog2]
> data = []
>
> # in the loop:
>  data.append({r[0]:r[1:] for r in opc.read(WANTED)})
>
>
>
Thanks for the helpful hints. I have a ton of questions yet to come!

Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello! Questions

2016-02-19 Thread Marco Soldavini
Sorry, Here my code in plaintext

#While loop - scanning and storing OPC values at scan rate
while (abort == 0):

    # ESC pressed?
    if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
        abort = 1
        break

    # Server up
    if opc.ping():


        if opc['.run_batch'] == True and rec_started == False:
            # Setting arrays for variables
            bool1 = []
            ana1 = []
            ana2 = []
            ana3 = []
            ana4 = []
            rec_started = True

        if opc['.run_batch'] == True and rec_started == True:
            # scan time
            time2 = time.time()
            dtime = time2 - time1

            if dtime > 2 and comm_alarm == False:
                dt = datetime.datetime.now()
                
bool1.append((opc.read('.watchdog')[0],opc.read('.watchdog')[1],dt))
                
ana1.append((opc.read('.analog2')[0],opc.read('.analog2')[1],dt))
                time1 = time2
                

    else:
        # scan time
        time2 = time.time()
        dtime = time2 - time1
        if dtime > 2:
            print "ERROR: OPC Server is down”



Il giorno 19 febbraio 2016 @ 02:18:05, Alan Gauld (alan.ga...@btinternet.com) 
ha scritto:
> Let's say I can have 30-40 variables (so 30-40 append instructions at every 
> cycle, with same scan rate). 

Its not clear what the scan rate actually is. 
How many scans per second? 


yes scan per second. For example a new fetch every 2 second, so a new append to 
array every 5 second



> shall run for 2 hours and gather let's say 2000 elements in 40 arrays, 
> could this be a problem in term of computation? 

Yes it could, but it depends on what size the data is. 
You need to do some basic math to calculate it out. 

40 * 2000 = 80k items. If they are integers then its 
4 bytes per item so 320Kbytes. Not too bad. If they 
are 100 character strings then its into MB but on a 
modern PC still not too bad. But if it's intended to 
run in an embedded controller with only 1M of RAM 
it might be a big issue. 


Pc for sure, I think with 8GB RAM. I’ll do some detailed calculations about 
that.

> Second question is I want the arguments in the opc.read command not to be 
> hard coded but coming from a configuration files. 

OK. You might want to think about what that file 
format would look like. 


I’d like to have an xml file or csv file to parse (another topic I wanna learn) 
and in this file I have a table defining my variables with a name and another 
field for description


> You see the names of my arrays? bool1, ana1, ana2, etc... Is it possible to 
> derive number and names of these variables from an external files. 

It is but its usually a bad idea. 
Better is to use a dictionary with your "variables" 
as keys and your arrays as values. So your append 
looks like 

data = dict() 
keyName = readFromFile() 
value = readFromFile() 

data[keyName].append(value) 
Ok so I will look more into dictionaries, it is like hash tables?





> Let's say in this configuration file I can say I have to read 10 arrays or 
> 20 arrays and then my program adjust the while cycle consequently. 

Yes that's doable. 

> Maybe an array of array where the second dimension is coming from the 
> config file. 

I'd use the dictionary approach rather than arrays of arrays. 
(Which are probably lists of lists in Python.) 


Thanks!
Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello! Questions

2016-02-18 Thread Marco Soldavini
On Wed, Feb 17, 2016 at 11:13 AM, Alan Gauld 
 wrote:


> > My first question is about data types, data structures in general and how
> > to organize an efficient loop for recording data.
>
> > while (stop condition false)
> >read data
> >write data into local array or something
> >wait sample time
>
> That's a good start. What is the question?
> You say you know how to read data fro openopc, so the
> first loop line should be fine.
> Storing into a list involves the append method:
>
> myDataList.append(myData)
>
> and the wait will probably be openopc specific
> but if not you can use the time.sleep() function.
>
>
> hth
> --
> Alan G



Ok here my main loop for gathering data (stripped off some code to make it
easier to read):


*# While loop - scanning and storing OPC values at scan rate **while *(abort
== 0):


*# ESC pressed? **if *msvcrt.kbhit() *and *ord(msvcrt.getch()) == 27:
abort = 1


*break *
*# Server up **if *opc.ping():


*if *opc[*'.run_batch'*] == True *and *rec_started == False:

*# Setting arrays for variables *bool1 = []
ana1 = []
ana2 = []
ana3 = []
ana4 = []
rec_started = True

*if *opc[*'.run_batch'*] == True *and *rec_started == True:

*# scan time *time2 = time.time()
dtime = time2 - time1

*if *dtime > 2 *and *comm_alarm == False:
dt = datetime.datetime.now()
bool1.append((opc.read(*'.watchdog'*)[0],opc.read(
*'.watchdog'*)[1],dt))
ana1.append((opc.read(*'.analog2'*)[0],opc.read(*'.analog2'*
)[1],dt))
time1 = time2


*else*:

*# scan time *time2 = time.time()
dtime = time2 - time1
*if *dtime > 2:
*print **"ERROR: OPC Server is down"*



As you can see I am using append to store data from opc.read command which
returns elements of string array.

Let's say I can have 30-40 variables (so 30-40 append instructions at every
cycle, with same scan rate).

Is this scalable when variables are getting bigger. What if this program
shall run for 2 hours and gather let's say 2000 elements in 40 arrays,
could this be a problem in term of computation?


Second question is I want the arguments in the opc.read command not to be
hard coded but coming from a configuration files.


You see the names of my arrays? bool1, ana1, ana2, etc... Is it possible to
derive number and names of these variables from an external files.

Let's say in this configuration file I can say I have to read 10 arrays or
20 arrays and then my program adjust the while cycle consequently.


Maybe an array of array where the second dimension is coming from the
config file.


Is this clear?


Version of python is 2.7.9 running on Windows 7.


Cheers,

Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Hello! Questions

2016-02-17 Thread Marco Soldavini
Hi,
I am almost new to python and I am trying to build a not so easy app (but
very neat and useful) related to industrial automation.

Is this the right place to knock down problems one by one?
Basically my app has several interactions but the most important is reading
values from an embedded machine (better a PLC) via the OPC protocol.

I already tested this with some values of various kind (real, boolean,
strings). Basically each tag is read with a fixed sample time from a stream
opened in OPC and recorded onto an array in python.

Is it better I explain you the main picture? I am not here for spoon
feeding but just tips and suggestion and maybe solution to particular
problems I might find on the track.

Something about OPC is here: https://opcfoundation.org/about/what-is-opc/

The lib I am using is openopc.

My first question is about data types, data structures in general and how
to organize an efficient loop for recording data.

Basically something like

while (stop condition false)
read data
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Hello! Questions

2016-02-17 Thread Marco Soldavini
I hit the send button too early. anyway

Basically something like

while (stop condition false)
read data
write data into local array or something
wait sample time


Thanks
marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor