Commit 324e44cc by rakesh.pv

1: send json as mqtt

2: reciver respone
3: save the respone in sqlite
parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (MQTT_JSON)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/MQTT_JSON.iml" filepath="$PROJECT_DIR$/.idea/MQTT_JSON.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
# importing libraries
import uvicorn
if __name__ == "__main__":
try:
uvicorn.run("scripts.core.services.app:app", reload=False)
except Exception as e:
print("Error-", e)
finally:
print("")
File added
import paho.mqtt.client as mqtt
MQTT_HOST = 'broker.mqttdashboard.com'
MQTT_PORT = 8000
MQTT_CLIENT_ID = 'clientId-v9ePzZBoVC'
TOPIC = 'home/#'
DATABASE_FILE = 'mqtt.db'
import json
import paho.mqtt.client as mqtt
import sqlite3
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("mqtt_test/json")
def on_message(client, userdata, msg):
data = json.loads(msg.payload.decode())
# Connect to the database
connection = sqlite3.connect('mqtt_data.db')
cursor = connection.cursor()
print("Database Connected")
# Create a table to store the data
cursor.execute("CREATE TABLE IF NOT EXISTS student_data (name VARCHAR(20) ,age VARCHAR(20),course VARCHAR(20))")
columns = ', '.join(data["data"][0].keys())
placeholders = ', '.join(['?'] * len(data["data"][0]))
for ele in range(len(data["data"])):
query = f'INSERT INTO student_data({columns}) VALUES({placeholders})'
cursor.execute(query, tuple(data["data"][ele].values()))
connection.commit()
print("Completed data inserting on DB")
connection.close()
broker_address = "192.168.0.220"
broker_port_no = 1883
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_address, broker_port_no, 60)
client.loop_forever()
# Importing libraries
import json
import paho.mqtt.client as mqtt
from fastapi import FastAPI
from scripts.core.config.mqtt_broker_connect_config import MQTT_HOST, MQTT_PORT
# Create object of FastAPI
app = FastAPI()
# Setting Root
@app.get("/")
async def root():
return {"STATUS : FASTAPI CONECTED"}
@app.post("/send_data_as_json")
async def send_json():
with open("scripts/temp/task3xl_json.json", 'r') as filename:
# Load json file
data = json.load(filename)
client = mqtt.Client()
client.connect(MQTT_HOST, MQTT_PORT)
client.publish("mqtt_test/json", json.dumps(data))
print("Data Published")
return {"STATUS": "SUCCESS"}
{
"data": [
{
"name":"rakesh",
"age": 23,
"course": "mca"
},
{
"name":"rajesh",
"age": 23,
"course": "mca"
},
{
"name":"logesh",
"age": 23,
"course": "mca"
},{
"name":"joshua",
"age": 23,
"course": "mca"
}
,
{
"name":"smith",
"age": 23,
"course": "mca"
}
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment