#!/usr/bin/python

# Lab 1 - Setting up.
# Make sure your host and region are correct.

import sys
import ssl
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import json
import time
import random
import datetime
import uuid

#Setup our MQTT client and security certificates
#Make sure your certificate names match what you downloaded from AWS IoT

mqttc = AWSIoTMQTTClient("1234")

#Make sure you use the correct region!
mqttc.configureEndpoint("data.iot.us-east-1.amazonaws.com",8883)
mqttc.configureCredentials("./rootCA.pem","./tcu.private.key","./tcu.cert.pem")

#Function to encode a payload into JSON
def json_encode(string):
        return json.dumps(string)

mqttc.json_encode=json_encode

VIN="1FDNJ75P4PVA03896"
trip_id=str(uuid.uuid4())

#Declaring our variables


#This sends our test message to the iot topic
def send():
    #mqttc.publish("iot", message, 0)

    message = {
        "name": "speed",
        "value": random.randint(0,120),
        "vin": VIN,
        "trip_id": trip_id,
        "timestamp": str(datetime.datetime.now())
    }

    #Encoding into JSON
    message = mqttc.json_encode(message)


    mqttc.publish("tcu/vehicle/"+VIN,message,0)
    print "Message Published"


#Connect to the gateway
mqttc.connect()
print "Connected"

#Loop until terminated
while True:
    send()
    time.sleep(5)

mqttc.disconnect()
#To check and see if your message was published to the message broker go to the MQTT Client and subscribe to the iot topic and you should see your JSON Payload

