1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
#include <iostream> #include <vector> #include <string> #include <cstdlib> #include <ctime> class IoTDevice { public: IoTDevice(const std::string& id) : deviceId(id) {} std::string getId() const { return deviceId; } virtual double getData() const = 0; // Pure virtual function protected: std::string deviceId; }; class TemperatureSensor : public IoTDevice { public: TemperatureSensor(const std::string& id) : IoTDevice(id) {} double getData() const override { // Simulate temperature data between -10 and 35 degrees Celsius return -10 + static_cast<double>(rand()) / RAND_MAX * 45; } }; class HumiditySensor : public IoTDevice { public: HumiditySensor(const std::string& id) : IoTDevice(id) {} double getData() const override { // Simulate humidity data between 0 and 100 percent return static_cast<double>(rand()) / RAND_MAX * 100; } }; class IoTServer { public: void addDevice(IoTDevice* device) { devices.push_back(device); } void collectData() { std::cout << "Collecting data from IoT devices:\n"; for (const auto& device : devices) { std::cout << "Device ID: " << device->getId() << ", Data: " << device->getData() << "\n"; } } private: std::vector<IoTDevice*> devices; }; int main() { srand(static_cast<unsigned int>(time(0))); IoTServer server; // Create and add devices to the server TemperatureSensor tempSensor1("Temp01"); TemperatureSensor tempSensor2("Temp02"); HumiditySensor humiditySensor1("Humidity01"); server.addDevice(&tempSensor1); server.addDevice(&tempSensor2); server.addDevice(&humiditySensor1); // Collect and display data server.collectData(); return 0; } |
Explanation
- IoTDevice Class:
- A base class representing a generic IoT device with a
deviceId
AdvertisementgetData()
, which must be implemented by derived classes.
Advertisement - A base class representing a generic IoT device with a
- TemperatureSensor Class:
- Inherits from
IoTDevice
. ImplementsgetData()
to simulate temperature readings between -10 and 35 degrees Celsius.
- Inherits from
- HumiditySensor Class:
- Inherits from
IoTDevice
. ImplementsgetData()
to simulate humidity readings between 0 and 100 percent.
- Inherits from
- IoTServer Class:
- Manages a collection of
IoTDevice
pointers. TheaddDevice()
function adds a device to the collection, andcollectData()
Advertisement
- Manages a collection of
- main Function:
- Seeds the random number generator.
- Creates instances of
TemperatureSensor
andHumiditySensor
. - Adds these devices to the
IoTServer
. - Collects and displays data from all devices.