forked from USC-EE-250L-Spring-2023/lab-04
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm_pub.py
61 lines (45 loc) · 2.02 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
"""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
user = "mihirsin"
"""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 = socket.gethostbyname(socket.gethostname())
"""your code here"""
# 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="eclipse.usc.edu", port=11000, keepalive=60)
client.connect(host="localhost", 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(f"{user}/ipinfo", f"{ip_address}")
print("Publishing ip address")
time.sleep(4)
# get date and time
"""your code here"""
time_now = datetime.now().strftime("%m-%d-%Y %H:%M")
# publish date and time in their own topics
"""your code here"""
client.publish(f"{user}/date", f"{time_now}")
print("Publishing date")