forked from git-connected/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththermostat.py
97 lines (74 loc) · 2.57 KB
/
thermostat.py
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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
import socket
import sys
import time
from colors import bcolors
ADDR = ''
PORT = 10000
# Create a UDP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (ADDR, PORT)
device_id = sys.argv[1]
if not device_id:
sys.exit('The device id must be specified.')
print('Bringing up device {}'.format(device_id))
# return message received
def send_command(sock, message, log=True):
sock.sendto(message, server_address)
# Receive response
response, _ = sock.recvfrom(4096)
return response
def make_message(device_id, action, data=''):
if data:
return '{{ "device" : "{}", "action":"{}", "data" : "{}" }}'.format(
device_id, action, data)
else:
return '{{ "device" : "{}", "action":"{}" }}'.format(device_id, action)
def run_action(action):
message = make_message(device_id, action)
if not message:
return
print('Sending data: {}'.format(message))
event_response = send_command(client_sock, message.encode())
print('Response {}'.format(event_response.decode("utf-8")))
def main():
try:
random.seed()
run_action('detach')
run_action('attach')
h = 35.0
t = 20.0
while True:
h += random.uniform(-1, 1)
t += random.uniform(-1, 1)
temperature_f = t * 9.0/5 + 32
humidity = "{:.3f}".format(h)
temperature = "{:.3f}".format(temperature_f)
sys.stdout.write(
'\r>> ' + bcolors.CGREEN + bcolors.CBOLD +
'Temp: {} F, Hum: {}%'.format(temperature, humidity) +
bcolors.ENDC + ' <<')
sys.stdout.flush()
message = make_message(
device_id, 'event', 'temperature={}, humidity={}'.format(t, h)
).encode()
send_command(client_sock, message, False)
time.sleep(2)
finally:
print('Closing socket')
client_sock.close()
if __name__ == "__main__":
main()