Skip to content

Hailey #4

Merged
merged 3 commits into from
Jun 23, 2026
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/4005CMD_Labs.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Conflict.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
hieee
hyyyy
hie
Im a conflict
Binary file modified README.md
Binary file not shown.
33 changes: 33 additions & 0 deletions Week4_Lab1/binary_lab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import base64
import json
def main():
# 1. Simulate an image file (Bytes)
# In Python, b"..." means bytes, not string.
fake_image_data = b"This is not really an image, but it is binary data."
print(f"Original Binary: {fake_image_data}")

# 2. Encode to Base64 (still bytes)
b64_bytes = base64.b64encode(fake_image_data)
# 3. Decode to UTF-8 String (Critical Step for JSON)
# JSON cannot hold bytes, so we turn the base64 bytes into a normal string.
# This is exactly what you do in the Week 7 Tutorial.
image_string = b64_bytes.decode('utf-8')
print(f"\nBase64 String (Safe for JSON): {image_string}")
# 4. Pack into JSON
payload = {
"filename": "camera_capture.jpg",
"image_data": image_string
}
json_payload = json.dumps(payload)
print(f"\nJSON Payload ready for MQTT: {json_payload}")
# --- SIMULATE RECEIVING THE MESSAGE ---
# 5. Unpack JSON
received = json.loads(json_payload)
received_str = received["image_data"]
# 6. Decode back to Binary
# We ignore the filename for now, just get the data back.
original_data = base64.b64decode(received_str)
print(f"\nRecovered Binary: {original_data}")

if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions Week4_Lab1/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"broker": "broker.hivemq.com",
"port": 1883,
"topic": "home/livingroom"
}
42 changes: 42 additions & 0 deletions Week4_Lab1/file_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import json
import os

FILENAME = "config.json"


def save_config(data: dict):
"""Writes a dictionary to a file as JSON."""
with open(FILENAME, "w") as f:
# json.dump (no 's') writes directly to file
json.dump(data, f, indent=4)
print("Config saved.")


def load_config() -> dict:
"""Reads JSON from a file and returns a dictionary."""
if not os.path.exists(FILENAME):
print("No config file found. Returning empty dict.")
return {}

with open(FILENAME, "r") as f:
return json.load(f)


def main():
# Create some dummy settings
my_settings = {
"broker": "broker.hivemq.com",
"port": 1883,
"topic": "home/livingroom"
}

# Save them
save_config(my_settings)

# Load them back
loaded_settings = load_config()
print(f"Loaded broker: {loaded_settings['broker']}")


if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions Week4_Lab1/json_basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import json


def main():

# 1. A Python Dictionary (exists in memory)

sensor_data = {
"id": "sensor_01",
"temp": 22.5,
"active": True
}

print(f"Original Type: {type(sensor_data)}")

# 2. Serialize (Freeze it into a string)
# indent=4 makes it pretty to read
json_string = json.dumps(sensor_data, indent=4)

print(f"Serialized Type: {type(json_string)}")
print("The String looks like this:")
print(json_string)

# 3. Deserialize (Thaw it back into a dictionary)
# This is what you do when you receive an MQTT message
received_data = json.loads(json_string)
print(f"Back to Type: {type(received_data)}")
print(f"Temperature is: {received_data['temp']}")


if __name__ == "__main__":
main()
33 changes: 33 additions & 0 deletions Week4_Lab1/safe parsing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import json


def process_message(json_msg: str):
data = json.loads(json_msg)

# SAFE WAY: .get() allows us to provide a default value (e.g., 0.0)
# If "temp" is missing, it uses 0.0 instead of crashing.
temperature = data.get("temp", 0.0)

# UNSAFE WAY: Direct access
# Uncommenting the next line would crash the script
# humidity = data["humidity"]

print(f"Processing... Temp: {temperature}")

def main():
# A perfect message
good_msg = '{"id": "s1", "temp": 23.5, "humidity": 60}'
print("--- Test 1 (Good Message) ---")
process_message(good_msg)

# A broken message (missing temp)
bad_msg = '{"id": "s1", "error": "battery_low"}'
print("\n--- Test 2 (Bad Message) ---")
process_message(bad_msg)


if __name__ == "__main__":
main()



21 changes: 21 additions & 0 deletions Week5_lab1/create_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import sqlite3
def create_table():
conn = sqlite3.connect('smart_home.db')
cursor = conn.cursor()
# SQL Command to create a table
# We use triple quotes """ for multi-line strings
sql_command = """
CREATE TABLE IF NOT EXISTS sensors (
sensor_id INTEGER PRIMARY KEY,
location TEXT NOT NULL,
type TEXT NOT NULL,
install_date TEXT
);
"""
cursor.execute(sql_command)
print("Table 'sensors' created successfully.")
# Commit saves the changes (Crucial!)
conn.commit()
conn.close()
if __name__ == "__main__":
create_table()
12 changes: 12 additions & 0 deletions Week5_lab1/db_setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import sqlite3
def create_database():
print("Connecting to database...")
# This creates the file 'smart_home.db' if it doesn't exist
conn = sqlite3.connect('smart_home.db')
# Create the cursor
cursor = conn.cursor()
print("Database connection successful.")
# Always close the connection when done
conn.close()
if __name__ == "__main__":
create_database()
19 changes: 19 additions & 0 deletions Week5_lab1/insert_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import sqlite3
def add_sensor(location, sensor_type, date):
conn = sqlite3.connect('smart_home.db')
cursor = conn.cursor()

# The '?' are placeholders. The library safely inserts the variables later.
sql = "INSERT INTO sensors (location, type, install_date) VALUES (?, ?, ?)"
# The data must be a tuple
data = (location, sensor_type, date)
cursor.execute(sql, data)
conn.commit()
print(f"Added sensor: {sensor_type} in {location}")
conn.close()

if __name__ == "__main__":
add_sensor("Living Room", "Temperature", "2023-01-15")
add_sensor("Kitchen", "Motion", "2023-02-20")
add_sensor("Bedroom", "Light", "2023-03-05")

30 changes: 30 additions & 0 deletions Week5_lab1/modify_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import sqlite3
def move_sensor(sensor_type, new_location):
conn = sqlite3.connect('smart_home.db')
cursor = conn.cursor()

# UPDATE syntax
sql = "UPDATE sensors SET location = ? WHERE type = ?"
cursor.execute(sql, (new_location, sensor_type))
conn.commit()
print(f"Moved all {sensor_type} sensors to {new_location}.")
conn.close()


def remove_sensor(sensor_id):
conn = sqlite3.connect('smart_home.db')
cursor = conn.cursor()

# DELETE syntax
sql = "DELETE FROM sensors WHERE sensor_id = ?"
cursor.execute(sql, (sensor_id,)) # Note the comma for a single-item tuple!
conn.commit()
print(f"Deleted sensor ID {sensor_id}.")
conn.close()


if __name__ == "__main__":
move_sensor("Motion", "Hallway")
remove_sensor(1) # Deletes the Living Room Temperature sensor


18 changes: 18 additions & 0 deletions Week5_lab1/read_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import sqlite3
def get_all_sensors():
conn = sqlite3.connect('smart_home.db')
cursor = conn.cursor()
# SELECT * means "Select All Columns"
cursor.execute("SELECT * FROM sensors")

# fetchall() grabs every row found by the query
rows = cursor.fetchall()
print("--- Current Sensors ---")
for row in rows:
# 'row' is a tuple: (1, 'Living Room', 'Temperature', '2023-01-15')
print(f"ID: {row[0]} | Loc: {row[1]} | Type: {row[2]}")

conn.close()

if __name__ == "__main__":
get_all_sensors()
Binary file added Week5_lab1/smart_home.db
Binary file not shown.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 5 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"broker": "broker.hivemq.com",
"port": 1883,
"topic": "home/livingroom"
}
3 changes: 3 additions & 0 deletions import sys.bib
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import sys
print(sys.argv)