commit 10/31/2015
This commit is contained in:
@@ -33,7 +33,6 @@ 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.
|
||||
@@ -133,7 +132,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
|
||||
"""
|
||||
return self.print(commandLine, encoding)
|
||||
|
||||
def printLn(self, commandString, bytes=None, encoding = "ascii"):
|
||||
def printLn(self, commandString, encoding = "ascii"):
|
||||
"""
|
||||
Sends string data and CR/LF in the end to the SIM module
|
||||
|
||||
@@ -141,16 +140,33 @@ 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
|
||||
"""
|
||||
if bytes is not None:
|
||||
data = bytearray(commandString, encoding) + bytes + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
if not isinstance(commandString, bytes):
|
||||
data = bytearray(commandString, encoding) + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
else:
|
||||
data= bytearray(commandString, encoding) + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
|
||||
# print("Print Line data: {}".format(data))
|
||||
|
||||
data = commandString + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
return self.__sendRawBytes(data)
|
||||
|
||||
def simpleWriteLn(self, commandLine, bytes=None, encoding = "ascii"):
|
||||
def simpleWriteLns(self, commandLines, encoding = "ascii"):
|
||||
for i, l in enumerate(commandLines):
|
||||
|
||||
if i < len(commandLines)-1:
|
||||
if not isinstance(l, bytes):
|
||||
data = bytearray(l, encoding)
|
||||
else:
|
||||
data = l
|
||||
else:
|
||||
if not isinstance(l, bytes):
|
||||
data = bytearray(l, encoding) + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
else:
|
||||
data = l + bytearray([GsmSpecialCharacters.cr, GsmSpecialCharacters.lf])
|
||||
|
||||
r = self.__sendRawBytes(data)
|
||||
if r is False:
|
||||
return r
|
||||
|
||||
return r
|
||||
|
||||
def simpleWriteLn(self, commandLine, encoding = "ascii"):
|
||||
"""
|
||||
Just alias for printLn() method
|
||||
|
||||
@@ -159,7 +175,7 @@ class SimGsmSerialPortHandler(AminisLastErrorHolderWithLogging):
|
||||
:return: True if data sent, otherwise returns False
|
||||
"""
|
||||
|
||||
return self.printLn(commandLine, encoding=encoding, bytes=bytes)
|
||||
return self.printLn(commandLine, encoding)
|
||||
|
||||
def flushInput(self):
|
||||
"""
|
||||
|
||||
@@ -38,6 +38,10 @@ class SimInetGSMConnection:
|
||||
inetClosing = 2
|
||||
inetClosed = 3
|
||||
|
||||
def chunks(l, n):
|
||||
n = max(1, n)
|
||||
return [l[i:i + n] for i in range(0, len(l), n)]
|
||||
|
||||
class SimInetGSM(SimGsm):
|
||||
def __init__(self, port, logger):
|
||||
SimGsm.__init__(self, port, logger)
|
||||
@@ -172,13 +176,54 @@ class SimInetGSM(SimGsm):
|
||||
#returning GPRS checking sequence
|
||||
return self.checkGprsBearer()
|
||||
|
||||
def disconnectTcp(self):
|
||||
"""
|
||||
Disconnects TCP connection
|
||||
:return:
|
||||
"""
|
||||
def attachCIP(self, apn, user=None, password=None, bearerNumber = 1):
|
||||
"""
|
||||
Attaches GPRS connection for SIM module
|
||||
|
||||
return self.commandAndStdResult("AT+CIPCLOSE", 1000, ["OK"])
|
||||
:param apn: Access Point Name
|
||||
:param user: User name (Login)
|
||||
:param password: Password
|
||||
:param bearerNumber: Bearer number
|
||||
:return: True if everything was OK, otherwise returns False
|
||||
"""
|
||||
|
||||
#checking current connection state
|
||||
# if not self.checkGprsBearer(bearerNumber):
|
||||
# return False
|
||||
#
|
||||
# #going out if already connected
|
||||
# if self.connectionState == SimInetGSMConnection.inetConnected:
|
||||
# return True
|
||||
|
||||
#Closing the GPRS PDP context. We dont care of result
|
||||
self.execSimpleOkCommand("AT+CIPSHUT", 500)
|
||||
|
||||
#initialization sequence for GPRS attaching
|
||||
commands = [
|
||||
["AT+CGATT=1", 1000 ],
|
||||
["AT+CSNS=4,", 500 ],
|
||||
["AT+CSTT=\"{}\",\"{}\",\"{}\"".format(apn, user, password), 500 ],
|
||||
["AT+CIICR", 500 ],
|
||||
["AT+CIFSR", 10000 ]
|
||||
# ["AT+CIPSTART=\"{}\",\"{}\",\"{}\"".format("TCP", {})]
|
||||
]
|
||||
|
||||
#executing commands sequence
|
||||
if not self.execSimpleCommandsList(commands):
|
||||
return False
|
||||
|
||||
return 1
|
||||
|
||||
#returning GPRS checking sequence
|
||||
# return self.checkGprsBearer()
|
||||
|
||||
def disconnectTcp(self):
|
||||
"""
|
||||
Disconnects TCP connection
|
||||
:return:
|
||||
"""
|
||||
|
||||
return self.commandAndStdResult("AT+CIPCLOSE", 1000, ["OK"])
|
||||
|
||||
def dettachGPRS(self, bearerNumber = 1):
|
||||
"""
|
||||
@@ -409,7 +454,7 @@ class SimInetGSM(SimGsm):
|
||||
self.__httpResponse = None
|
||||
self.__httpResult = 0
|
||||
|
||||
def httpPOST(self, server, port, path, parameters, bearerChannel = 1):
|
||||
def httpPOST(self, server, port, path, parameters, contentType="application/x-www-form-urlencoded", bearerChannel = 1):
|
||||
"""
|
||||
Makes HTTP POST request to the given server and script
|
||||
|
||||
@@ -431,10 +476,10 @@ class SimInetGSM(SimGsm):
|
||||
[ "AT+HTTPINIT", 2000 ],
|
||||
[ "AT+HTTPPARA=\"CID\",\"{0}\"".format(bearerChannel), 1000 ],
|
||||
[ "AT+HTTPPARA=\"URL\",\"{0}:{1}{2}\"".format(server, port, path), 500 ],
|
||||
[ "AT+HTTPPARA=\"CONTENT\",\"application/x-www-form-urlencoded\"", 500 ],
|
||||
[ "AT+HTTPPARA=\"CONTENT\",\"{0}\"".format(contentType), 500 ],
|
||||
[ "AT+HTTPPARA=\"UA\",\"{0}\"".format(self.userAgent), 500 ],
|
||||
[ "AT+HTTPPARA=\"REDIR\",\"1\"", 500 ],
|
||||
[ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 500 ]
|
||||
[ "AT+HTTPPARA=\"TIMEOUT\",\"45\"", 500 ],
|
||||
]
|
||||
|
||||
#executing commands sequence
|
||||
@@ -445,7 +490,7 @@ class SimInetGSM(SimGsm):
|
||||
#uploading data
|
||||
self.logger.debug("uploading HTTP POST data")
|
||||
ret = self.commandAndStdResult(
|
||||
"AT+HTTPDATA={0},10000".format(len(parameters)),
|
||||
"AT+HTTPDATA={0},60000".format(len(parameters)),
|
||||
7000,
|
||||
["DOWNLOAD", "ERROR"]
|
||||
)
|
||||
@@ -456,9 +501,14 @@ class SimInetGSM(SimGsm):
|
||||
|
||||
self.simpleWriteLn(parameters)
|
||||
|
||||
dataLine = self.readDataLine(500)
|
||||
# if len(parameters)<32:
|
||||
# self.simpleWriteLn(parameters)
|
||||
# else:
|
||||
# parameters = self.simpleWriteLns(chunks(parameters,32))
|
||||
|
||||
dataLine = self.readDataLine(maxWaitTime=20000)
|
||||
if (dataLine is None) or (dataLine != "OK"):
|
||||
self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
|
||||
self.setError("{0}: can't upload HTTP POST data {1}".format(inspect.stack()[0][3], dataLine))
|
||||
return
|
||||
|
||||
self.logger.debug("actually making request")
|
||||
@@ -512,121 +562,115 @@ class SimInetGSM(SimGsm):
|
||||
#
|
||||
# return True
|
||||
|
||||
def httpPOST_DATA(self, server, port, path, parameters, bearerChannel = 1):
|
||||
"""
|
||||
Makes HTTP POST request to the given server and script
|
||||
#
|
||||
# int res= gsm.read(result, resultlength);
|
||||
# //gsm.disconnectTCP();
|
||||
# return res;
|
||||
|
||||
:param server: server (host) address
|
||||
:param port: server port
|
||||
:param path: path to the script
|
||||
:param parameters: POST parameters
|
||||
:param bearerChannel: bearer channel number
|
||||
:return: true if operation was successfully finished. Otherwise returns false
|
||||
"""
|
||||
def httpPOST_CIP(self, server, port, path, parameters, contentType="application/x-www-form-urlencoded", bearerChannel = 1):
|
||||
"""
|
||||
Makes HTTP POST request to the given server and script
|
||||
|
||||
# self.__clearHttpResponse()
|
||||
:param server: server (host) address
|
||||
:param port: server port
|
||||
:param path: path to the script
|
||||
:param parameters: POST parameters
|
||||
:param bearerChannel: bearer channel number
|
||||
:return: true if operation was successfully finished. Otherwise returns false
|
||||
"""
|
||||
|
||||
#TODO: close only when opened
|
||||
# self.terminateHttpRequest()
|
||||
self.__clearHttpResponse()
|
||||
|
||||
#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+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"]
|
||||
# )
|
||||
|
||||
# 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)
|
||||
|
||||
dataLine = self.readDataLine(500)
|
||||
if (dataLine is None) or (dataLine != "OK"):
|
||||
self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
|
||||
return
|
||||
|
||||
self.logger.debug("actually making request")
|
||||
|
||||
#TODO: check CPU utilization
|
||||
if not self.execSimpleOkCommand("AT+HTTPACTION=1", 15000):
|
||||
return False
|
||||
|
||||
#reading HTTP request result
|
||||
dataLine = self.readDataLine(15000)
|
||||
|
||||
if dataLine is None:
|
||||
self.setError("{0}: empty HTTP request result string".format(inspect.stack()[0][3]))
|
||||
return False
|
||||
|
||||
#parsing string like this "+HTTPACTION:0,200,15"
|
||||
httpResult = self.__parseHttpResult(dataLine, bearerChannel)
|
||||
if httpResult is None:
|
||||
return False
|
||||
|
||||
#assigning HTTP result code
|
||||
self.__httpResult = httpResult[0]
|
||||
|
||||
#it's can be bad http code, let's check it
|
||||
if not self.___isOkHttpResponseCode(self.httpResult):
|
||||
#TODO: close only when opened
|
||||
self.terminateHttpRequest()
|
||||
|
||||
#HTTP POST request commands sequence
|
||||
simpleCommands = [
|
||||
# ["AT+CGATT=1", 1000 ],
|
||||
# ["AT+CSNS=4,", 500 ],
|
||||
# ["AT+CSTT=\"{}\",\"{}\",\"{}\"".format("wholesale", "", ""), 500 ],
|
||||
# ["AT+CIICR", 500 ],
|
||||
# ["AT+CIFSR", 10000 ]
|
||||
[ "AT+CIPSTART=\"TCP\",\"{0}{2}\",\"{1}\"".format(server, port, path), 500 ],
|
||||
[ "AT+CIPSEND=", 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"]
|
||||
# )
|
||||
|
||||
# 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)
|
||||
|
||||
dataLine = self.readDataLine(500)
|
||||
if (dataLine is None) or (dataLine != "OK"):
|
||||
self.setError("{0}: can't upload HTTP POST data".format(inspect.stack()[0][3]))
|
||||
return
|
||||
|
||||
# self.logger.debug("actually making request")
|
||||
|
||||
# #TODO: check CPU utilization
|
||||
# if not self.execSimpleOkCommand("AT+HTTPACTION=1", 15000):
|
||||
# return False
|
||||
|
||||
#reading HTTP request result
|
||||
dataLine = self.readDataLine(15000)
|
||||
|
||||
if dataLine is None:
|
||||
self.setError("{0}: empty HTTP request result string".format(inspect.stack()[0][3]))
|
||||
return False
|
||||
|
||||
#parsing string like this "+HTTPACTION:0,200,15"
|
||||
httpResult = self.__parseHttpResult(dataLine, bearerChannel)
|
||||
if httpResult is None:
|
||||
return False
|
||||
|
||||
#assigning HTTP result code
|
||||
self.__httpResult = httpResult[0]
|
||||
|
||||
#it's can be bad http code, let's check it
|
||||
if not self.___isOkHttpResponseCode(self.httpResult):
|
||||
self.terminateHttpRequest()
|
||||
return True
|
||||
|
||||
#when no data from server we just want go out, everything if OK
|
||||
if (
|
||||
(self.__isNoContentResponse(self.httpResult)) or
|
||||
(not self.___isHttpResponseCodeReturnsData(self.httpResult))
|
||||
):
|
||||
self.terminateHttpRequest()
|
||||
return True
|
||||
|
||||
responseLength = httpResult[1]
|
||||
if responseLength == 0:
|
||||
self.terminateHttpRequest()
|
||||
return True
|
||||
|
||||
self.logger.debug("reading http request response data")
|
||||
|
||||
if not self.__readHttpResponse(0, responseLength):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
#when no data from server we just want go out, everything if OK
|
||||
if (
|
||||
(self.__isNoContentResponse(self.httpResult)) or
|
||||
(not self.___isHttpResponseCodeReturnsData(self.httpResult))
|
||||
):
|
||||
self.terminateHttpRequest()
|
||||
return True
|
||||
|
||||
responseLength = httpResult[1]
|
||||
if responseLength == 0:
|
||||
self.terminateHttpRequest()
|
||||
return True
|
||||
# self.disconnectTcp()
|
||||
#
|
||||
# return True
|
||||
|
||||
self.logger.debug("reading http request response data")
|
||||
|
||||
if not self.__readHttpResponse(0, responseLength):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# self.disconnectTcp()
|
||||
#
|
||||
# return True
|
||||
|
||||
|
||||
#
|
||||
# int res= gsm.read(result, resultlength);
|
||||
# //gsm.disconnectTCP();
|
||||
# return res;
|
||||
#
|
||||
# int res= gsm.read(result, resultlength);
|
||||
# //gsm.disconnectTCP();
|
||||
# return res;
|
||||
Reference in New Issue
Block a user