-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
90 lines (82 loc) · 2.59 KB
/
Copy pathexample.py
File metadata and controls
90 lines (82 loc) · 2.59 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
# This is the main.py micropython program that will run and run while the pico W has power.
# It connects to the internet, collects data, connects to my own private mqtt broker and sends data to it.
# Needs to be tested before I publish it for public consumption.
from helperCode import GetTemperature, connect_to_wifi, WifiServer, to_json, collect_sensor_data
import usocket
import socket
from time import time, sleep
import network
import time
from simple import MQTTClient
import machine
from picozero import pico_temp_sensor
from machine import Pin
import micropython
import ustruct as struct
import json
import random
import socket
csv_data = collect_sensor_data()
def write_to_csv(csv_data, filename="PW_1.csv"):
# Write the CSV data to a file
with open(filename, "a") as file:
file.write(csv_data)
Self_Name = 'PW_1'
ssidAP = 'CuthbertWifi' #Enter the router name
passwordAP = '999' # Enter the router password
local_IP = '192.168.1.1'
gateway = '192.168.1.1'
subnet = '255.255.255.0'
dns = '8.8.8.8'
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
adcpin = 4
sensor = machine.ADC(adcpin)
sock = usocket
SSID = ''
PASSWORD = ''
SERVER_HOSTNAME = ""
USER = "Cuthbert"
#PASSWORD = ''
wlan = network.WLAN(network.STA_IF)
TOPIC = "test_data"
mqtt = MQTTClient
sending = broker_address
BROKER = "192.168.1.17"
PORT = 1883 # Topic to publish to
CLIENT_ID = "Cuthbert"
Temperature = GetTemperature()
json_string = '{"Name": "device_id", "temp":"27"}'
data1 = json.loads(json_string)
ip = connect_to_wifi()
gateway1 = WifiServer('CuthbertWifi', '999')
client = MQTTClient(CLIENT_ID, BROKER)
start_time = time.time()
duration = 4000
try:
print("Connecting to MQTT broker...")
client.connect()
print("Connected to MQTT broker.")
while (time.time() - start_time) < duration:
Temperature = GetTemperature()
json_result = to_json(Temperature)
print (json_result)
client.publish(TOPIC, json_result)
time.sleep(10)
Temperature = GetTemperature()
json_result = to_json(Temperature)
print(json_result)
client.publish(TOPIC, json_result)
time.sleep(10)
Temperature = GetTemperature()
json_result = to_json(Temperature)
print (json_result)
client.publish(TOPIC, json_result)
Temperature = GetTemperature()
json_result = to_json(Temperature)
print (json_result)
client.publish(TOPIC, json_result)
except Exception as e:
print("An error occurred:", e)
client.disconnect()
wlan.disconnect()