import googlemaps from datetime import datetime import paho.mqtt.client as paho import time current_hour = datetime.now().hour #define mqtt function to connect to broker def pub_mqtt(message): broker="mqtt broker host" port=1883 user = "username" password = "password" def on_publish(client,userdata,result): #create function for callback print("data published \n") pass client1= paho.Client("control1") #create client object client1.on_publish = on_publish #assign function to callback client1.username_pw_set(user, password=password) #set username and password client1.connect(broker,port) #establish connection ret= client1.publish("traffic/ocas/waterloo",message) #I only want traffic updates in the afternoon if 11 < current_hour < 20: gmaps = googlemaps.Client(key='API key goes here') #set datetime now = datetime.now() #configure the conditions of the Google Maps traffic directions request directions_result = gmaps.directions("start address", "end address", mode="driving", alternatives="false", waypoints="via:lat long of waypoints", avoid="ferries", departure_time=now ) #wait a little bit time.sleep(2) #read the duration_in_traffic value = directions_result[0]['legs'][0]['duration_in_traffic']['text'] #get only the number and assign it to a variable value = int(''.join(filter(str.isdigit, value))) #00 will tell the lightcube to turn off messagetosend = "00" #change these number values to suit your needs. You could also use a percentage difference between duration_in_traffic and duration if 37 < value < 47: messagetosend = "20" elif value >= 47: messagetosend = "30" elif value <= 37: messagetosend = "10" else : messagetosend = "00" #send the message to the broker pub_mqtt(messagetosend) else: #otherwise turn the light off messagetosend = "00" pub_mqtt(messagetosend)