Skip to content

Commit

Permalink
✨ feat(contral): add alcohol
Browse files Browse the repository at this point in the history
  • Loading branch information
AndPuQing committed Jul 19, 2022
1 parent 6115750 commit a041ef2
Show file tree
Hide file tree
Showing 4 changed files with 364 additions and 40 deletions.
98 changes: 58 additions & 40 deletions Serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@
import time


class Call():
class Call:
def __init__(self, at):
self.at = at
self.port = 1883
self.broker = '119.91.198.5'
self.broker = "119.91.198.5"
self.topic = "/call"
self.client_id = 'SERVER'
self.mapurl = 'http://map.puqing.work/index.html?'
self.client_id = "SERVER"
self.mapurl = "http://map.puqing.work/index.html?"
self.engine = pyttsx3.init()
self.engine.setProperty('rate', 150)
self.dangerVoice = "您好,我是智能汽车辅助系统,您被绑定的驾驶员出现危险情况,请即时确定驾驶员情况,他的位置信息将通过短信发送给您,请注意查收。"
self.engine.setProperty("rate", 180)
self.dangerVoice = (
"您好,我是智能汽车辅助系统,您被绑定的驾驶员出现危险情况,请即时确定驾驶员情况,他的位置信息将通过短信发送给您,请注意查收。"
)
self.client = self.connect_mqtt()
self.subscribe()
self.client.loop_forever()
Expand All @@ -27,12 +29,13 @@ def generateShortLink(self, long_link):
Generate short link
"""
try:
response = requests.get(
'https://ock.cn/api/short?token=62515c3686d74&longurl=' +
long_link)
response = requests.post(
"https://aiu.pub/api/link", data={"url": long_link}
)
response = json.loads(response.text)
if response['code'] == 1000:
return response['data']['short']
print(response)
if response["code"] == 1:
return response["data"]
else:
return None
except Exception as e:
Expand All @@ -47,49 +50,57 @@ def sendDangerMessage(self, contacts, longitude, latitude):
longitude: the longitude of the driver
latitude: the latitude of the driver
"""
short_url = self.generateShortLink(self.mapurl + '(' + str(longitude) +
',' + str(latitude) + ')')
short_url = self.generateShortLink(
self.mapurl + "(" + str(longitude) + "," + str(latitude) + ")"
)
if short_url is not None:
# set the SMS center
# if you want to send message in other place, please change this
self.at.send_at('AT+CSCA="+8613800773500"')
self.at.check_at_resp('OK')
self.at.check_at_resp("OK")

self.at.send_at('AT+CMGF=1')
self.at.check_at_resp('OK')
self.at.send_at("AT+CMGF=1")
self.at.check_at_resp("OK")

self.at.send_at('AT+CMGS="' + contacts + '"')
self.at.check_at_resp('>')
self.at.check_at_resp(">")

self.at.send_at('Your bound driver is in danger.')
self.at.send_at('You can find he/she at ' + short_url)
self.at.send_at("Your bound driver is in danger.")
self.at.send_at("You can find he/she at " + short_url)

self.at.send_at_notn('\x1a')
self.at.check_at_resp('OK')
self.at.send_at_notn("\x1a")
self.at.check_at_resp("OK")

def callPhone(self, contacts):
"""
Call the phone
"""
self.at.send_at('ATD' + contacts + ';')
self.at.check_at_resp('OK')
self.at.send_at("ATD" + contacts + ";")
try:
self.at.check_at_resp("OK")
except Exception as e:
print(e)
self.at.close()
self.at = atc(findPort())
self.callPhone(contacts)
# self.at.check_at_resp("OK")

start_time = time.time()
while True:
# If the dialed number times out or the call is disconnected,
# the phone will be hang up
if time.time() - start_time >= 30:
self.at.send_at('ATH')
self.at.check_at_resp('OK')
self.at.send_at("ATH")
self.at.check_at_resp("OK")
break
if self.at.check_at_resp('OK'):
print('Ready to speak...')
if self.at.check_at_resp("OK"):
print("Ready to speak...")
i = 0
while i < 3:
# If the call is connected, the phone will speak
self.at.send_at('AT+CLCC')
self.at.send_at("AT+CLCC")
# If the call is disconnected, the phone will be hang up
if self.at.check_at_resp('NO CARRIER') is None:
if self.at.check_at_resp("NO CARRIER") is None:
self.engine.say(self.dangerVoice)
self.engine.runAndWait()
i += 1
Expand All @@ -112,22 +123,29 @@ def subscribe(self):
def on_message(client, userdata, msg):
msg = msg.payload.decode()
json_msg = json.loads(msg)
contacts = json_msg['contacts'].replace('"', '')
longitude = json_msg['longitude']
latitude = json_msg['latitude']
print("The contacts is: ", contacts)
print("The longitude is :", longitude)
print("The latitude is :", latitude)

self.sendDangerMessage(contacts, longitude, latitude)

self.callPhone(contacts)
if len(json_msg) == 3:
contacts = json_msg["contacts"].replace('"', "")
longitude = json_msg["longitude"]
latitude = json_msg["latitude"]
print("The contacts is: ", contacts)
print("The longitude is :", longitude)
print("The latitude is :", latitude)

self.sendDangerMessage(contacts, longitude, latitude)
# sleep 500ms to wait for the message to be sent
time.sleep(0.5)

self.callPhone(contacts)
else:
contacts = json_msg["contacts"]
print("The contacts is: ", contacts)
self.callPhone(contacts)

self.client.subscribe(self.topic)
self.client.on_message = on_message


if __name__ == '__main__':
if __name__ == "__main__":
port = findPort()
if port is None:
print("Can't find the port!")
Expand Down
Binary file modified __pycache__/ATserial.cpython-39.pyc
Binary file not shown.
106 changes: 106 additions & 0 deletions contral.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import numpy as np
import serial
import serial.tools.list_ports
import re
from paho.mqtt import client as mqtt_client
import pyttsx3
import matplotlib.pyplot as plt

# plt.ion()
plt.figure(1)
mngr = plt.get_current_fig_manager()
mngr.window.wm_geometry("+1380+0")
t = np.zeros(10)
i = 0
LAST_STATUS = False
LAST_DATA = 0


class Contral:
def __init__(self):
self.ser = serial.Serial(Contral.findPort(), timeout=1, baudrate=115200)
self.client_id = "contral_client"
self.broker = "broker-cn.emqx.io"
self.port = 1883
self.client = self.connect_mqtt()
self.topic = "/call"
self.engine = pyttsx3.init()
self.engine.setProperty("rate", 180)
self.dangerVoice = "喝酒不开车,开车不喝酒。"
if self.is_open():
print("Serial port is open")
self.run()
else:
print("Serial port is not open")

def __del__(self):
self.ser.close()
self.client.disconnect()

def publish(self):
message = '{"contacts":"18273623931"}'
self.client.publish(self.topic, message)

def connect_mqtt(self):
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)

client = mqtt_client.Client(self.client_id)
client.on_connect = on_connect
client.connect(self.broker, self.port)
return client

def is_open(self):
return self.ser.is_open

def run(self):
global LAST_STATUS, LAST_DATA, t, i
while True:
line = self.ser.readline()
if line:
line.decode("ascii", "ignore")
line = str(line, "utf-8")
line = line.replace("\r\n", "")
data = line[line.find(":") + 1 :]
expression = "".join(re.findall(r"[A-Za-z]", line))
if expression == "alcohol":
print("alcohol-->", float(data))
t = np.roll(t, -1)
t[9] = float(data)
print("t-->", t)
plt.clf()
plt.plot(t, "r")
plt.pause(0.01)
plt.draw()
if (
float(data) > 40
and LAST_STATUS is False
and LAST_DATA < float(data)
):
LAST_STATUS = True
LAST_DATA = float(data)
self.engine.say(self.dangerVoice)
self.engine.runAndWait()
# self.publish()
print("publish")
elif float(data) < 200:
LAST_STATUS = False
LAST_DATA = float(data)
elif float(data) == LAST_DATA:
pass
else:
LAST_DATA = float(data)

def findPort():
ports = serial.tools.list_ports.comports()
for each in ports:
print(each.description)
if "CP210x USB to UART" in each.description:
return each.device


if __name__ == "__main__":
con = Contral()
Loading

0 comments on commit a041ef2

Please sign in to comment.