-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiot_simulator.py.txt
More file actions
43 lines (33 loc) · 1.8 KB
/
Copy pathiot_simulator.py.txt
File metadata and controls
43 lines (33 loc) · 1.8 KB
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
import time
import requests
import random
# --- 1. Your Thingspeak Credentials (Networking Setup) ---
CHANNEL_ID = "YOUR_CHANNEL_ID" # <<< CRITICAL: REPLACE with your actual Channel ID number
WRITE_API_KEY = "YOUR_WRITE_API_KEY" # <<< CRITICAL: REPLACE with your actual Write API Key
# --- 2. The Main URL to send data to Thingspeak ---
BASE_URL = "https://api.thingspeak.com/update"
# --- 3. The Continuous Loop (The Embedded System's Heart) ---
print("--- Real-time IoT Simulation Started ---")
while True:
# A. SIMULATED SENSOR READ: Normal Temperature is 50, but with random noise
temp_raw = 50.0 + random.uniform(-0.5, 0.5)
# B. EMBEDDED LOGIC & ANOMALY INJECTION: Check if it's time to inject a spike
# Check if the current time is in the anomaly window (e.g., first 30 seconds of every 5 minutes)
if time.time() % 300 < 30:
# Inject the anomaly spike (Force temperature to 70 C)
temp_raw = 70.0 + random.uniform(-0.5, 0.5)
print("!!! ANOMALY INJECTED !!!")
# C. NETWORKING: Prepare the data link
# We are sending the temp_raw value to Field 1 of your Thingspeak channel
payload = {'api_key': WRITE_API_KEY, 'field1': temp_raw}
# D. SENDING DATA (The final Networking step)
try:
response = requests.get(BASE_URL, params=payload)
if response.status_code == 200:
print(f"[{time.strftime('%H:%M:%S')}] Data Sent: {temp_raw:.2f} C. Status: Success.")
else:
print(f"[{time.strftime('%H:%M:%S')}] Error sending data. Status code: {response.status_code}")
except Exception as e:
print(f"[{time.strftime('%H:%M:%S')}] Connection Error: {e}")
# E. WAIT TIME (The Embedded System pauses)
time.sleep(10) # Wait for 10 seconds before reading and sending again