예제 #1
0
def check(module_name):
    global git_sys_info, esp_sys_info, git_url
    esp_sys_info = sys_info.esp_info()
    git_sys_info = sys_info.git_info()
    git_url = sys_info.git_url()
    print(
        '\n' + color.blue() + 'git_sys_info:', color.normal(),
        str(git_sys_info).replace(',',
                                  ',\n').replace('{',
                                                 '{\n ').replace('}', '\n}'))
    print(
        '\n' + color.red() + 'esp_sys_info:', color.normal(),
        str(esp_sys_info).replace(',',
                                  ',\n').replace('{',
                                                 '{\n ').replace('}', '\n}'))

    sys_state = (False, 'system', 'updated')
    try:
        if module_name == '':
            for module in git_sys_info:
                try:
                    if esp_sys_info[module] != git_sys_info[module]:
                        sys_state = (False, module, "outdated")
                except:
                    print("error: module '" + module + "' not founded")
            return sys_state
        else:
            if esp_sys_info[module_name] != git_sys_info[module_name]:
                return True, module_name, "outdated"
            else:
                return False, module_name, "updated"
    except:
        return "error: module '" + module_name + "' not founded"
예제 #2
0
async def camv2(asd):
    print(color.blue() + 'SENDING CAM' + color.normal())
    await asyncio.sleep(1)
    while True:
        connected = False
        #print('try to connect')
        s = socket.socket()
        s.setblocking(False)
        while connected == False:
            try:
                #print('connecting')
                s.connect(cam_address)
            except OSError as e:
                #print(e)
                if str(e) == "127":
                    connected = True
            pass
        img = next(pic)
        try:
            POST(s, 'snap/dev_cam01', 'img', img)
        except:
            print('failed')
        s.close()
        print(color.red() + 'cam out' + color.normal())
        del s
        gc.collect()
        await asyncio.sleep(.2)
예제 #3
0
def start_cam(address):
    json_data = machine_data.create()
    while True:
        client_socket = socket.socket()
        client_socket.setblocking(False)

        try:    
            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())
        
        try:
            POST(client_socket, 'snap/dev_cam01', 'img',next(pic)) 
            sleep(0.2)        
            while True:
                res = str(client_socket.recv(2000))
                command = str(res)[str(res).find('\\r\\n\\r\\n')+len('\\r\\n\\r\\n'):len(str(res))-1]
                json_command = ujson.loads(command)
                print(json_command)
                break    
        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+color.normal())
                attempts = 0

        client_socket.close()  # flash buffer and close socket
        del client_socket
        gc.collect()
        sleep(.1)
예제 #4
0
def cs(s):  #connects using socket
    connected = False
    print('try to connect')

    while connected == False:
        try:
            #print('connecting')
            s.connect(data_address)
        except OSError as e:
            print(e)
            if str(e) == "127":
                connected = True
            elif str(e) == "120":
                connected = True
        pass

    print(color.green() + 'connected' + color.normal())
    while True:
        if sd(s):
            print('data sent')
            while True:
                if rd(s):
                    break
            break
    s.close()
    print(color.red() + 'disconnected' + color.normal())
    del s
    gc.collect()
예제 #5
0
def read_remote(file_name, dir_url):
    print(color.blue() + '\nReading', file_name, 'from', dir_url, '\n')
    try:
        remote_file = urequests.get(dir_url + file_name)
        print('got file\n', remote_file.text + color.normal())
        return remote_file
    except:
        print(color.red, 'error reading remote file' + color.normal())
        return 'error reading remote file'
예제 #6
0
def git_file(file_name):
    try:
        outdated_file = urequests.get(git_url + file_name)
        try:
            file = open("/structure/" + file_name, "w")
            file.write(outdated_file.text)
            file.close()
            print(color.normal() + outdated_file.text)
            print(color.green(), file_name, 'updated\n' + color.normal())
        except:
            print("error: didn't found", file_name)
    except:
        print('error: getting git file')
예제 #7
0
def start_com(address):
    json_data = machine_data.create()
    while True:
        print(color.green() + 'Check cam_socket')
        cam_state = sget('cam')
        while cam_state != 'socket_closed':
            cam_state = sget('cam')
            sleep(.05)
            pass
        print(color.green() + 'cam_socket disconnected')
        try:
            sset('com', 'creating_socket')
            client_socket = socket.socket()
            print(color.normal() + '{')
            client_socket.setblocking(0)
            try:
                print(color.green() + '{\n\tConnect to', "asmon.com.ar:", 8080)
                sset('com', 'connecting')
                client_socket.connect(address)
                print('\t\t{\n\t\t\tSending data')
                POST(client_socket, 'esp_data/dev_cam01', 'json',
                     machine_data.get())
                print('\t\t\tData Sent\n\t\t\t{')
                print('\t\t\t\tWait for response')

                sleep(0.2)
                buffer_data = client_socket.recv(1024)
                while (len(buffer_data) > 0):
                    print(buffer_data)
                    print(color.blue() + '\t\t\t\tGot response')
                    break
                connection = True
            except Exception as error:
                client_socket.close()
                connection = False
                print(color.red() + '\t\t\t**** ERROR Connecting ****\n\t\t\t',
                      error)

            client_socket.close()  # flash buffer and close socket
            del client_socket
            sset('com', 'socket_closed')
        except:
            print('failed to create socket')

        gc.collect()
        print(color.red() + '\t\t\t}')
        print(color.normal() + '\t\t}')
        print(color.normal() + '\t}\n')
        print('}')
        sleep(.5)
예제 #8
0
파일: sv334.py 프로젝트: marsex/asmon
def start():
    print(color.yellow()+'\n Starting CAM_SYSTEM')
    #server_list = get_server_list()
    host, port = ['asmon.com.ar','8081'] #server_list[0].split(':')
    if host != 'null':
        print(color.green()+'\nStart server communication\n' +
              'IP:', host, '\nPORT:', port+'\n'+color.normal())
        try:
            address = socket.getaddrinfo(host, port)[0][-1]
            print(address)
            th(start_cam, (address,))
        except:
            print(color.red()+'Error getting addr info from', host, port, color.normal())
    else:
        print(color.red()+'Error starting CAM_SYSTEM'+color.normal())
예제 #9
0
async def comv2(asd):
    print(color.green() + 'SENDING ESP DATA' + color.normal())
    await asyncio.sleep(1)
    while True:
        s = socket.socket()
        s.setblocking(False)
        connected = False
        while connected == False:
            try:
                #print('connecting')
                s.connect(data_address)
            except OSError as e:
                #print(e)
                if str(e) == "127":
                    connected = True
            pass
        try:
            POST(s, 'esp_data/dev_cam01', 'json', machine_data.get())
            server_data = s.recv(1024)
            print(server_data)
        except:
            print('failed')

        s.close()
        del s
        gc.collect()
        await asyncio.sleep(.2)
예제 #10
0
def ccs(s):
    #connect cam server
    connected = False
    print('try to connect')

    while connected == False:
        try:
            #print('connecting')
            s.connect(cam_address)
        except OSError as e:
            print(e)
            if str(e) == "127":
                connected = True
            elif str(e) == "120":
                connected = True
        pass
    print(color.green() + 'connected' + color.normal())

    img = next(pic)
    while True:
        if sc(s, img):
            print('img sent')
            while True:
                if rd(s):
                    break
            break
예제 #11
0
파일: sv334.py 프로젝트: marsex/asmon
def start_cam(address):
    while True:
        com_state = sget('com')
        if com_state == 'socket_closed':
            sset('cam','busy')
            try:
                client_socket = socket.socket()
                th(timeout,(client_socket,5))
                try:    
                    client_socket.connect(address)
                except OSError as error:
                  if error.args[0] not in [uerrno.EINPROGRESS, uerrno.ETIMEDOUT]:
                    print(color.red()+'**** Error connecting  CAM ****', error,color.normal())
                img = next(pic)
                try:
                    POST(client_socket, 'snap/dev_cam01', 'img',img) 
                    while True:
                        res = str(client_socket.recv(2000))
                        #if res.find('200 OK') != -1:
                            #print(res)
                        break    
                except OSError as error:
                    if error.args[0] not in [uerrno.EINPROGRESS, uerrno.ETIMEDOUT]:
                        print(color.red()+'\t\t\t**** ERROR writing CAM  ****\n\t\t\t', error,color.normal())

                client_socket.close()  # flash buffer and close socket
                del client_socket
                gc.collect()
            except OSError as error:
                print(color.red()+'\t\t\t**** ERROR creating CAM socket ****\n\t\t\t', error, color.normal())
        sset('cam','socket_closed')
        sleep(.2)
예제 #12
0
def tc(to):
    conn_try = 0
    s = socket.socket()
    s.setblocking(False)
    connected = False
    while connected == False:
        try:
            #print('connecting')
            s.connect(cam_address)
        except OSError as e:
            print(conn_try)
            if str(e) == "127":
                connected = True
                conn_try = 0
            else:
                conn_try = conn_try + 1
                if conn_try > to:
                    print(color.red() + 'DATA CONN F' + color.normal())
                    break
        sleep(.05)
        pass
    if connected == True:
        return s
    else:
        return False
예제 #13
0
파일: sv334.py 프로젝트: marsex/asmon
def start_com(address):
    global json_command
    while True:
        try:
            client_socket = socket.socket()
            client_socket.setblocking(False)

            try:    
                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())
            
            try:
                POST(client_socket, 'esp_data/dev_cam01', 'json',machine_data.get())         
                while True:
                    res = str(client_socket.recv(2000))
                    sleep(.2)
                    if res.find('200 OK') != -1:
                        command = str(res)[str(res).find('\\r\\n\\r\\n')+len('\\r\\n\\r\\n'):len(str(res))-1]
                        new_json_command = ujson.loads(command)
                        if json_command != new_json_command:
                            json_command = new_json_command
                            print(json_command)
                    break    
            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, color.normal())

            client_socket.close()  # flash buffer and close socket
            del client_socket
            gc.collect()
        except OSError as error:
            print(color.red()+'\t\t\t**** ERROR creating socket ****\n\t\t\t', error, color.normal())
        sleep(.1)
예제 #14
0
def tsr(s, to):
    global json_command
    POST(s, 'esp_data/dev_cam01', 'json', machine_data.get())
    conn_try = 0
    while True:
        try:
            res = str(s.recv(1024))
            if res.find('200 OK') != -1:
                try:
                    command = str(res)[str(res).find('\\r\\n\\r\\n') +
                                       len('\\r\\n\\r\\n'):len(str(res)) - 1]
                    new_json_command = json.loads(command)
                    #            if json_command != new_json_command:
                    #                json_command = new_json_command
                    print(new_json_command)
                    print('\nright recv', res)
                    break
                except OSError as e:
                    print('wrong recv ' + res + str(e))
                    break
        except OSError as e:
            if conn_try > to:
                print(color.red() + 'DATA CONN F' + color.normal())
                break
            conn_try = conn_try + 1
            print('error receiving ' + str(e))
        sleep(.1)
    s.close()
예제 #15
0
def git_info():
    try:
        git_sys_info = json.loads(urequests.get(get('esp_sys_info')['git_url']+'sys_info').text)
        print('\n'+color.blue()+'git_sys_info:',color.normal(), str(git_sys_info).replace(',',',\n').replace('{','{\n ').replace('}','\n}'))
        return git_sys_info
    except:
        print('\terror getting git system info\n}\n')
        return False
예제 #16
0
def remote(file_name,file_dir,from_url):
  print(color.blue,'\nRemotely updating:',file_name,'from:', from_url ,'\n')  
  try:
    print('Get:',from_url)
    remote_file=urequests.get(from_url)
    print('Got:',from_url)
    try:
      file = open(file_dir+"/"+file_name,"w")
      file.write(remote_file.text)
      file.close()
      print(color.normal()+remote_file.text)
      print(color.green(),file_name,'updated\n'+color.normal())
      import machine
      machine.reset()
    except:
      print("error: didn't found",file_name)
  except:
    print('error: getting git file')
예제 #17
0
def esp_info():
    try:
        sys_file = open('/structure/sys_info','r')
        esp_sys_info = json.loads(sys_file.read())
        sys_file.close()
        print('\n'+color.red()+'esp_sys_info:',color.normal(), str(esp_sys_info).replace(',',',\n').replace('{','{\n ').replace('}','\n}'))
        return esp_sys_info
    except:
        print('\terror getting esp system info\n}\n')
        return False
예제 #18
0
async def start(loop_delay):
    await asyncio.sleep(.1)
    print(color.yellow() + 'wifi state running' + color.normal())
    while True:
        cd_state, cd_ssid, cd_pw = wifi.get_credentials()

        st_wlan = network.WLAN(network.STA_IF)
        wifi_st = st_wlan.isconnected()

        server_list = sys_info.get('server_list')
        data_server = sys_info.get('data_server')
        cam_server = sys_info.get('cam_server')
        git_sys_info = sys_info.get('git_sys_info')

        sys_info.set('wifi', wifi_st)
        if wifi_st == False:
            if cd_state == True:
                print('Connecting to:', cd_ssid, cd_pw)
                st_wlan.active(True)
                st_wlan.connect(cd_ssid, cd_pw)
            else:
                print('Waiting for Wifi Credentials')
        else:
            if git_sys_info == '':
                sys_info.set('git_sys_info', sys_info.git_info())
                if update.check('sys_info')[0] == True:
                    print('\nSystem OUTDATED')
                    update.system()
                    print('\nSystem UPDATED')
                    print('\nRestarting system\n-----------------------\n\n')
                    machine.reset()
                else:
                    print('\nSystem updated\nStart system')

            if server_list == 'null':
                try:
                    server_request = update.read_remote(
                        'server_list',
                        sys_info.get('esp_sys_info')['git_url'])
                    server_list = json.loads(server_request.text)
                    data_host, data_port = server_list['data_host'][0].split(
                        ':')
                    cam_host, cam_port = server_list['cam_host'][0].split(':')

                    sys_info.set('server_list', server_list)
                    sys_info.setd('data_server', 'host', data_host)
                    sys_info.setd('data_server', 'port', data_port)
                    sys_info.setd('cam_server', 'host', cam_host)
                    sys_info.setd('cam_server', 'port', cam_port)
                except:
                    sys_info.reset()
            # if data_server['timeout'] != 0:
            # sys_info.set('server_list','null')
            # sys_info.setd('data_server','timeout',0)
        await asyncio.sleep(loop_delay)
예제 #19
0
파일: asmon_sys.py 프로젝트: marsex/asmon
def start():
    print(color.yellow() + '\n Starting asmon_system')
    #server_list = get_server_list()
    #host, port = ['asmon.com.ar','8080'] #server_list[0].split(':')
    host = 's'
    h1 = "http://asmon.com.ar:8080/esp_data/dev_cam01"
    h2 = "http://asmon.com.ar:8081/snap/dev_cam01"

    if host != 'null':
        print(color.green() + '\nStart server communication\n' +
              color.normal())
        try:
            th(plus, (
                h1,
                h2,
            ))
            #th.start_new_thread(start_com, (data_address,cam_address,))
        except:
            print(color.red() + 'Error starting com thread' + color.normal())
    else:
        print(color.red() + 'Error starting asmon_system' + color.normal())
예제 #20
0
def system():
  update_list = []
  for module in git_sys_info:
    try:
      if esp_sys_info[module] != git_sys_info[module]:
        update_list.append(module)
    except:
      update_list.append(module)
      print("error: module '"+ module +"' not founded on local esp system")
  print('OUTDATED Modules:', update_list)
  for outdated_module in update_list:
    print(color.blue(),'\nUpdating:', outdated_module+color.normal())
    git_file(outdated_module)
예제 #21
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)
예제 #22
0
def start():
    print(color.yellow() + '\n Starting asmon_system')
    server_list = get_server_list()
    host, port = server_list[0].split(':')
    if host != 'null':
        print(color.green() + '\nStart server communication\n' + 'IP:', host,
              '\nPORT:', port + '\n' + color.normal())
        try:
            address = socket.getaddrinfo(host, port)[0][-1]
            print(address)
            th.start_new_thread(start_com, (address, ))
        except:
            print(color.red() + 'Error getting addr info from', host, port)
    else:
        print(color.red() + 'Error starting asmon_system')
예제 #23
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)
예제 #24
0
async def camv2(to):
    print(color.blue() + 'SENDING CAM' + color.normal())
    await asyncio.sleep(1)
    conn_try = 0
    while True:
        connected = False
        #print('try to connect')
        s = socket.socket()
        s.setblocking(False)
        while connected == False:
            try:
                s.connect(cam_address)
            except OSError as e:
                #print(conn_try)
                if str(e) == "127":
                    connected = True
                    conn_try = 0
                else:
                    conn_try = conn_try + 1
                    if conn_try > to:
                        print(color.red() + 'CAM CONN F' + color.normal())
                        break
            await asyncio.sleep(.05)
            pass
        if conn_try != to:
            print(color.green() + '{\n\tconnected to cam_address' +
                  color.normal())
            try:
                n_try = 0
                buf = False
                while (n_try < 10 and buf == False):  #{
                    # wait for sensor to start and focus before capturing image
                    print('\tgetting img')
                    buf = camera.capture()
                    if (buf == False): await asyncio.sleep(2)
                    n_try = n_try + 1
                print('\tsending img')
                while True:
                    try:
                        type = 'image/jpeg'
                        size = len(buf)
                        req = 'snap/dev_cam01'
                        header = h['POST'].replace('$req',
                                                   req).replace('$type', type)
                        s.send(b'%s %d\r\n\r\n' % (header, size))
                        while buf:
                            sent = s.send(buf)
                            buf = buf[sent:]
                            await asyncio.sleep(.5)
                        break
                    except OSError as e:
                        print(e)
                        if conn_try > to:
                            print(color.red() + 'CAM SEND F' + color.normal())
                            break
                        conn_try = conn_try + 1
                #POST(s, 'snap/dev_cam01', 'img',buf)
                print('\timg sent')
            except OSError as e:
                print('cam failed ' + str(e))
        s.close()
        print(color.red() + '\tcam out\n}\n' + color.normal())
        del s
        gc.collect()
        conn_try = 0
        await asyncio.sleep(.2)
예제 #25
0
async def comv2(to):
    global json_command
    print(color.green() + 'SENDING ESP DATA' + color.normal())
    await asyncio.sleep(1)
    conn_try = 0
    while True:
        s = socket.socket()
        s.setblocking(False)
        connected = False
        while connected == False:
            try:
                #print('connecting')
                s.connect(data_address)
            except OSError as e:
                #print(conn_try)
                if str(e) == "127":
                    connected = True
                    conn_try = 0
                else:
                    conn_try = conn_try + 1
                    if conn_try > to:
                        print(color.red() + 'DATA CONN F' + color.normal())
                        break
            await asyncio.sleep(.05)
            pass
        if conn_try != to:
            print(color.green() + '{\n\tconnected to data_address' +
                  color.normal())
            conn_try = 0
            try:
                #POST(s, 'esp_data/dev_cam01', 'json',{'uptime':9999,"out_s":[1,0,0,0,0,0,0,1],"in_s":[1,0,0,0,0,0,0,1]})
                print('\tsending esp_data')
                #POST(s, 'esp_data/dev_cam01', 'json',machine_data.get())
                while True:
                    try:
                        type = 'application/json'
                        data = json.dumps(machine_data.get())
                        size = len(data)
                        data = data.encode()
                        req = 'esp_data/dev_cam01'
                        header = h['POST'].replace('$req',
                                                   req).replace('$type', type)
                        s.send(b'%s %d\r\n\r\n' % (header, size))
                        while data:
                            sent = s.send(data)
                            data = data[sent:]
                            await asyncio.sleep(.5)
                        conn_try = 0
                        break
                    except OSError as e:
                        print(e)
                        if conn_try > to:
                            print(color.red() + 'DATA SEND F' + color.normal())
                            break
                        conn_try = conn_try + 1

                if conn_try != to:
                    while True:
                        try:
                            print('\treceiving server data')
                            res = str(s.recv(1024))
                            await asyncio.sleep(.2)
                            if res.find('200 OK') != -1:
                                print('\tserver data received')
                                try:
                                    command = str(res)[
                                        str(res).find('\\r\\n\\r\\n') +
                                        len('\\r\\n\\r\\n'):len(str(res)) - 1]
                                    new_json_command = json.loads(command)
                                    #            if json_command != new_json_command:
                                    #                json_command = new_json_command
                                    print(color.green() +
                                          str(new_json_command) +
                                          color.normal())
                                    #print('\nright recv',res)
                                    break
                                except OSError as e:
                                    print('wrong recv ' + res + str(e))
                                    break
                        except OSError as e:
                            if conn_try > to:
                                print(color.red() + 'DATA RECV F' +
                                      color.normal())
                                break
                            conn_try = conn_try + 1
                            #print('error receiving '+str(e))
                        await asyncio.sleep(.2)
                s.close()
            except OSError as e:
                print('data com failed ' + str(e))
        print(color.red() + '\tesp_data out\n}\n' + color.normal())
        s.close()
        del s
        gc.collect()
        gc.mem_free()
        conn_try = 0
        await asyncio.sleep(.1)
예제 #26
0
파일: ap_cam.py 프로젝트: marsex/asmon_2021
async def start(to):
    await asyncio.sleep(.24)
    print(color.yellow() + 'STARTING AP_CAM' + 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', 81)
    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(50)  # time in milliseconds
            if not res:
                print('\toperation timed out')
            else:
                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)

                while True:
                    try:
                        if req[1] == 'live':
                            print('\taccesing', req[1])
                            client.send(b'%s' % hdr.get('stream'))

                            client.send(b'%s' % hdr.get('frame'))
                            n_try = 0
                            buf = False
                            cam.light('1')
                            while (n_try < 10 and buf == False):  #{
                                # wait for sensor to start and focus before capturing image
                                #print('\tgetting img')
                                buf = camera.capture()
                                if (buf == False): await asyncio.sleep(1)
                                n_try = n_try + 1
                            cam.light('0')
                            #print('\tsending img:', len(buf))
                            try:
                                while buf:
                                    sent = client.send(buf)
                                    buf = buf[sent:]
                                #print('\timg sent')
                            except OSError as e:
                                print('send apcam error', e)
                            client.send(
                                b'\r\n')  # send and flush the send buffer
                    except OSError as e:
                        print(e)
                        break
                    await asyncio.sleep(.1)

            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)
예제 #27
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)
예제 #28
0
async def start(to):
    await asyncio.sleep(.12)
    print(color.blue() + 'STARTING PYCOM CAM' + color.normal())
    await asyncio.sleep(1)
    while True:
        cam_server = sys_info.get('cam_server')
        cam_host = cam_server['host']
        port = cam_server['port']
        cam_address = cam_server['address']
        wifi_st = sys_info.get('wifi')
        if wifi_st == False:
            await asyncio.sleep(3)
        if wifi_st != False:
            if cam_address == '':
                if cam_host != '':
                    try:
                        cam_address = socket.getaddrinfo(cam_host, port)[0][-1]
                        sys_info.setd('cam_server', 'address', cam_address)
                    except:
                        cam_address = ''
                        print('Error getting CAM addr info')
                else:
                    print('cam_host not ready')
                    await asyncio.sleep(3)
            else:
                conn_try = 0
                timeout = 0
                timeout_time = to
                trycount = 0
                trycount_timeout = to
                print(color.blue() + '{\n\tCONNECTING TO PYCOM CAM' +
                      color.normal())
                try:
                    client = socket.socket()
                    client.setblocking(False)
                    connected = False
                    while connected == False:
                        try:
                            client.connect(cam_address)
                        except OSError as e:
                            if str(e) == "127":
                                connected = True
                            else:
                                conn_try = conn_try + 1
                                if conn_try > to:
                                    print(color.red() + '\tCAM CONN F' +
                                          color.normal())
                                    conn_try = to
                                    break
                        await asyncio.sleep(.1)
                        pass
                    #connected
                    if connected == True:
                        print(color.blue() + '\tconnected to cam_address' +
                              color.normal())
                        while True:
                            if timeout > timeout_time:
                                print(color.blue(), 'failed to send image',
                                      trycount, timeout, color.normal())
                                break
                            if trycount > trycount_timeout:
                                print('couldnt send image')
                                break
                            await asyncio.sleep(.1)

                            img_data = {
                                'user': machine_data.get_key('user'),
                                'id': machine_data.get_key('id')
                            }
                            id_data = json.dumps(img_data)
                            id_data = id_data.encode()
                            data = json.dumps({'command': 'imgsent'})
                            data = data.encode()

                            frame = False
                            cam.light('1')
                            frame = camera.capture()
                            cam.light('0')

                            frame = id_data + frame + data
                            while True:
                                await asyncio.sleep(.1)
                                try:
                                    while frame:
                                        sent = client.send(frame)
                                        frame = frame[sent:]
                                    print(color.blue(), 'image sent',
                                          color.normal())
                                    timeout = 0
                                    break
                                except:
                                    timeout = timeout + 1
                                    if timeout > timeout_time * 2:
                                        print(color.blue(),
                                              'failed to send image', trycount,
                                              timeout, color.normal())
                                        break
                            if timeout == 0:
                                while True:
                                    trycount = trycount + 1
                                    if trycount > trycount_timeout:
                                        print(color.blue(),
                                              'couldnt receive image data',
                                              color.normal())
                                        break
                                    print(color.blue(), 'tries to read:',
                                          trycount, timeout, color.normal())
                                    await asyncio.sleep(.1)
                                    try:
                                        res = client.recv(256)
                                        if str(res).find('command') != -1:
                                            print(color.blue(), res,
                                                  color.normal())
                                            timeout = 0
                                            break
                                    except:
                                        timeout = timeout + 1
                                        if timeout > timeout_time:
                                            print(color.blue(),
                                                  'failed to read image data',
                                                  timeout, color.normal())
                                            break
                            if timeout == 0:
                                trycount = 0
                            print('')  #send again
                    print(color.blue() + '\tcam trycount', trycount)
                    print(color.red() + '\tcam out\n}\n' + color.normal())
                    sys_info.setd('cam_server', 'timeout', conn_try)
                    client.close()
                    del client
                except OSError as e:
                    print('cam socket failed', str(e))
        gc.collect()
        await asyncio.sleep(.1)
예제 #29
0
async def sv(to):
    global json_command
    print(color.green() + 'STARTING LOCAL SERVER' + color.normal())
    await asyncio.sleep(1)
    port = 80
    ap_localhost = '0.0.0.0'  # get ip addr
    conn_try = 0
    while True:
        # try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #s.setblocking(False)
        a = ('0.0.0.0', 80)
        s.bind(a)
        s.listen(2)  # queue at most 2 clients
        print('\nSocket now listening on', str(ap_localhost) + ':' + str(port))
        while True:
            try:
                ok = True
                error = ''
                try:
                    print(' in sec NB! default browser timeout (5-15 min)')
                    socket.settimeout(0.05)
                    client, client_address = socket.accept()
                    client.settimeout(0.5)  # in sec
                except Exception as e:
                    error = str(e)

                if error != '':
                    pass
                    ok = False

                if ok:  # No soc.accept timeout
                    error = ''
                    try:
                        print(' client accepted')
                        client_data = client.recv(1024)
                        print('# REQ: b'
                              '  # may be due to very short timeout')
                    except Exception as e:
                        error = str(e)

                    if error != '':
                        print(error)
                        ok = False
                    else:
                        client_data = client_data.decode('utf-8')
                        if client_data.find('favicon.ico') < 0:
                            req = client_data.split(' ')
                            try:
                                print(req[0], req[1], client_address)
                            except:
                                ok = False
                        else:
                            print('# handle favicon request early')
                            client.send(b'%s' % hdr['favicon'])
                            clean_up(client)
                            ok = False

                if ok:  # No soc.recv timeout or favicon request
                    try:
                        print('try asyncio port1')
                        asyncio.run(port1(client, req[1]))
                    except Exception as e:
                        error = str(e)
                        if error != '':
                            print(error)
            except Exception as e:
                error = str(e)
                if error != '':
                    print(error)
        print('error????')
        await asyncio.sleep(.1)
예제 #30
0
파일: camv2.py 프로젝트: marsex/asmon
async def cam(to, to2):
    print(color.blue() + 'SENDING CAM' + color.normal())
    await asyncio.sleep(1)
    conn_try = 0
    while True:
        connected = False
        #print('try to connect')
        try:
            s = socket.socket()
            s.setblocking(False)
            while connected == False:
                try:
                    s.connect(cam_address)
                except OSError as e:
                    #print(conn_try)
                    if str(e) == "127":
                        connected = True
                        conn_try = 0
                    else:
                        conn_try = conn_try + 1
                        if conn_try > to:
                            print(color.red() + 'CAM CONN F' + color.normal())
                            break
                await asyncio.sleep(.05)
                pass
            if conn_try != to:
                print(color.green() + '{\n\tconnected to cam_address' +
                      color.normal())
                try:
                    buf = camera.capture()
                    while True:
                        try:
                            type = 'image/jpeg'
                            size = len(buf)
                            req = 'snap/dev_cam01'
                            header = h['POST'].replace('$req', req).replace(
                                '$type', type)
                            s.send(b'%s %d\r\n\r\n' % (header, size))
                            print('img size', size)
                            while buf:
                                sent = s.send(buf)
                                buf = buf[sent:]
                                await asyncio.sleep(to2)
                            break
                        except OSError as e:
                            print(e)
                            if conn_try > to:
                                print(color.red() + 'CAM SEND F' +
                                      color.normal())
                                break
                            conn_try = conn_try + 1
                    #POST(s, 'snap/dev_cam01', 'img',buf)
                    print('\timg sent')
                except OSError as e:
                    print('\tsending cam failed ' + str(e))
            s.close()
            print(color.red() + '\tcam out\n}\n' + color.normal())
            del s
        except OSError as e:
            print('cam socket failed', str(e))
        gc.collect()
        conn_try = 0
        await asyncio.sleep(.1)