Пример #1
0
def handle_client(client, ip, port):
    MAX_BUFFER_SIZE = 69
    print('\n\nParsing data from ' + ip + ':' + port)
    input_from_client_bytes = client.readline()  # client.recv(MAX_BUFFER_SIZE)
    line = input_from_client_bytes
    print('data size:', len(input_from_client_bytes))
    while True:
        data = str(input_from_client_bytes)
        send_html = data.find('GET / HTTP/1.1')
        write_img = data.find('GET /logo.png')
        data_com = data.find('@data_com')
        get_credentials = data.find('@credentials:')
        output_state = data.find('@output_state:')
        end_data = data.find('@end')

        if send_html != -1:
            html_file = create_html()
            print('gotem')
            # client.sendall(response)
            client.send(b'%s' %
                        header['inicio'].replace('$html_file', html_file))
            print(data)
            break

        if write_img != -1:
            print('write logo')
            imOpen = open('/structure/logo.png')
            image = imOpen.read()
            imOpen.close()
            client.write(image)
            print(data)
            break

        if get_credentials != -1:
            print('Found credentials')
            c_data = data[get_credentials + len('@credentials:'):end_data]
            wifi.set_credentials(c_data)
            response = com_data.replace('$machine_data', '@credentials_saved')
            client.send(response)
            print(data)
            break

        if output_state != -1:
            print('Found output command')

            c_data = data[output_state + len('@output_state:'):end_data]
            command_json = {'command': 'output_state', 'update': c_data}
            machine_data.parse_data(command_json)

            esp_data = machine_data.get()
            gpio_output = esp_data['gpio']['output_state']
            json_response = {'output_state': gpio_output}
            response = com_data.replace('$machine_data', str(json_response))

            client.sendall(response)
            print(data)
            break
    clean_up(client)
    gc.collect()
    print(red + 'Connection ' + ip + ':' + port + ' ended\n' + normal + '}\n')
Пример #2
0
        break
    time.sleep(2)
    wc += 1
    if wc >= 5:
        break

if not cr:
    print("Camera not ready. Can't continue!")
else:
    file = open('/structure/logo.png', 'r')
    logo_img = file.read()
    file.close()

    wifi.start()
    sleep(1)
    wifi.set_credentials('1255,12551255')
    credentials_state, cred_ssid, cred_psw = wifi.get_credentials()

    while credentials_state == False:
        print('Getting credentials...')
        credentials_state, cred_ssid, cred_psw = wifi.get_credentials()
        sleep(1)
        pass

    sleep(1)

    wifi_connected = wifi.connect(cred_ssid, cred_psw)

    while wifi_connected == False:
        print("WIFI not ready. Wait...")
        sleep(2)
Пример #3
0
async def start(to):
    await asyncio.sleep(.18)
    print(color.yellow() + 'STARTING AP_SV' + color.normal())
    await asyncio.sleep(1)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    a = ('0.0.0.0', 80)
    s.bind(a)
    s.listen(2)  # queue at most 2 clients
    s.setblocking(False)
    while True:
        try:
            client, addr = s.accept()
            ip, port = str(addr[0]), str(addr[1])
            print('{')
            print(color.yellow() + '\tConnection from ' + ip + ':' + port)

            # Use:
            poller = uselect.poll()
            poller.register(client, uselect.POLLIN)
            res = poller.poll(200)  # time in milliseconds
            if not res:
                print('\toperation timed out')
            else:
                await asyncio.sleep(.1)
                client_data = client.recv(1024)
                client_data = client_data.decode('utf-8')
                req = client_data.split(' ')
                try:
                    print('\t', req[0], '##', req[1], "##", addr)
                    req = req[1].split('/')
                    print('req split', req)
                except OSError as e:
                    print('\t#failed to split req', e)

                if req[1] == 'app':
                    print('\taccesing', req[1])
                    html = hdr.get_index()
                    index_data = (b'%s' % html)
                    while True:
                        try:
                            while index_data:
                                sent = client.send(index_data)
                                index_data = index_data[sent:]
                            break
                        except OSError as e:
                            print(e)
                elif req[1] == 'gpio':
                    pin, value = req[2], req[3]
                    command_json = {
                        'command': 'output_state',
                        'data': {
                            'pin': pin,
                            'value': value
                        }
                    }
                    machine_data.parse_data(command_json)

                    esp_data = machine_data.get()
                    gpio_output = esp_data['gpio']['output_state']

                    json_response = json.dumps({
                        'command': 'output_state',
                        'output_state': gpio_output
                    })
                    json_header = hdr.get('json').replace(
                        '$len', str(len(json_response)))

                    client.send(b'%s' % json_header)
                    client.sendall(json_response.encode())
                elif req[1] == 'credentials':
                    ssid, psw = req[2], req[3]

                    wifi.set_credentials(ssid + ',' + psw)
                    json_response = json.dumps({
                        'command': 'credentials',
                        'state': 'saved'
                    })
                    json_header = hdr.get('json').replace(
                        '$len', str(len(json_response)))

                    client.send(b'%s' % json_header)
                    client.sendall(json_response.encode())
                elif req[1] == 'user_data':
                    user, id = req[2], req[3]
                    try:
                        id = id.replace('%20', ' ')
                    except:
                        e = ''
                    dev_id = machine_data.get_key('id')
                    machine_data.set(
                        'command', {
                            'command': 'popdev',
                            'dev_id': dev_id,
                            'user': machine_data.get_key('user')
                        })
                    machine_data.set('user', user)
                    machine_data.set('id', id)

                    json_response = json.dumps({
                        'command': 'user_data',
                        'state': 'saved'
                    })
                    json_header = hdr.get('json').replace(
                        '$len', str(len(json_response)))

                    client.send(b'%s' % json_header)
                    client.sendall(json_response.encode())
            client.close()
            print(color.red() + '\tConnection ' + ip + ':' + port + ' closed' +
                  color.normal() + '\n}')
        except OSError as e:
            if str(e) != '[Errno 11] EAGAIN':
                print(e)
        await asyncio.sleep(.1)