Add telemetry database insertion
This commit is contained in:
44
api-customer/src/services/mongo_service.py
Normal file
44
api-customer/src/services/mongo_service.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import json
|
||||
|
||||
from pymongo import MongoClient
|
||||
from pymongo.synchronous.database import Database
|
||||
|
||||
|
||||
class MongoService:
|
||||
|
||||
_client : MongoClient
|
||||
_db : Database
|
||||
|
||||
def __init__(self, uri : str, database : str):
|
||||
self._client = MongoClient(uri)
|
||||
self._db = self._client[database]
|
||||
|
||||
|
||||
def insert(self, collection : str, data : object):
|
||||
collection = self._db[collection]
|
||||
payload = self._to_document(data)
|
||||
result = collection.insert_one(payload)
|
||||
return result.inserted_id
|
||||
|
||||
def find(self, collection: str, field: str, value):
|
||||
col = self._db[collection]
|
||||
return list(col.find({field: value}))
|
||||
|
||||
def _to_document(self, obj):
|
||||
if obj is None or isinstance(obj, (str, int, float, bool)):
|
||||
return obj
|
||||
|
||||
if isinstance(obj, list):
|
||||
return [self._to_document(i) for i in obj]
|
||||
|
||||
if isinstance(obj, dict):
|
||||
return {k: self._to_document(v) for k, v in obj.items()}
|
||||
|
||||
if hasattr(obj, "__dict__"):
|
||||
return {
|
||||
k: self._to_document(v)
|
||||
for k, v in vars(obj).items()
|
||||
if not k.startswith("_")
|
||||
}
|
||||
|
||||
return str(obj)
|
||||
@@ -41,19 +41,18 @@ class MQTTService:
|
||||
self._connected = False
|
||||
|
||||
def connect(self):
|
||||
if self._connected: return
|
||||
|
||||
print(f"Connecting to {self.address}...")
|
||||
self.client.connect(self.address, self.port)
|
||||
self.client.loop_start()
|
||||
timeout = 5
|
||||
start = time.time()
|
||||
while not self._connected and time.time() - start < timeout:
|
||||
time.sleep(0.1)
|
||||
if not self._connected:
|
||||
print(f"Connecting to {self.address}...")
|
||||
self.client.connect(self.address, self.port)
|
||||
self.client.loop_start()
|
||||
timeout = 5
|
||||
start = time.time()
|
||||
while not self._connected and time.time() - start < timeout:
|
||||
time.sleep(0.1)
|
||||
if not self._connected:
|
||||
raise ConnectionError(f"Cannot connect to MQTT broker at {self.address}:{self.port}")
|
||||
print(f"Successfully connected to {self.address}")
|
||||
else :
|
||||
print(f"Already connected to {self.address}...")
|
||||
raise ConnectionError(f"Cannot connect to MQTT broker at {self.address}:{self.port}")
|
||||
print(f"Successfully connected to {self.address}")
|
||||
|
||||
def disconnect(self):
|
||||
if self._connected:
|
||||
|
||||
Reference in New Issue
Block a user