-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcameraIOT.py
More file actions
168 lines (139 loc) · 6.85 KB
/
cameraIOT.py
File metadata and controls
168 lines (139 loc) · 6.85 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import logging
from IOTdevice import IOTDevice
from data.config import *
import time
import threading
import hmac
logging.basicConfig(
filename='camera.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
class CameraIOT(IOTDevice):
"""Simulate camera IOT with support for multiple instances.
Each camera can be identified by a unique ID (e.g., 'cam1', 'cam2', 'outdoor_cam', etc.)
"""
def __init__(self, id, location="unknown"):
super().__init__(id, "Camera", location)
self.status = "live"
self.location = location
logging.info(f"Camera {id} initialized at location: {location}")
#Logs commands recieved by the camera device
def process_command(self, command, message=None):
"""Process received command"""
try:
# Split command and MAC
if "|" in command:
command, _ = command.rsplit("|", 1) # Discard the MAC
logging.info(f"Camera {self.id}: Processing command '{command}' with message: '{message}'")
mapper = {
'get_status': self.get_status,
'set_status': self.set_status,
'get_location': self.get_location,
'set_location': self.set_location,
'get_blockchain_data': self.get_blockchain_data
}
if command not in mapper:
logging.warning(f"Camera {self.id}: Unknown command '{command}'")
return f"ERROR: Unknown command '{command}'"
result = mapper[command](message) if message else mapper[command]()
#log action and create a new block
self.blockchain.new_interaction(sender = self.id, recipient = "Hub",
data = {"command": command, "message": message, "result": result})
proof = self.blockchain.proof_of_work(self.blockchain.last_block['proof'])
self.blockchain.new_block(proof)
logging.info(f"Command '{command}' executed successfully on Thermostat {self.id} with result: {result}")
return str(result)
except Exception as e:
logging.error(f"Camera {self.id}: Error processing command '{command}': {e}")
return f"ERROR: {str(e)}"
def get_status(self):
return f"Camera {self.id} status: {self.status}"
def set_status(self, state):
try:
self.status = state
logging.info(f"Camera {self.id} status set to {state}")
return f"Camera {self.id} set to {state}"
except Exception as e:
logging.error(f"Error setting status: {e}")
raise e
def get_location(self):
logging.info(f"Camera {self.id}: Retrieved location: {self.location}")
return f"Camera {self.id} location: {self.location}"
def set_location(self, new_location):
try:
old_location = self.location
self.location = new_location
logging.info(f"Camera {self.id}: Location changed from {old_location} to {new_location}")
return f"Camera {self.id} location set to {new_location}"
except Exception as e:
logging.error(f"Camera {self.id}: Error setting location: {e}")
raise e
def start_camera(camera_id, location, ip, port):
"""Start the camera with TCP communication."""
try:
camera = CameraIOT(camera_id, location)
camera.setEncryption(KEY, upperCaseAll=False, removeSpace=False)
camera.init_sockets(ip, port) # Initialize sockets first
# Start TCP server on a separate thread for blockchain handling
tcp_thread = threading.Thread(target=camera.start_TCP)
tcp_thread.daemon = True # Thread ends when the program exits
tcp_thread.start() # Start thread
print(f"Camera {camera.id}: TCP server started for blockchain handling.")
logging.info(f"Camera {camera_id}: Initialized at {location}, listening on {ip}:{port}")
while True:
try:
# Accept incoming TCP connections
conn, addr = camera.commSocket.accept()
encrypted_data = conn.recv(4096).decode("utf-8")
logging.info(f"Camera {camera_id}: Received encrypted message from {addr}")
if encrypted_data == "exit":
break
# Split message and MAC
if "|" in encrypted_data:
encrypted_message, mac = encrypted_data.rsplit("|", 1)
encrypted_message = encrypted_message.strip()
mac = mac.strip()
# Verify MAC
if not hmac.compare_digest(camera.generate_mac(encrypted_message), mac):
conn.sendall("ERROR: Invalid MAC".encode("utf-8"))
continue
# Decrypt the message after MAC verification
response = camera.decrypt(encrypted_message)
print(f"Camera {camera_id} received decrypted: {response}")
command, message = camera.parse_command(response)
output = camera.process_command(command, message)
# Encrypt the response
encrypted_output = camera.encrypt(output)
response_mac = camera.generate_mac(encrypted_output)
final_response = f"{encrypted_output} | {response_mac}"
logging.info(f"Camera {camera_id}: Sending encrypted response")
print(f"Camera {camera_id} sending encrypted response")
print() # Spacing for clean output
conn.sendall(final_response.encode("utf-8"))
else:
conn.sendall("ERROR: Invalid message format".encode("utf-8"))
conn.close()
except Exception as e:
error_msg = f"Error in Camera {camera_id}: {str(e)}"
logging.error(error_msg)
conn.sendall(error_msg.encode("utf-8"))
conn.close()
logging.info(f"Camera {camera_id}: Shutting down...")
except Exception as e:
logging.critical(f"Fatal error in Camera {camera_id}: {str(e)}")
if __name__ == "__main__":
import sys
if len(sys.argv) < 4:
logging.error("Camera initialization failed: Incorrect arguments provided.")
print("Usage: python cameraIOT.py <camera_id> <location> <port>")
print("Example: python cameraIOT.py cam1 'Front Door' 8081")
sys.exit(1)
try:
camera_id = sys.argv[1]
location = sys.argv[2]
port = int(sys.argv[3])
logging.info(f"Starting Camera with ID: {camera_id}, Location: {location}, Port: {port}")
start_camera(camera_id, location, CAMERA_IP, port)
except Exception as e:
logging.critical(f"Fatal error starting Camera: {str(e)}")