Jump to content

Welcome to Smart Home Forum by FIBARO

Dear Guest,

 

as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.

 

As a member you can:

  •     Start new topics and reply to others
  •     Follow topics and users to get email updates
  •     Get your own profile page and make new friends
  •     Send personal messages
  •     ... and learn a lot about our system!

 

Regards,

Smart Home Forum by FIBARO Team


Sending data to broker from HC3 through MQTT


Recommended Posts

I'm new to coding in HC3 and was wondering if anyone could help me understand how to publish to a know broker. I am trying to publish data to a broker. I managed to do this in python with the code below. Is there anyone here who could help me translate this to HC3?
 

import sys
import time
import numbers
from datetime import datetime, timezone, timedelta
import json
import paho.mqtt.client as mqtt
import random

mqtt_server = "mqtt.energydata.dk"
mqtt_port = 1883
mqtt_user = "Username"
mqtt_pass ="Password"

def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.connected_flag = True
        print("connected OK")
    else:
        print("Bad connection Returned code=",rc)


mqtt.Client.connected_flag = False

client = mqtt.Client("Flexhouse 2 client")
client.username_pw_set(mqtt_user, mqtt_pass)

client.on_connect=on_connect

client.loop_start()
print("Connecting to broker: ", mqtt_server)
client.connect(mqtt_server, mqtt_port, 60)

while not client.connected_flag:
    print("In wait loop")
    time.sleep(1)

print("in Main Loop")

while True:
  my_topic = "9F7J/M4/P2/DTU/PLDK/SYSLAB/studenproject_Q1_2021/SMART_HOME_CONSUM/gas_in_temperature"
  my_value = random.randint(0, 100)

  now = datetime.now(timezone.utc)
  epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) # use POSIX epoch
  my_timestamp = (now - epoch) // timedelta(microseconds=1) // 1000

  json_body = '{"value": ' + str(1.52) + ', "timestamp": ' + str(my_timestamp) + ' }'

  print(json_body)
  client.publish(my_topic, json_body)
  time.sleep(1)

client.loop_stop()  
client.disconnect()
#######################################################################################
 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...