Пример #1
0
def makeMultipartBody(params):

    print("makeMultipartBody")
    mylib.collectMemory()
    #print(mylib.reportMemory())  # for debug
    uniq_str = sha1Hash(str(utime.time() * random()))
    bodyTMPfile = '/sd/' + 'tmp' + uniq_str[5:
                                            10]  # make tmp file name (len:3+5)
    boundary = uniq_str[0:16]  # take string (len:16)
    fp = open(bodyTMPfile, 'wb')
    for key in params:
        fp.write(('--' + boundary).encode())
        fp.write(CRLF)
        value = params[key]

        if key == 'file':
            if len(value) == 1:
                file_name = value[0]
                file_body = None
            if len(value) == 2:
                (file_name, file_body) = value
            else:
                print("Error in makeMultipartBody")
                print("file entity illegal")
                fp.close()
                return None

            fp.write(TMPL_CD_FILE.format(file_name).encode())
            fp.write(CRLF)
            fp.write(TMPL_CT_JPEG)
            fp.write(CRLF * 2)
            if file_body is None:
                with open(file_name, "rb") as fp_body:
                    buffer = bytearray(FILEBUFSIZE)
                    while True:
                        if DBG_MEMORY_REPORT:
                            print(mylib.reportMemory())  # for debug
                        size = fp_body.readinto(buffer, FILEBUFSIZE)
                        if size == 0:
                            break
                        else:
                            fp.write(buffer, FILEBUFSIZE)
                    buffer = None
        else:
            fp.write(TMPL_CD.format(key).encode())
            fp.write(CRLF * 2)
            if isinstance(value, str):
                fp.write(value.encode())
            else:
                print("Error in makeMultipartBody")
                print("entity is not string")
                fp.close()
                return None

        fp.write(CRLF)

    fp.write(('--' + boundary + '--').encode())
    fp.close()
    return (boundary, bodyTMPfile)
    def takePictureAndUpload(self, uploadMessage=None):

        # take Picture and save to tmp File
        mylib.collectMemory()
        fileName = mylib.getPhotoFileNameWithPath('jpg')
        state = self.grovecam.takePictureAndSaveToFile(fileName)

        if state == False:
            print('Error in takeing a photo')
            return False
        else:
            print('photo is saved: ' + fileName)
        print('taking a photo ok, upload photo to CloudService')
        print(mylib.reportMemory())  # for debug

        # upload picture to Cloudinary Server
        mylib.collectMemory()
        s = utime.ticks_ms()  # for time measurement
        (status_code,
         response) = cloudinaryUploader.uploadPhoto(fileName, CLOUD_NAME,
                                                    API_KEY, API_SECRET)
        e = utime.ticks_ms()  # for time measurement
        diff = utime.ticks_diff(e, s)
        print("upload photo takes:{:d}(ms)".format(diff))
        if status_code != 200:
            print('Error in uploading a photo to the Cloud Album Service')
            print('StatusCode:[{:d}]'.format(status_code))
            return False

        print('uploading photo is completed')
        dt = mylib.getLocalTimeJST()
        timeStamp = '{:d}/{:02d}/{:02d} {:02d}:{:02d}'.format(
            dt[0], dt[1], dt[2], dt[3], dt[4])
        if uploadMessage == None:
            uploadMessage = 'Photo is Uploaded'
        uploadMessage = uploadMessage + ' (' + timeStamp + ')'
        photoURL = response['secure_url']
        prevURL = cloudinaryUploader.getResizeURL(photoURL)
        print('access url(org):' + photoURL)
        print('access url(prev):' + prevURL)
        mylib.collectMemory()
        status_code = lineBOT.postImage(LINE_TOKEN, photoURL, prevURL,
                                        uploadMessage)

        if status_code == 200:
            print('POST to LineBOT OK')
        elif status_code == 429:  # 429 is 'Too Many Requests'
            print('Error in lineBOT.postImage')
            print('LineBOT API Error')
            print('Too Many Requests')
            return False
        else:
            print('Error in lineBOT.postImage')
            print('LineBOT API Error')
            print('status[{:03d}]'.format(status_code))
            return False

        return True
Пример #3
0
    def showQQVGAPicture(self, screenClear=False, drawLines=1):

        (h_size, v_size) = QQVGASIZE
        s = utime.ticks_ms()
        if screenClear:
            self.tft.fill(self.tft.BLACK)
        mylib.collectMemory()
        print("free mem: ", end="")
        print(mylib.reportMemory())
        rectSize = h_size * RGB565BPP * drawLines
        lineBuf = bytearray(rectSize)
        self.ov7670.FIFOReadReset()  # read data from Top of FIFO
        for y in range(0, v_size, drawLines):
            if self.shutterPressed:
                print("shutter pressed, so stop drawing")
                break
            self.ov7670.getPixelFromFIFO(lineBuf, rectSize, False)
            self.tft.image(0, y, h_size - 1, y + drawLines, lineBuf)
        e = utime.ticks_ms()
        print("Preview draw time:{:d}(ms)".format(utime.ticks_diff(e, s)))
        mylib.collectMemory()
Пример #4
0
def postBodyFromFile(url, headers, file):

    print("postBodyFromFile")
    mylib.collectMemory()
    #print(mylib.reportMemory())  # for debug

    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "https:":
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
    ai = ai[0]

    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        s.connect(ai[-1])
        s = wrap_socket(s, server_hostname=host)
        s.write(b"%s /%s HTTP/1.0\r\n" % ('POST', path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")

        size = mylib.getFileSize(file)
        if size == None:
            raise ValueError("FileSize is None")
        s.write(b"Content-Length: %d\r\n" % size)
        s.write(b"\r\n")

        with open(file, 'rb') as fp:
            buffer = bytearray(FILEBUFSIZE)
            while True:
                if DBG_MEMORY_REPORT:
                    print(mylib.reportMemory())  # for debug
                size = fp.readinto(buffer, FILEBUFSIZE)
                if size == 0:
                    break
                else:
                    s.write(buffer, FILEBUFSIZE)
            buffer = None
        l = s.readline()
        l = l.split(None, 2)
        status = int(l[1])
        reason = ""
        if len(l) > 2:
            reason = l[2].rstrip()
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
    except OSError:
        s.close()
        raise

    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    return resp
Пример #5
0
    def getImageDataAndWriteFile(self, pictSize, fp=None, verb=False):

        buffer = bytearray(CAM_PACKAGE_SIZE)
        n_of_blocks = int(pictSize / (CAM_PACKAGE_SIZE - PACKAGE_HEADER_VRFY))
        get_size = 0

        #
        # receive  packets
        #

        poll = uselect.poll()
        poll.register(self.uart, uselect.POLLIN)

        for i in range(0, n_of_blocks):
            lowCount = i & 0xFF
            highCount = (i >> 8) & 0xFF
            self.sendCmd('ACK', 0, 0, lowCount, highCount, True)
            getPacket = False  # flag for nth packet is received or not

            #s = utime.ticks_ms()   # for time measurement
            for i in range(MAX_RETRY_COUNT):

                if poll.poll(POLLING_TIMEOUT):

                    size = self.uart.any()
                    if verb:
                        print('uart receive size:{:d}'.format(size))

                    if size != CAM_PACKAGE_SIZE:
                        if verb:
                            print('w.. ', end="")
                        continue
                    else:
                        get_size += CAM_PACKAGE_SIZE
                        if verb:
                            print(get_size)
                        self.uart.readinto(buffer, size)
                        # for time measurement (tune up)
                        #e = utime.ticks_ms()
                        #diff = utime.ticks_diff(e, s)
                        #print("write time:{:d}(ms)".format(diff))
                        #if diff == 0:
                        #     pass
                        #else:
                        #     print("{:d}pbs".format(int(512 * 8 * 1000 / diff )))
                        #if verb:
                        #    print(buffer)
                        if fp is None:
                            print(buffer)
                        else:
                            fp.write(buffer[4:(
                                size - 2)])  # strip headner and verify field
                        if DBG_MEMORY_REPORT:
                            print(mylib.reportMemory())  # for debug
                        getPacket = True
                        break

            # check packet is read or not
            if not getPacket:
                print('Fail to read packet in {:d} times'.format(
                    MAX_RETRY_COUNT))
                print('so discard this picture')
                self.dummyGetImageData()
                return False

        #
        # receive last packet
        #
        # PACKAGE_HEADER_VRFY means...  ID(2):SIZE(2):Verify(2)
        lestSize = pictSize - (CAM_PACKAGE_SIZE - PACKAGE_HEADER_VRFY
                               ) * n_of_blocks + PACKAGE_HEADER_VRFY
        lowCount = n_of_blocks & 0xFF
        highCount = (n_of_blocks >> 8) & 0xFF

        self.sendCmd('ACK', 0, 0, lowCount, highCount, True)
        for i in range(MAX_RETRY_COUNT):

            if poll.poll(POLLING_TIMEOUT):

                size = self.uart.any()
                if verb:
                    print('uart receive size:{:d}'.format(size))
                if size != lestSize:
                    if verb:
                        print('not yet...')
                    continue
                else:
                    get_size += size
                    print(get_size)
                    self.uart.readinto(buffer, size)
                    if fp is None:
                        print(buffer)
                    else:
                        fp.write(
                            buffer[4:(size -
                                      2)])  # strip headner and verify field
                    break

        if self.uart.any() == 0:
            print('read image completed')

        else:
            print('Warning: some data remains in UART buffer')
            print('rest size in buffer:{:d}'.format(self.uart.any()))
            self.dropPacket()

        del poll  # to be on the safe side
        buffer = None
        self.sendCmd('ACK', 0, 0, 0xF0, 0xF0, True)
        return True