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

0
lib/__init__.py Normal file
View File

View File

@@ -33,6 +33,7 @@ import time
import serial import serial
import logging import logging
from lib.sim900.simshared import * from lib.sim900.simshared import *
import struct
class GsmSpecialCharacters: class GsmSpecialCharacters:
ctrlz = 26 #//Ascii character for ctr+z. End of a SMS. ctrlz = 26 #//Ascii character for ctr+z. End of a SMS.
@@ -132,7 +133,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
""" """
return self.print(commandLine, encoding) 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 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 :param encoding: before sending string it will be converted to the bytearray with this encoding
:return: True if data sent, otherwise returns False :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) return self.__sendRawBytes(data)
def simpleWriteLn(self, commandLine, encoding = "ascii"): def simpleWriteLn(self, commandLine, bytes=None, encoding = "ascii"):
""" """
Just alias for printLn() method Just alias for printLn() method
@@ -152,7 +159,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
:return: True if data sent, otherwise returns False :return: True if data sent, otherwise returns False
""" """
return self.printLn(commandLine, encoding) return self.printLn(commandLine, encoding=encoding, bytes=bytes)
def flushInput(self): def flushInput(self):
""" """

View File

@@ -524,37 +524,48 @@ class SimInetGSM(SimGsm):
:return: true if operation was successfully finished. Otherwise returns false :return: true if operation was successfully finished. Otherwise returns false
""" """
self.__clearHttpResponse() # self.__clearHttpResponse()
#TODO: close only when opened #TODO: close only when opened
self.terminateHttpRequest() # self.terminateHttpRequest()
#HTTP POST request commands sequence #HTTP POST request commands sequence
simpleCommands = [ # simpleCommands = [
[ "AT+HTTPINIT", 2000 ], # [ "AT+HTTPINIT", 2000 ],
[ "AT+HTTPPARA=\"CID\",\"{0}\"".format(bearerChannel), 1000 ], # [ "AT+HTTPPARA=\"CID\",\"{0}\"".format(bearerChannel), 1000 ],
[ "AT+HTTPPARA=\"URL\",\"{0}:{1}{2}\"".format(server, port, path), 500 ], # [ "AT+HTTPPARA=\"URL\",\"{0}:{1}{2}\"".format(server, port, path), 500 ],
[ "AT+HTTPPARA=\"CONTENT\",\"multipart/form-data\"", 500 ], # [ "AT+HTTPPARA=\"CONTENT\",\"multipart/form-data\"", 500 ],
[ "AT+HTTPPARA=\"UA\",\"{0}\"".format(self.userAgent), 500 ], # [ "AT+HTTPPARA=\"UA\",\"{0}\"".format(self.userAgent), 500 ],
[ "AT+HTTPPARA=\"REDIR\",\"1\"", 500 ], # [ "AT+HTTPPARA=\"REDIR\",\"1\"", 500 ],
[ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 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 #executing commands sequence
if not self.execSimpleCommandsList(simpleCommands): if not self.execSimpleCommandsList(simpleCommands):
return False return False
#uploading data #uploading data
self.logger.debug("uploading HTTP POST data") # self.logger.debug("uploading HTTP POST data")
ret = self.commandAndStdResult( # ret = self.commandAndStdResult(
"AT+HTTPDATA={0},10000".format(len(parameters)), # "AT+HTTPDATA={0},10000".format(len(parameters)),
7000, # 7000,
["DOWNLOAD", "ERROR"] # ["DOWNLOAD", "ERROR"]
) # )
if (ret is None) or (self.lastResult != "DOWNLOAD"): # if (ret is None) or (self.lastResult != "DOWNLOAD"):
self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3])) # self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
return False # return False
self.simpleWriteLn(parameters) 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 from datahandling import Datareporter_Debug3 as Datareporter
import serial import serial
import sys import sys
import json
REPORTIMAGETOURL = "http://10.0.1.4:5010/photo" REPORTIMAGETOURL = "http://10.0.1.4:5010/photo"
LOG_FILE = "log2.txt" 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), # a=binascii.b2a_uu(f)
low_quality_compression_pct=50)
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 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 #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 pass