1
|
|
|
|
2
|
|
|
# Copyright 2019 Virantha N. Ekanayake |
3
|
|
|
# |
4
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); |
5
|
|
|
# you may not use this file except in compliance with the License. |
6
|
|
|
# You may obtain a copy of the License at |
7
|
|
|
# |
8
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0 |
9
|
|
|
# |
10
|
|
|
# Unless required by applicable law or agreed to in writing, software |
11
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, |
12
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13
|
|
|
# See the License for the specific language governing permissions and |
14
|
|
|
# limitations under the License. |
15
|
|
|
"""Experimental socket updates of devices and hubs""" |
16
|
|
|
|
17
|
|
|
import logging |
18
|
|
|
import pprint |
19
|
|
|
from curio import run, spawn, sleep, Queue, tcp_server |
20
|
|
|
|
21
|
|
|
#async def socket_server(web_out_queue, address): |
22
|
|
|
#sock = socket(AF_INET, SOCK_STREAM) |
23
|
|
|
#sock.setsockopt(SOL_SOCKET, SO_REUSEADDR,1) |
24
|
|
|
#sock.bind(address) |
25
|
|
|
#sock.listen(5) |
26
|
|
|
#print(f'Server listening at {address}') |
27
|
|
|
#async with sock: |
28
|
|
|
#while True: |
29
|
|
|
#client, addr = await sock.accept() |
30
|
|
|
#wc = WebClient(client, addr, web_out_queue) |
31
|
|
|
#await spawn(wc.run, daemon=True) |
32
|
|
|
|
33
|
|
|
async def bricknil_socket_server(web_out_queue, address): |
34
|
|
|
async def web_client_connected(client, addr): |
35
|
|
|
print('connection from', addr) |
36
|
|
|
wc = WebClient(client, addr, web_out_queue) |
37
|
|
|
await wc.run() |
38
|
|
|
|
39
|
|
|
task = await spawn(tcp_server, '', 25000, web_client_connected, daemon=True) |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
class WebClient: |
43
|
|
|
|
44
|
|
|
def __init__(self, client, addr, in_queue): |
45
|
|
|
assert in_queue is not None |
46
|
|
|
self.in_queue = in_queue |
47
|
|
|
self.client = client |
48
|
|
|
self.addr = addr |
49
|
|
|
print(f'Web client {client} connected from {addr}') |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
async def run(self): |
53
|
|
|
|
54
|
|
|
async with self.client: |
55
|
|
|
while True: |
56
|
|
|
msg = await self.in_queue.get() |
57
|
|
|
#print(f'Webclient queue got: {msg}') |
58
|
|
|
await self.in_queue.task_done() |
59
|
|
|
await self.client.sendall(msg) |
60
|
|
|
print('connection closed') |
61
|
|
|
|