forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathledlight.py
More file actions
89 lines (70 loc) · 2.58 KB
/
ledlight.py
File metadata and controls
89 lines (70 loc) · 2.58 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
# 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 socket
import sys
from colors import bcolors
ADDR = ''
PORT = 10000
BUFF_SIZE = 4096
device_id = None
server_address = (ADDR, PORT)
# Create a UDP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def send_command(sock, message):
sock.sendto(message.encode(), server_address)
# Receive response
print('Waiting for response.....')
response = sock.recv(BUFF_SIZE)
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(device_id, action, data=''):
message = make_message(device_id, action, data)
if not message:
return
print('Send message: {}'.format(message))
event_response = send_command(client_sock, message).decode('utf-8')
print('Received response: {}'.format(event_response))
def main():
device_id = sys.argv[1]
if not device_id:
sys.exit('The device id must be specified.')
print('Bringing up device {}'.format(device_id))
try:
run_action(device_id, 'detach')
run_action(device_id, 'attach')
run_action(device_id, 'event', 'LED is online')
run_action(device_id, 'subscribe')
while True:
response = client_sock.recv(BUFF_SIZE)
message = response.decode('utf-8')
if message.find("ON") != -1:
sys.stdout.write(
'\r>> ' + bcolors.CGREEN + bcolors.CBLINK +
" LED is ON " + bcolors.ENDC + ' <<')
sys.stdout.flush()
elif message.find("OFF") != -1:
sys.stdout.write(
'\r >>' + bcolors.CRED + bcolors.BOLD +
" LED is OFF " + bcolors.ENDC + ' <<')
sys.stdout.flush()
finally:
print('closing socket')
client_sock.close()
if __name__ == '__main__':
main()