This commit is contained in:
Cyberes 2024-06-30 18:53:08 -06:00
parent 50ddf2c72e
commit a7ff402b77
1 changed files with 68 additions and 35 deletions

View File

@ -5,7 +5,7 @@ import time
import machine
from machine import Pin
from config import CELLULAR_APN, CELLULAR_STARTUP_TIMEOUT, TRACCAR_CONN_MODE
from config import CELLULAR_APN, CELLULAR_STARTUP_TIMEOUT, TRACCAR_HOST
from lib.logging import logger, LogLevel
from lib.runtime import timeout, uTimeoutError, run_with_timeout
@ -51,12 +51,12 @@ class CellularModem:
await self.swriter.awrite(f'{command}\r\n')
for i in range(10):
raw_line = await self.sreader.readline()
print(raw_line)
if len(raw_line.decode().strip('\r\n')) > 0 and raw_line != f'{command}\r\r\n'.encode():
lines.append(raw_line)
if raw_line == b'ERROR\r\n':
raise ModemErrorResponse(code=(command, lines))
if len(lines):
print(raw_line)
if expecing_plus:
if lines[-1].decode().startswith('+'):
break
@ -121,6 +121,7 @@ async def cellular_wait_cpsi():
async def cellular_wait_creg():
# https://community.hologram.io/t/sim7600-in-ovms-board-t-mobile-registration-denied/4616/12
async def check():
resp = await cellular.send_command('AT+CREG?')
if len(resp) == 2 and resp[0].startswith('+CREG: '):
@ -220,7 +221,7 @@ async def start_modem():
for cmd in cmds:
while True:
init_resp = await cellular.send_command(cmd)
logger('\n'.join((x for x in init_resp if x != 'OK')), source='CELL', level=LogLevel.error)
logger('\n'.join((x for x in init_resp if x != 'OK')), source='CELL', level=LogLevel.info)
if init_resp[-1] != 'OK':
await asyncio.sleep(0.1)
else:
@ -252,10 +253,10 @@ async def start_modem():
continue
try:
await cellular.send_command(f'AT+CGSOCKCONT=1,"IP","{CELLULAR_APN}"', require_ok=True)
await cellular.send_command(f'AT+CGDCONT=1,"IP","{CELLULAR_APN}"', require_ok=True)
await cellular.send_command('AT+CSOCKSETPN=1', require_ok=True)
await cellular.send_command('AT+CIPMODE=0', require_ok=True)
# await cellular.send_command('AT+CNMP=38', require_ok=True)
await cellular.send_command('AT+CNMP=38', require_ok=True)
await cellular.send_command('AT+NETOPEN', require_ok=True)
break
except ModemErrorResponse as e:
@ -274,8 +275,21 @@ async def start_modem():
async def cellular_start_http():
if TRACCAR_HOST.startswith('http://'):
code = 'AT+HTTPINIT'
elif TRACCAR_HOST.startswith('https://'):
code = 'AT+CCHSTART'
else:
raise Exception
try:
await cellular.send_command('AT+HTTPINIT')
if TRACCAR_HOST.startswith('https://'):
await cellular.send_command('AT+CSSLCFG="sslversion",0,4')
await cellular.send_command('AT+CSSLCFG="authmode",0,0')
await cellular.send_command('AT+CSSLCFG="ignorelocaltime",0,1')
await cellular.send_command('AT+CSSLCFG="enableSNI",0,1')
await cellular.send_command('AT+CCHSET=1')
await cellular.send_command('AT+CCHSSLCFG=0,0')
await cellular.send_command(code)
return True
except ModemErrorResponse:
return False
@ -292,25 +306,6 @@ async def start_modem_task():
except uTimeoutError:
await asyncio.sleep(10)
continue
if TRACCAR_CONN_MODE == 'http':
await asyncio.sleep(0.5)
success = False
for i in range(30):
httpinit = await run_with_timeout(func=cellular_start_http, timeout_sec=5)
if httpinit.failure:
logger('AT+HTTPINIT timeout', source='CELL', level=LogLevel.error)
await restart_modem()
continue
if not httpinit.result:
logger('AT+HTTPINIT failure', source='CELL', level=LogLevel.error)
await restart_modem()
continue
else:
success = True
if not success:
continue
break
while True:
@ -320,12 +315,17 @@ async def start_modem_task():
gc.collect()
await cellular_send_http('http://postman-echo.com/ip', 'get')
cellular.uart.write('AT+CIPOPEN=0,"UDP","64.227.105.164",10001,8000')
data = 'Hello!!'
cellular.uart.write(f'AT+CIPSEND=0,{len(data.encode())},"64.227.105.164",10001')
await asyncio.sleep(0.1)
cellular.uart.write(data)
await cellular.send_command('AT+CIPCLOSE=0')
# TODO: loop to reconnect modem
@timeout(10)
@timeout(30)
async def cellular_send_http(url: str, method: str, data: str = None):
m = method.upper()
if m == 'GET':
@ -337,22 +337,55 @@ async def cellular_send_http(url: str, method: str, data: str = None):
else:
raise Exception
await cellular.send_command(f'AT+HTTPPARA="URL","{url}"')
_, resp = await cellular.send_command(f'AT+HTTPACTION={mode}', expecing_plus=True)
# for i in range(30):
# httpinit = await run_with_timeout(func=cellular_start_http, timeout_sec=5)
# if httpinit.failure:
# # logger('AT+HTTPINIT timeout', source='CELL', level=LogLevel.error)
# await restart_modem()
# continue
# if not httpinit.result:
# # logger('AT+HTTPINIT failure', source='CELL', level=LogLevel.error)
# await cellular.send_command('AT+CRESET')
# # await restart_modem()
# # break
_, status_code, data_len = resp.strip('+HTTPACTION: ').split(',')
if status_code != '200':
logger(f'HTTP {m} failed: {status_code}', source='CELL', level=LogLevel.error)
return
await cellular_start_http()
if TRACCAR_HOST.startswith('http://'):
await cellular.send_command(f'AT+HTTPPARA="URL","{url}"')
_, resp = await cellular.send_command(f'AT+HTTPACTION={mode}', expecing_plus=True)
_, status_code, data_len = resp.strip('+HTTPACTION: ').split(',')
if status_code != '200':
logger(f'HTTP {m} failed: {status_code}', source='CELL', level=LogLevel.error)
return
data = await cellular.send_command(f'AT+HTTPREAD={data_len}', read_until=b'+HTTPREAD:0\r\n', clean_lines=False)
elif TRACCAR_HOST.startswith('https://'):
# HTTPS does not work.
# ModemErrorResponse: Modem returned an error: ('AT+CCHOPEN=0,"postman-echo.com",443,2', [b'ERROR\r\n'])
parts = url.replace('https://', '', 1).split('/')
host = parts.pop(0)
path = '/' + '/'.join(parts)
await cellular.send_command(f'AT+CCHOPEN=0,"{host}",443,2')
content = f"""GET {path} HTTP/1.1
Host: {host}
User-Agent: Freematics
Proxy-Connection: keep-alive
Content-Length: 0"""
await cellular.send_command(f'AT+CCHSEND=0,{len(content.encode())}')
resp = await cellular.send_command('AT+CCHRECV=0', read_until=b'+CCHRECV: 0,0\r\n')
print(resp)
else:
raise Exception
data = await cellular.send_command(f'AT+HTTPREAD={data_len}', read_until=b'+HTTPREAD:0\r\n', clean_lines=False)
if data[0] != b'OK\r\n':
raise Exception
data = list(data)
del data[0]
del data[0]
del data[-1]
print(data)
data_clean = ''.join([x.decode() for x in data]).strip('\r\n')
return data_clean
asyncio.run(start_modem_task())