diff --git a/.vs/MyCore/v15/Server/sqlite3/storage.ide-shm b/.vs/MyCore/v15/Server/sqlite3/storage.ide-shm index 707a508..2c9064c 100644 Binary files a/.vs/MyCore/v15/Server/sqlite3/storage.ide-shm and b/.vs/MyCore/v15/Server/sqlite3/storage.ide-shm differ diff --git a/.vs/MyCore/v15/Server/sqlite3/storage.ide-wal b/.vs/MyCore/v15/Server/sqlite3/storage.ide-wal index 0bfa039..f194bc4 100644 Binary files a/.vs/MyCore/v15/Server/sqlite3/storage.ide-wal and b/.vs/MyCore/v15/Server/sqlite3/storage.ide-wal differ diff --git a/MyCore/Controllers/IOTController.cs b/MyCore/Controllers/IOTController.cs index 05009b4..ed6fcc9 100644 --- a/MyCore/Controllers/IOTController.cs +++ b/MyCore/Controllers/IOTController.cs @@ -26,23 +26,47 @@ namespace MyCore.Controllers /// /// Retrieve all SmartPrinterMessage /// - [HttpGet] - public ActionResult> Get(int id) + [HttpGet("smartprinter/{idDevice}")] + public ActionResult> GetSmartPrinterMessages(int id) { - return _ioTDeviceService.Get(); + return _ioTDeviceService.GetSmartPrinterMessages(); } // POST: IOT/Create /// /// It's the method to post data from mqtt broker to Database (Thanks Rpi!) /// - [HttpPost("{idDevice}")] - public IActionResult PostToDB(int idDevice, [FromBody] SmartPrinterMessage[] content) + [HttpPost("smartprinter/{idDevice}")] + public IActionResult PostToDBPrinter(int idDevice, [FromBody] SmartPrinterMessage[] content) { - if(idDevice == 0) { + if(idDevice == 0) + { foreach (SmartPrinterMessage message in content) { - _ioTDeviceService.Create(message); + message.Type = "SmartPrinter"; + _ioTDeviceService.CreateSmartPrinterMessage(message); + } + + return StatusCode(201); + } + + return StatusCode(500); + } + + // POST: IOT/Create + /// + /// It's the method to post data from mqtt broker to Database (Thanks Rpi!) + /// + [HttpPost("smartgarden/{idDevice}")] + public IActionResult PostToDBSmartGarden(int idDevice, [FromBody] SmartGardenMessage[] content) + { + if (idDevice == 0) + { + + foreach (SmartGardenMessage message in content) + { + message.Type = "SmartGarden"; + _ioTDeviceService.CreateSmartGardenMessage(message); } return StatusCode(201); diff --git a/MyCore/Models/SmartGardenMessage.cs b/MyCore/Models/SmartGardenMessage.cs new file mode 100644 index 0000000..b393dde --- /dev/null +++ b/MyCore/Models/SmartGardenMessage.cs @@ -0,0 +1,37 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Models +{ + public class SmartGardenMessage + { + [BsonId] + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } + + [BsonElement("Type")] + public string Type { get; set; } + + [BsonElement("Time")] + public string Time { get; set; } + + [BsonElement("Temperature")] + public double Temperature { get; set; } + + [BsonElement("Pressure")] + public double Pressure { get; set; } + + [BsonElement("Humidity")] + public double Humidity { get; set; } + + [BsonElement("Water")] + public int Water { get; set; } + + [BsonElement("Light")] + public int Light { get; set; } + } +} diff --git a/MyCore/Models/SmartPrinterMessage.cs b/MyCore/Models/SmartPrinterMessage.cs index e4a4071..5ab02a1 100644 --- a/MyCore/Models/SmartPrinterMessage.cs +++ b/MyCore/Models/SmartPrinterMessage.cs @@ -13,6 +13,9 @@ namespace MyCore.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } + [BsonElement("Type")] + public string Type { get; set; } + [BsonElement("Time")] public string Time { get; set; } diff --git a/MyCore/Services/IoTDeviceService.cs b/MyCore/Services/IoTDeviceService.cs index 28ab946..0d6dffe 100644 --- a/MyCore/Services/IoTDeviceService.cs +++ b/MyCore/Services/IoTDeviceService.cs @@ -13,30 +13,48 @@ namespace MyCore.Services public class IoTDeviceService { private readonly IMongoCollection _SmartPrinterMessages; + private readonly IMongoCollection _SmartGardenMessages; public IoTDeviceService(IConfiguration config) { var client = new MongoClient(config.GetConnectionString("MyCoreDb")); var database = client.GetDatabase("MyCoreDb"); _SmartPrinterMessages = database.GetCollection ("IoTDevices"); + _SmartGardenMessages = database.GetCollection("IoTDevices"); } - public List Get() + public List GetSmartPrinterMessages() { return _SmartPrinterMessages.Find(m => true).ToList(); } - public SmartPrinterMessage Get(string id) + public SmartPrinterMessage GetSmartPrinterMessage(string id) { return _SmartPrinterMessages.Find(m => m.Id == id).FirstOrDefault(); } - public SmartPrinterMessage Create(SmartPrinterMessage message) + public SmartPrinterMessage CreateSmartPrinterMessage(SmartPrinterMessage message) { _SmartPrinterMessages.InsertOne(message); return message; } + public List GetSmartGardenMessages() + { + return _SmartGardenMessages.Find(m => true).ToList(); + } + + public SmartGardenMessage GetSmartGardenMessage(string id) + { + return _SmartGardenMessages.Find(m => m.Id == id).FirstOrDefault(); + } + + public SmartGardenMessage CreateSmartGardenMessage(SmartGardenMessage message) + { + _SmartGardenMessages.InsertOne(message); + return message; + } + /*public void Update(string id, Book bookIn) { _books.ReplaceOne(book => book.Id == id, bookIn); diff --git a/MyCore/bin/Debug/netcoreapp2.1/MyCore.xml b/MyCore/bin/Debug/netcoreapp2.1/MyCore.xml index 5e34a12..4399122 100644 --- a/MyCore/bin/Debug/netcoreapp2.1/MyCore.xml +++ b/MyCore/bin/Debug/netcoreapp2.1/MyCore.xml @@ -4,12 +4,17 @@ MyCore - + Retrieve all SmartPrinterMessage - + + + It's the method to post data from mqtt broker to Database (Thanks Rpi!) + + + It's the method to post data from mqtt broker to Database (Thanks Rpi!) diff --git a/MyCore/obj/Debug/netcoreapp2.1/MyCore.xml b/MyCore/obj/Debug/netcoreapp2.1/MyCore.xml index 5e34a12..4399122 100644 --- a/MyCore/obj/Debug/netcoreapp2.1/MyCore.xml +++ b/MyCore/obj/Debug/netcoreapp2.1/MyCore.xml @@ -4,12 +4,17 @@ MyCore - + Retrieve all SmartPrinterMessage - + + + It's the method to post data from mqtt broker to Database (Thanks Rpi!) + + + It's the method to post data from mqtt broker to Database (Thanks Rpi!) diff --git a/RPI Code/Mqtt_To_Http/mqtt_to_http.py b/RPI Code/Mqtt_To_Http/mqtt_to_http.py index c0af5d9..d9488a0 100644 --- a/RPI Code/Mqtt_To_Http/mqtt_to_http.py +++ b/RPI Code/Mqtt_To_Http/mqtt_to_http.py @@ -12,11 +12,13 @@ broker="localhost" #password="lEyZb90q49Rf" # defining the api-endpoint -API_ENDPOINT = 'http://192.168.0.17:3000/api/iot/0' +API_ENDPOINT_SmartPrinter = 'http://192.168.0.17:3000/api/iot/smartprinter/' +API_ENDPOINT_SmartGarden = 'http://192.168.0.17:3000/api/iot/smartgarden/' delay = 5000 bufferJsonPrinter = [] +bufferJsonSmartGarden = [] headersVar = {} def getToken(): @@ -34,6 +36,7 @@ def getToken(): def on_message(mosq, obj, msg): print("Topic = " + msg.topic) global bufferJsonPrinter + global bufferJsonSmartGarden global headers if msg.topic == '3DPrinterSensors' : @@ -42,7 +45,7 @@ def on_message(mosq, obj, msg): # Add increment and test = if data length >= 10, push to DB via Http # Add Verification on token.. if status code == 401 forbidden then get token and call again the service - validData = False; + validDataPrinter = False; try : msgPayload = '{"Time":"'+ str(datetime.datetime.now()) + '",'+ msgPayload[1:] @@ -51,21 +54,18 @@ def on_message(mosq, obj, msg): #item_dict = json.loads(bufferJsonPrinter) #print("BufferJsonPrinter= " + json.dumps(bufferJsonPrinter)) print("3DPrinterMessage = NumberOfElement already collected : " + str(len(bufferJsonPrinter))) - validData = True; + validDataPrinter = True; except Exception as e: print(e) print("3DPrinterMessage = Got an error in parsing message") - if validData and len(bufferJsonPrinter) == 10: + if validDataPrinter and len(bufferJsonPrinter) == 10: print("I'm in !") # Request #jsonData1 = json.dumps([{'Time': '14/04/19', 'Temperature': 26.5, 'Pressure': 1004.3, 'Smoke': 100},{'Time': '14/04/19', 'Temperature': 26.5, 'Pressure': 1004.3, 'Smoke': 100}]) try: - jsonData = bufferJsonPrinter - #print('jsonData1 : ' + jsonData1) - #print('jsonData : ' + str(jsonData).replace("'","")) - printerRequest = requests.post(API_ENDPOINT,data=str(jsonData).replace("'",""), headers=headersVar) + printerRequest = requests.post(API_ENDPOINT_SmartPrinter + "0",data=str(bufferJsonPrinter).replace("'",""), headers=headersVar) except Exception as e: print(e) print("3DPrinterMessage = error in post request") @@ -73,14 +73,13 @@ def on_message(mosq, obj, msg): while printerRequest.status_code == 401: getToken() - time.sleep(20) + time.sleep(30) print("3DPrinterMessage = Forbidden error : Trying to send again the request with new token") - #jsonData = json.dumps([{'Time': '14/04/19', 'Temperature': 26.5, 'Pressure': 1004.3, 'Smoke': 100}]) - printerRequest = requests.post(API_ENDPOINT,data=bufferJsonPrinter["result"], headers=headersVar) + printerRequest = requests.post(API_ENDPOINT_SmartPrinter + "0",data=str(bufferJsonPrinter).replace("'",""), headers=headersVar) if printerRequest.status_code == 404: print("3DPrinterMessage = The server is unreachable (404)") - if printerRequest.status_code == 400: + elif printerRequest.status_code == 400: print("3DPrinterMessage = Bad request (400)") elif printerRequest.status_code == 200 or printerRequest.status_code == 201: print("3DPrinterMessage = I sent the infos ! Everything is ok :) !") @@ -93,21 +92,50 @@ def on_message(mosq, obj, msg): #data = r.json() elif msg.topic == 'SmartGarden' : - print(str(msg.payload, "utf-8")) + msgPayload = str(msg.payload, "utf-8") + print("SmartGardenMessage = PayLoad : " + msgPayload) - # data to be sent to api - data = {'api_dev_key':'', - 'api_option':'paste', - 'api_paste_code':source_code, - 'api_paste_format':'python'} - + # Add increment and test = if data length >= 10, push to DB via Http + # Add Verification on token.. if status code == 401 forbidden then get token and call again the service + validDataSmartGarden = False; + + try : + msgPayload = '{"Time":"'+ str(datetime.datetime.now()) + '",'+ msgPayload[1:] + bufferJsonSmartGarden.append(msgPayload) + print("SmartGardenMessage = NumberOfElement already collected : " + str(len(bufferJsonSmartGarden))) + validDataSmartGarden = True; + except Exception as e: + print(e) + print("SmartGardenMessage = Got an error in parsing message") - # sending post request and saving response as response object - r = requests.post(url = API_ENDPOINT, data = data) - - # extracting response text - pastebin_url = r.text - print("The pastebin URL is:%s"%pastebin_url) + if validDataSmartGarden and len(bufferJsonSmartGarden) == 10: + print("I'm in !") + + try: + print(headersVar) + print("Request = " + str(bufferJsonSmartGarden).replace("'","")) + smartGardenRequest = requests.post(API_ENDPOINT_SmartGarden + "0",data=str(bufferJsonSmartGarden).replace("'",""), headers=headersVar) + except Exception as e: + print(e) + print("SmartGardenMessage = error in post request") + + while smartGardenRequest.status_code == 401: + getToken() + time.sleep(30) + print("SmartGardenMessage = Forbidden error : Trying to send again the request with new token") + smartGardenRequest = requests.post(API_ENDPOINT_SmartGarden + "0",data=str(bufferJsonSmartGarden).replace("'",""), headers=headersVar) + + if smartGardenRequest.status_code == 404: + print("SmartGardenMessage = The server is unreachable (404)") + elif smartGardenRequest.status_code == 400: + print("SmartGardenMessage = Bad request (400)") + elif smartGardenRequest.status_code == 200 or smartGardenRequest.status_code == 201: + print("SmartGardenMessage = I sent the infos ! Everything is ok :) !") + bufferJsonSmartGarden = [] + else: + print(str(smartGardenRequest.status_code)) + print("SmartGardenMessage = Unexpected Error : status code") + else: print("Unknown topic") @@ -116,15 +144,17 @@ def on_message(mosq, obj, msg): mqttc = mqtt.Client('Mqtt_To_Http_Interceptor') #mqttc.username_pw_set(username, password) +print("connecting to broker : ",broker) mqttc.connect(broker, 1883) TOKEN_URL = 'http://192.168.0.17:3000/api/token?username=Thomas&password=MonsieurMagic' +print("trying to retrieve a token from server") getToken() mqttc.on_message=on_message ##### -print("connecting to broker ",broker) + mqttc.loop_start() #start loop to process received messages print("subscribing ") mqttc.subscribe("SmartGarden")#subscribe diff --git a/RPI Code/SmartGarden/allInOne.py b/RPI Code/SmartGarden/allInOne.py index b0f1786..744608f 100644 --- a/RPI Code/SmartGarden/allInOne.py +++ b/RPI Code/SmartGarden/allInOne.py @@ -240,8 +240,8 @@ try: #print ("Temperature : ", temperature, "C") #print ("Pressure : ", pressure, "hPa") #print ("Humidity : ", humidity, "%") - # Pause for ten seconds. - time.sleep(10) + # Pause for one minute. + time.sleep(60) except KeyboardInterrupt: # here you put any code you want to run before the program