Ejemplo n.º 1
0
def port1(client, req):
    print('port1 req:', req)
    req = req.split('/')
    if req[1] == 'app':  # Must have /apikey/<REQ>
        index_page = create_html()
        html = hdr['html'].replace('$html', index_page)
        client.send(b'%s' % html)
        sleep(.1)
        clean_up(client)
    elif req[1] == 'logo.png':
        client.send(logo_img)
        sleep(.1)
        clean_up(client)
    elif req[1] == ('gpio'):
        pin, value = req[2], req[3]

        command_json = {'command': 'output_state', 'data': pin + '=' + 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['json'].replace('$len', str(len(json_response)))

        client.send(b'%s' % json_header)
        client.sendall(json_response.encode())
        clean_up(client)
    else:
        client.send(b'%s' % hdr['err'])
        clean_up(client)
Ejemplo n.º 2
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')
Ejemplo n.º 3
0
def start_com(address):
    json_data = machine_data.create()
    while True:
        #print(color.blue()+'{')

        client_socket = socket.socket()
        client_socket.setblocking(0)
        try:
            #print('\tConnect to',address)
            client_socket.connect(address)
        except OSError as error:
            if error.args[0] not in [uerrno.EINPROGRESS, uerrno.ETIMEDOUT]:
                print(color.red() + '**** Error connecting ****',
                      error + color.normal())

        attempts = 10
        json_data = machine_data.get()
        while attempts:
            attempts = attempts - 1
            #print('\t{\n\t\tAttempt to send data: ', attempts)
            try:
                #print('\t\t{\n\t\t\tSending data')
                client_socket.sendall(bytes(str(json_data), 'UTF-8'))
                #print('\t\t\tData Sent\n\t\t\t{')
                sleep(0.2)
                #print('\t\t\t\tWait for response')
                while True:
                    buffer_data = client_socket.recv(2000)
                    host_data = str(buffer_data)
                    if host_data.find('null') == -1:
                        parsed_input = str(host_data[2:len(host_data) -
                                                     1].replace("\'", "\""))
                        command_json = ujson.loads(parsed_input)
                        machine_data.parse_data(command_json)
                    attempts = 0
                    #print('\t\t\t\tGot response')
                    break
                #print(color.red()+'\t\t\t}')
            except OSError as error:
                if error.args[0] not in [uerrno.EINPROGRESS, uerrno.ETIMEDOUT]:
                    print(
                        color.red() + '\t\t\t**** ERROR writing ****\n\t\t\t',
                        error)
                    attempts = 0
            #print(color.red()+'\t\t}')
            sleep(0.1)
            break
        client_socket.close()
        #print(color.red()+'\t}\n')
        #print(color.red()+'}'+color.normal())
        sleep(0.1)
Ejemplo n.º 4
0
async def start(to):
    await asyncio.sleep(.6)
    print(color.green() + 'STARTING PYCOM DATA' + color.normal())
    await asyncio.sleep(1)
    while True:
        data_server = sys_info.get('data_server')
        data_host = data_server['host']
        port = data_server['port']
        data_address = data_server['address']
        wifi_st = sys_info.get('wifi')
        if wifi_st == False:
            await asyncio.sleep(3)
        if wifi_st != False:
            if data_address == '':
                if data_host != '':
                    try:
                        data_address = socket.getaddrinfo(data_host,
                                                          port)[0][-1]
                        sys_info.setd('data_server', 'address', data_address)
                    except:
                        data_address = ''
                        print('Error getting DATA addr info')
                else:
                    print('data_host not ready')
                    await asyncio.sleep(3)
            else:
                conn_try = 0
                print(color.green() + '{\n\tCONNECTING TO PYCOM DATA' +
                      color.normal())
                try:
                    s = socket.socket()
                    s.setblocking(False)
                    connected = False
                    while connected == False:
                        try:
                            s.connect(data_address)
                        except OSError as e:
                            if str(e) == "127":
                                connected = True
                            else:
                                conn_try = conn_try + 1
                                if conn_try > to:
                                    print(color.red() + '\tDATA CONN F' +
                                          color.normal())
                                    conn_try = to
                                    break
                        await asyncio.sleep(.1)
                        pass
                    #connected
                    if connected == True:
                        print(color.green() + '\tconnected to data_address' +
                              color.normal())
                        conn_try = 0
                        while True:
                            if conn_try > to:
                                print('\n\tcouldnt send data')
                                break

                            data = json.dumps(machine_data.get())
                            data = data.encode()
                            while True:
                                try:
                                    while data:
                                        sent = s.send(data)
                                        data = data[sent:]
                                        await asyncio.sleep(.01)
                                    print('\tdata sent')
                                    machine_data.set('command',
                                                     {'command': 'wait'})
                                    break
                                except OSError as e:
                                    if conn_try > to:
                                        print(color.red() + 'DATA SEND F' +
                                              color.normal())
                                        conn_try = 0
                                        break
                                    conn_try = conn_try + 1
                                    await asyncio.sleep(.1)
                            print('\treceiving DATA server data')
                            while True:
                                try:
                                    res = s.recv(256)
                                    await asyncio.sleep(.01)
                                    if str(res).find('command') != -1:
                                        print('\tDATA server data received: ')
                                        print('\t', color.yellow(), res,
                                              color.normal())
                                        try:
                                            js_res = json.loads(res)
                                        except:
                                            print('failed to load json')
                                        try:
                                            machine_data.parse_data(js_res)
                                            conn_try = 0
                                        except:
                                            print('failed to parse data',
                                                  js_res)
                                        break
                                    if conn_try > to * 10:
                                        print(color.red() + '\tDATA RECV F' +
                                              color.normal())
                                        break
                                    conn_try = conn_try + 1
                                except OSError as e:
                                    if conn_try > to:
                                        print(color.red() +
                                              '\tERROR DATA RECV F' +
                                              color.normal())
                                        break
                                    conn_try = conn_try + 1
                                    await asyncio.sleep(.1)
                            await asyncio.sleep(.1)
                    print(color.yellow() + '\tdata conn_try', conn_try)
                    print(color.red() + '\tdata out\n}\n' + color.normal())
                    sys_info.setd('data_server', 'timeout', conn_try)
                    s.close()
                    del s
                except OSError as e:
                    print('data socket failed', str(e))
        gc.collect()
        await asyncio.sleep(.1)
Ejemplo n.º 5
0
async def start(to):
    await asyncio.sleep(.6)
    print(color.green() + 'STARTING PYCOM DATA' + color.normal())
    await asyncio.sleep(1)
    while True:
        data_server = sys_info.get('data_server')
        data_host = data_server['host']
        port = data_server['port']
        data_address = data_server['address']
        wifi_st = sys_info.get('wifi')
        if wifi_st == False:
            await asyncio.sleep(3)
        if wifi_st != False:
            if data_address == '':
                if data_host != '':
                    try:
                        data_address = socket.getaddrinfo(data_host,
                                                          port)[0][-1]
                        sys_info.setd('data_server', 'address', data_address)
                    except:
                        data_address = ''
                        print('Error getting DATA addr info')
                else:
                    print('data_host not ready')
                    await asyncio.sleep(3)
            else:
                conn_try = 0
                timeout = 0
                timeout_time = to
                trycount = 0
                trycount_timeout = to
                print(color.green() + '{\n\tCONNECTING TO PYCOM DATA' +
                      color.normal())
                try:
                    client = socket.socket()
                    client.setblocking(False)
                    connected = False
                    while connected == False:
                        try:
                            client.connect(data_address)
                        except OSError as e:
                            if str(e) == "127":
                                connected = True
                            else:
                                conn_try = conn_try + 1
                                if conn_try > to:
                                    print(color.red() + '\tDATA CONN F' +
                                          color.normal())
                                    conn_try = to
                                    break
                        await asyncio.sleep(.1)
                        pass
                    #connected
                    if connected == True:
                        print(color.green() + '\tconnected to data_address' +
                              color.normal())
                        while True:
                            if timeout > timeout_time:
                                print('failed to send data', timeout)
                                break
                            if trycount > trycount_timeout:
                                print('couldnt send data')
                                break
                            await asyncio.sleep(.1)

                            data = json.dumps(machine_data.get())
                            data = data.encode()
                            while True:
                                try:
                                    while data:
                                        sent = client.send(data)
                                        data = data[sent:]
                                    print(color.yellow(), 'data sent',
                                          color.normal())
                                    machine_data.set('command',
                                                     {'command': 'wait'})
                                    timeout = 0
                                    break
                                except:
                                    timeout = timeout + 1

                            if timeout == 0:
                                while True:
                                    trycount = trycount + 1
                                    if trycount > trycount_timeout:
                                        print(color.yellow(),
                                              'couldnt receive data',
                                              color.normal())
                                        break
                                    print(color.yellow(), 'tries to read:',
                                          trycount, timeout, color.normal())
                                    await asyncio.sleep(.1)
                                    try:
                                        res = client.recv(256)
                                        if str(res).find('command') != -1:
                                            print(color.yellow(), res,
                                                  color.normal())
                                            timeout = 0
                                            break
                                    except:
                                        timeout = timeout + 1
                                        if timeout > timeout_time:
                                            print(color.yellow(),
                                                  'failed to read data',
                                                  timeout, color.normal())
                                            break
                            if timeout == 0:
                                trycount = 0
                                try:
                                    js_res = json.loads(res)
                                except:
                                    print('failed to load json')
                                try:
                                    machine_data.parse_data(js_res)
                                except:
                                    print('failed to parse data', js_res)

                    print(color.yellow() + '\tdata trycount', trycount)
                    print(color.red() + '\tdata out\n}\n' + color.normal())
                    sys_info.setd('data_server', 'timeout', conn_try)
                    client.close()
                    del client
                except OSError as e:
                    print('data socket failed', str(e))
        gc.collect()
        await asyncio.sleep(.1)
Ejemplo n.º 6
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)