Python Forum
How to use an Emulator and a MttQ broker?
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use an Emulator and a MttQ broker?
#11
It doesn't make any sense to compare EntOn() to anything. The function always returns None. But this doesn't matter because what you are doing with the Histo panel doesn't make any sense either.

I think the Histo panel is supposed to be a log of events that occurred while the program is running. When you turn the lights on you add a log message. When you turn the lights off you add a log message. Each log message has a timestamp and a description of what happened. For that to happen the Histo panel must be created at the start of the program, not when the user presses the Afficher button. The only thing the Afficher button should do is show() the panel.

I think the Histo panel would make a great class. In addition to __init__() which makes the widgets the class would have a log() method for adding a messag to the log.
class Histo(Toplevel):
    """A window for viewing log messages"""
    def __init__(self):
        super().__init__()
        self.title('Historique')  
        self.text = Text(self, width=40, height=10)
        self.text.pack(padx=5, pady=5)

    def log(self, msg):
        """Append log message to text"""
        now = datetime.datetime.now()
        self.text.insert(INSERT, f"{now} {msg}")
Now all the Afficher button has to do is show the window.
histo = Histo()
btn6 = Button(root, text='Afficher', command=histo.show)
The EntOn() function also does some things at the wrong time. When the user presses the On button the EntOn function should set the Ent output high, update the text of a label, and log a message.
def EntOn():
    # Set the output
    GPIO.output(Ent, GPIO.HIGH)
    # Change the entOn label and log the event
    entOnLabel.config(text="On")
    histo.log(Lumière entrée allumée")  # Histo panel needs to exist before this is called
And EntOff() should look like this:
def EntOff():
    # Set the output
    GPIO.output(Ent, GPIO.LOW)
    # Change the entOn label and log the event
    entOnLabel.config(text="Off)
    histo.log("Lumière entrée fermée")
Notice that neither of these configure the GPIO or create labels. That should be done once at the very start of the program, not every time a button is pressed.

Answers to questions in your last post:

ct does not change because it is assigned a value once, at the start of the program. A datetime object does not change to reflect the current time. You need to call ct = datetime.now() each time you want ct to have the current time.

You history window only shows one line because you make a new history window each time you press the Afficher button.

The value of a function is None unless the function has a "return". This function returns 42
def func():
    return 42
A function with no arguments can have a return value. A function with many arguments may not return a value. What is returned when a function executes depends on what follows "return" inside the function.

This comment from you post makes no sense to me:
Quote:The idea is to test if what's in the function is executed than execute if statement
There is no reason to test if a function is executed. If you call a function it will execute. Do you mean that you want to test if all the code in EntOn() executed successfully? What code are you concerned about? I don't see where you are checking anything inside EntOn.
Reply
#12
Quote:Also is there a way to test the mongodb part of my script online?
I am using the rasbian but pymongo return error type cant find pymongo when it is actually installed
When you have errors please post the error message an the traceback.
Reply
#13
Good Morning,

I used the wrong choice of words. I wanted to know if EntOff() has been called, if it has been (button pressed) called print timestamp in the historic window. I was doing side tests for mongo to see if it would show up in the histo log, but i never posted the code. Sorry.

The project has you guessed send info as a timestamp to a log(histo). There is 3 parts, the GPIO RPiSim i have not been able to make it work yet. The second is the MttQ server, you send the time stamp from the program and get the info out from a terminal. Thats fine. The third is to send the timestamp log to mangodb and than you retrieve the timestamp log from mango server and make it appear in the histo log. That third part i cant test on my rasbian because every time i run the code i get this:

Error:
Traceback (most recent call last): - File "/home/pi/Desktop/Projet_1.py", line 9, in <module> import pymongo ModuleNotFoundError: No module named 'pymongo'
But pymongo is installed. That part is commented in the code. Line 38-39-14-15-17

BTW what is the use of show in your code, it is returning 'Histo' object has no attribute 'show'.

I got an exam on classes in august i really need to find a good tutorial about this to learn more. Its not my strong suite.

For GPIO i tried many times to make it work but cant figure out all those errors:

Error:
Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__ return self.func(*args) File "/home/pi/Desktop/Projet_1.py", line 91, in EntOff GPIO.output(Ent, GPIO.LOW) RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM) Pin 22 - Low
Thank you
Reply
#14
Python disagrees that pymongo is installed. Which version of Python are you using? What is your OS? How did you install pymongo?

Did you do all the GPIO setup at the start of the program? All of this stuff has to happen before you call mainloop()
GPIO.setmode(GPIO.BCM)
GPIO.setup(Ent,GPIO.OUT)
GPIO.setwarnings(False)
window.show() is how you have a hidden window drawn to the screen, but it is for Qt, not tkinter. My mistake. Here's a working example of how I think the histo window should work.
import tkinter as tk
import datetime

class Histo(tk.Toplevel):
    """A window for viewing log messages"""
    def __init__(self):
        super().__init__()
        self.title('Historique')  
        self.text = tk.Text(self, width=40, height=10)
        self.text.pack(padx=5, pady=5)
 
    def log(self, msg):
        """Append log message to text"""
        now = datetime.datetime.now()
        self.text.insert(tk.INSERT, f"{now} {msg}\n")

class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.histo = Histo()
        self.histo.withdraw()
        button = tk.Button(self, text="Press Me", command=self.show_histo)
        button.pack(padx=20, pady=20)

    def show_histo(self):
        self.histo.log("Show histo")
        self.histo.deiconify()

MainWindow().mainloop()
Here I combined logging and drawing the window. Your app will do logging for on/off events and draw the panel when the afficher button is pressed.
Reply
#15
pi@raspberrypi:~ $ pip freeze | grep pymongo
pymongo==3.4.0

for the gpio i tried inside and outside tkinter. i get one error or another actualy the same:

If i want to clear the histo window or limit the number of output to 20 lines. There must be a command to do that?
Reply
#16
There must be some GPIO setup that you are not doing. The only error you've posted would be fixed if you set the GPIO mode before trying to set the output.

I think ScrolledText would be a better choice than limiting or clearing the log.

https://www.pythontutorial.net/tkinter/t...olledtext/

What does it say if you type: pip show pymongo

My guess is that you do not have pymongo installed for the python you are using.
Reply
#17
Hello,

It says it is installed. I have been trying all day yesterday to create a bootable usb ubuntu key. Somewhere it fails, cant use software like firefox.
The homework has been submitted so i am just testing other options for the next time. Trying to uderstand where i am doing wrong.

I cross on stackoverflow on that solution : https://stackoverflow.com/questions/2796...ext-widget

For the GPIO i dont know anymore, i have tried with a collegue on its computer and it was working. A few weeks ago i bought a Dell, it took a month a half to receive it and it was faulty i had to return it.
I dont know what to do anymore.
Reply
#18
What is printed if you type "pip show pymongo"
Reply
#19
pi@raspberrypi:~ $ pip show pymongo
Name: pymongo
Version: 3.4.0
Summary: Python driver for MongoDB <http://www.mongodb.org>
Home-page: http://github.com/mongodb/mongo-python-driver
Author: Mike Dirolf
Author-email: [email protected]
License: Apache License, Version 2.0
Location: /home/pi/.local/lib/python2.7/site-packages
Requires:
Required-by:
Reply
#20
It looks like pymongo is installed for Python 2.7
Location: /home/pi/.local/lib/python2.7/site-packages
You aren't using Python 2.7, are you?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyautogui with a display emulator? gumby4231 0 2,610 Jul-30-2020, 02:46 PM
Last Post: gumby4231
  running python script from shell invoked with os.system("x-terminal-emulator -e /bin/ markhaus 2 3,084 Feb-21-2019, 11:55 PM
Last Post: markhaus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020