commit 10/24/2015

This commit is contained in:
2015-10-24 00:00:00 -06:00
committed by Anthony Correa
parent df6f462cb0
commit 8d45de4f2d
5 changed files with 111 additions and 40 deletions

View File

@@ -108,14 +108,16 @@ class Datareporter_Debug3 ():
def __init__(self, path=SCRIPTDIR,
report_url = "http://10.0.1.4:5010/report",
report_image_url = "http://10.0.1.4:5010/photo",
report_image_url = "http://10.0.1.4:5010/upload-file",
com_port_name = "/dev/ttyAMA0",
baud_rate = "9600"):
baud_rate = "9600",
content_type = None):
#TODO communication
self.report_url = report_url
self.report_image_url = report_image_url
self.com_port_name = com_port_name,
self.com_port_name = com_port_name
self.baud_rate = baud_rate
self.content_type = content_type
pass
@@ -138,7 +140,7 @@ class Datareporter_Debug3 ():
print ("%s - Sent Message: %s"% (str(datetime.datetime.now()), message))
elif type == "image":
#todo send image
response = requests.post(self.report_image_url, files={'file': message})
# response = requests.post(self.report_image_url, files={'file': message})
print ("%s - Sent Image: %s"% (str(datetime.datetime.now()), message))
#adding & initializing port object
@@ -157,7 +159,7 @@ class Datareporter_Debug3 ():
inet = self.SimInetGSM(port, logger)
logger.info("attaching GPRS")
if not inet.attachGPRS("internet", "", "", 1):
if not inet.attachGPRS("wholesale", "", "", 1):
logger.error("error attaching GPRS")
return False
@@ -166,13 +168,12 @@ class Datareporter_Debug3 ():
#making HTTP GET request
logger.info("making HTTP POST request")
if not inet.httpPOST_DATA(
"home.ascorrea.com",
5010,
"/photo",
"file={0}".format(message)
"/upload-file",
# content=self.content_type,
parameters="{0}".format(message)
):
logger.error("error making HTTP GET post: {0}".format(inet.errorText))
return False

0
lib/__init__.py Normal file
View File

View File

@@ -33,6 +33,7 @@ import time
import serial
import logging
from lib.sim900.simshared import *
import struct
class GsmSpecialCharacters:
ctrlz = 26 #//Ascii character for ctr+z. End of a SMS.
@@ -132,7 +133,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
"""
return self.print(commandLine, encoding)
def printLn(self, commandString, encoding = "ascii"):
def printLn(self, commandString, bytes=None, encoding = "ascii"):
"""
Sends string data and CR/LF in the end to the SIM module
@@ -140,10 +141,16 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
:param encoding: before sending string it will be converted to the bytearray with this encoding
:return: True if data sent, otherwise returns False
"""
data = bytearray(commandString, encoding) + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
if bytes is not None:
data = bytearray(commandString, encoding) + bytes + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
else:
data= bytearray(commandString, encoding) + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
# print("Print Line data: {}".format(data))
return self.__sendRawBytes(data)
def simpleWriteLn(self, commandLine, encoding = "ascii"):
def simpleWriteLn(self, commandLine, bytes=None, encoding = "ascii"):
"""
Just alias for printLn() method
@@ -152,7 +159,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
:return: True if data sent, otherwise returns False
"""
return self.printLn(commandLine, encoding)
return self.printLn(commandLine, encoding=encoding, bytes=bytes)
def flushInput(self):
"""

View File

@@ -524,37 +524,48 @@ class SimInetGSM(SimGsm):
:return: true if operation was successfully finished. Otherwise returns false
"""
self.__clearHttpResponse()
# self.__clearHttpResponse()
#TODO: close only when opened
self.terminateHttpRequest()
# self.terminateHttpRequest()
#HTTP POST request commands sequence
simpleCommands = [
[ "AT+HTTPINIT", 2000 ],
[ "AT+HTTPPARA=\"CID\",\"{0}\"".format(bearerChannel), 1000 ],
[ "AT+HTTPPARA=\"URL\",\"{0}:{1}{2}\"".format(server, port, path), 500 ],
[ "AT+HTTPPARA=\"CONTENT\",\"multipart/form-data\"", 500 ],
[ "AT+HTTPPARA=\"UA\",\"{0}\"".format(self.userAgent), 500 ],
[ "AT+HTTPPARA=\"REDIR\",\"1\"", 500 ],
[ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 500 ]
]
# simpleCommands = [
# [ "AT+HTTPINIT", 2000 ],
# [ "AT+HTTPPARA=\"CID\",\"{0}\"".format(bearerChannel), 1000 ],
# [ "AT+HTTPPARA=\"URL\",\"{0}:{1}{2}\"".format(server, port, path), 500 ],
# [ "AT+HTTPPARA=\"CONTENT\",\"multipart/form-data\"", 500 ],
# [ "AT+HTTPPARA=\"UA\",\"{0}\"".format(self.userAgent), 500 ],
# [ "AT+HTTPPARA=\"REDIR\",\"1\"", 500 ],
# [ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 500 ]
# ]
simpleCommands = [
[ "AT+CGATT?", 2000 ],
[ "AT+CIPCLOSE", 1000 ],
# [ "AT+CIPMUX=0", 1000 ],
[ "AT+CSTT=\"{0}\"".format('wholesale'), 1000],
[ "AT+CIICR", 500 ],
[ "AT+CIFSR", 500 ],
[ "AT+CIPSTART=\"{0}\",\"{1}\",\"{2}\"".format("TCP", server, port), 500 ],
[ "AT+CIPSEND", 500 ],
# [ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 500 ]
]
#executing commands sequence
if not self.execSimpleCommandsList(simpleCommands):
return False
#uploading data
self.logger.debug("uploading HTTP POST data")
ret = self.commandAndStdResult(
"AT+HTTPDATA={0},10000".format(len(parameters)),
7000,
["DOWNLOAD", "ERROR"]
)
# self.logger.debug("uploading HTTP POST data")
# ret = self.commandAndStdResult(
# "AT+HTTPDATA={0},10000".format(len(parameters)),
# 7000,
# ["DOWNLOAD", "ERROR"]
# )
if (ret is None) or (self.lastResult != "DOWNLOAD"):
self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
return False
# if (ret is None) or (self.lastResult != "DOWNLOAD"):
# self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
# return False
self.simpleWriteLn(parameters)

66
test.py
View File

@@ -3,26 +3,78 @@ from instruments import Camera_Debug2 as Camera
from datahandling import Datareporter_Debug3 as Datareporter
import serial
import sys
import json
REPORTIMAGETOURL = "http://10.0.1.4:5010/photo"
LOG_FILE = "log2.txt"
data = {"temp":1,"press":3,"altitude":2,"cheetas":"just enough"}
import binascii
import base64
from base64 import urlsafe_b64encode
reporter = Datareporter ()
with open('log2.txt','rb') as f:
g=f.read()
e=urlsafe_b64encode(g)
camera = Camera(low_quality_resolution=(320, 180),
low_quality_compression_pct=50)
# a=binascii.b2a_uu(f)
image = camera.capture()
# e = f.encode('base64')
print (image)
# e = str(e, "ascii")
data = {"temp":1,
"press":3,
"altitude":2,
"image":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
# data = json.dumps(data,ensure_ascii=True)
# camera = Camera(low_quality_resolution=(320, 180),
# low_quality_compression_pct=50)
# image = camera.capture()
# print (image)
pass
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
# i=open('resized_image.jpg','rb')
# r=i.read()
# def callback(encoder, bytes_read):
# # Do something with this information
# pass
#
# monitor = MultipartEncoderMonitor.from_fields(
# fields={'field0': 'value0'}, callback
# )
# m = MultipartEncoder(fields={"field":("image", open("resized_image.jpg", 'rb'), "image/jpeg")})
#
reporter = Datareporter (content_type="form-data")
#
# f = open('resized_image.jpg','rb')
# r=f.read()
#report image
# reporter.send(image.get('file'), type="image")
# response = requests.post("http://home.ascorrea.com:5010/upload-file", data=m.read())
# print(type(r))
# reporter.send(str(r)[2:-5].replace("\\\", "\\"), type="image")
# reporter.send("Content-Disposition: {0}; name=\"{1}\"; filename=\"{2}\" {4}".format(
# 'application/octet-stream',
# 'field',
# 'resized_image',
# 'image/jpeg',""), type="image")
reporter.send(data, type="image")
pass