forked from 20gtrue/lab-04
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvm_pub.py
63 lines (49 loc) · 2.13 KB
/
vm_pub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""EE 250L Lab 04 Starter Code
Run vm_sub.py in a separate terminal on your VM."""
import paho.mqtt.client as mqtt
import time
from datetime import datetime
import socket
"""This function (or "callback") will be executed when this client receives
a connection acknowledgement packet response from the server. """
def on_connect(client, userdata, flags, rc):
print("Connected to server (i.e., broker) with result code "+str(rc))
if __name__ == '__main__':
#get IP address
ip_address=0
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
# print(f"IP Address: {ip_address}")
#create a client object
client = mqtt.Client()
#attach the on_connect() callback function defined above to the mqtt client
client.on_connect = on_connect
"""Connect using the following hostname, port, and keepalive interval (in
seconds). We added "host=", "port=", and "keepalive=" for illustrative
purposes. You can omit this in python. For example:
`client.connect("eclipse.usc.edu", 11000, 60)`
The keepalive interval indicates when to send keepalive packets to the
server in the event no messages have been published from or sent to this
client. If the connection request is successful, the callback attached to
`client.on_connect` will be called."""
client.connect(host="broker.hivemq.com", port=1883, keepalive=60)
"""ask paho-mqtt to spawn a separate thread to handle
incoming and outgoing mqtt messages."""
client.loop_start()
time.sleep(1)
while True:
#replace user with your USC username in all subscriptions
client.publish("gtrue/ipinfo", f"{ip_address}")
print("Publishing ip address")
time.sleep(4)
#get date and time
from datetime import date;
today = date.today()
ctime = datetime.now()
#publish date and time in their own topics
client.publish("gtrue/date", f"{today}")
print("Publishing todays date")
time.sleep(4)
client.publish("gtrue/ctime", f"{ctime}")
print("Publishing time")
time.sleep(4)