# AUTOGENERATED! DO NOT EDIT! File to edit: ../11_mqtt.ipynb.

# %% auto 0
__all__ = ['default_topic', 'MQTTpublisher', 'VehStateSender']

# %% ../11_mqtt.ipynb 4
import paho.mqtt.client as mqtt
import socket

default_topic = 'topic name'

class MQTTpublisher(object):
    def __init__(self):
        mqtt_ip = '140.113.148.77'
        mqtt_port = 1883
        self.mqtt_topic = 'VehStatsAnchor'
        self.hostname = socket.gethostname()

        self.mqtt_client = mqtt.Client("arg_mqtt")
        self.mqtt_client.on_publish = self.on_publish
        self.mqtt_client.on_connect = self.on_connect
        self.mqtt_client.connect(mqtt_ip, mqtt_port)

    def create_payload(self):
        return str(self.hostname) + ': '

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with broker, result: " + mqtt.connack_string(rc))

    def on_publish(self, client, userdata, mid):
        print("payload published " + str(mid))

    def on_shutdown(self):
        self.mqtt_client.disconnect() 
        print("Shutting down...")

    def loop(self, timeout = .1):
        self.mqtt_client.loop(timeout)

# %% ../11_mqtt.ipynb 6
class VehStateSender(MQTTpublisher):
    def __init__(self):
        super(VehStateSender, self).__init__()
        mqtt_ip = '140.113.148.77'
        mqtt_port = 1883
        self.mqtt_topic = 'VehStatsAnchor'
        self.tempcpu = float()
        self.ip = str()
        self.current_time = None
        self.current = int()
        self.tempenv = float()

    def create_payload(self):
        data = VehStateType()
        now = time.localtime()
        r = requests.get(r'http://jsonip.com')
        self.ip= r.json()['ip']
        self.current_time = time.strftime("%Y-%m-%dT%H:%M:%S", now)
        data.setData(timestamp=self.current_time, mid=2, vid=2,globalx=0.0,globaly=0.0,ip=self.ip,powerlevel=self.current,tempcpu=self.tempcpu,tempenv=self.tempenv)
        return data.toString()
