Compare commits

..

No commits in common. 'master' and 'simulator-backend' have entirely different histories.

53
.gitignore vendored

@ -1,53 +0,0 @@
# ---> Eagle
# Ignore list for Eagle, a PCB layout tool
# Backup files
*.s#?
*.b#?
*.l#?
*.b$?
*.s$?
*.l$?
# Eagle project file
# It contains a serial number and references to the file structure
# on your computer.
# comment the following line if you want to have your project file included.
eagle.epf
# Autorouter files
*.pro
*.job
# CAM files
*.$$$
*.cmp
*.ly2
*.l15
*.sol
*.plc
*.stc
*.sts
*.crc
*.crs
*.dri
*.drl
*.gpi
*.pls
*.ger
*.xln
*.drd
*.drd.*
*.s#*
*.b#*
*.info
*.eps
# file locks introduced since 7.x
*.lck

@ -1,208 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution
as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct
or indirect, to cause the direction or management of such entity, whether
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the Appendix
below).
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative
Works thereof, that is intentionally submitted to Licensor for inclusion in
the Work by the copyright owner or by an individual or Legal Entity authorized
to submit on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently incorporated
within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise
transfer the Work, where such license applies only to those patent claims
licensable by such Contributor that are necessarily infringed by their Contribution(s)
alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses granted to You
under this License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy
of this License; and
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source
form of the Work, excluding those notices that do not pertain to any part
of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction,
or distribution of Your modifications, or for any such Derivative Works as
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -1,19 +0,0 @@
#### 从命令行创建一个新的仓库
```bash
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://bdgit.educoder.net/pa4hzw8mg/MySmartHome.git
git push -u origin master
```
#### 从命令行推送已经创建的仓库
```bash
git remote add origin https://bdgit.educoder.net/pa4hzw8mg/MySmartHome.git
git push -u origin master
```

BIN
c2t/c2t/.DS_Store vendored

Binary file not shown.

@ -0,0 +1,21 @@
air.humidity should increase->humidifier.hon
allow sweeping the floor->vacuum.von
allow monitoring the room->camera.con
forbid monitoring the room->camera.coff
s:TemperatureSensor->air.temperature
s:HumiditySensor->air.humidity
s:LightSensor->light.brightness
s:CO2Sensor->co2.ppm
s:InfraredSensor->person.number
s:InfraredSensor->person.distancefrommc
s:InfraredSensor->person.distancefrompro
s:RainSensor->weather.raining
r:ac.coldon->power=700//cooler=1
r:ac.hoton->power=1500//heater=1
r:mc.mon->power=20
r:projector.pon->power=350
r:light.lon->power=5
r:af.afon->power=500
r:ah.ahon->power=500
r:fan.fon->power=15//cooler=1
r:heater.hon->power=2000//heater=1

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,420 @@
import snowboydecoder
import signal
import wave
import sys
import json
import requests
import time
import os
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
from fetchToken import fetch_token
import time
import unicodedata
import math
import pickle
import Levenshtein
import cn2an
import pypinyin
import re
import retrieval
IS_PY3 = sys.version_info.major == 3
interrupted = False # snowboy监听唤醒结束标志
endSnow = False # 程序结束标志
framerate = 16000 # 采样率
num_samples = 2000 # 采样点
channels = 1 # 声道
sampwidth = 2 # 采样宽度2bytes
pid = ''
music_exit = 'audio/exit.wav' # 唤醒系统退出语音
music_open = 'audio/open.wav' # 唤醒系统打开语音
music_alarm = 'audio/alarm.wav'
music_listen = 'audio/listen.wav'
music_over = 'audio/over.wav'
FILEPATH = 'audio/audio.wav'
MAPPATH = 'cemap.txt'
DEVICEPATH = 'my-case-study.properties'
SRC = 'ChineseRequirements.txt'
requirementTexts = ''
# os.close(sys.stderr.fileno()) # 去掉错误警告
def speech2text(speech_data, token, dev_pid=1537):
"""
音频转文字
"""
FORMAT = 'wav'
RATE = '16000'
CHANNEL = 1
CUID = 'baidu_workshop'
SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid': dev_pid
}
# 语音转文字接口 该接口可能每个人不一样,取决于你需要哪种语音识别功能,本文使用的是 语音识别极速版
url = 'https://vop.baidu.com/pro_api'
headers = {'Content-Type': 'application/json'} # 请求头
print('正在识别...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
return Result
def get_audio(file):
"""
获取音频文件
"""
with open(file, 'rb') as f:
data = f.read()
return data
def initDict(mapPath):
d = dict()
for line in open(mapPath, 'r'):
if line.find('->') != -1:
d[line.split('->')[0]] = line.split('->')[1]
return d
def getValue(tempValue):
value = ''
for char in tempValue:
if is_number(char):
value = value + char
return value
def is_number(s):
try: # 如果能运行float(s)语句返回True字符串s是浮点数
float(s)
return True
except ValueError: # ValueError为Python的一种标准异常表示"传入无效的参数"
pass # 如果引发了ValueError这种异常不做任何事情pass不做任何事情一般用做占位语句
try:
import unicodedata # 处理ASCii码的包
unicodedata.numeric(s) # 把一个表示数字的字符串转换为浮点数返回的函数
return True
except (TypeError, ValueError):
pass
return False
def getTrigger(trigger, d):
if trigger.find("") == -1:
if trigger in d:
trigger = d[trigger]
else:
if trigger.find('高于') != -1:
attribute = trigger.split("高于")[0]
tempValue = trigger.split("高于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + ">" + value
elif trigger.find('低于') != -1:
attribute = trigger.split("低于")[0]
tempValue = trigger.split("低于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + "<" + value
elif trigger.find('等于') != -1:
attribute = trigger.split("等于")[0]
tempValue = trigger.split("等于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + "=" + value
else:
trigger1 = trigger.split('')[0]
trigger2 = trigger.split('')[1]
trigger = getTrigger(trigger1, d) + " AND " + getTrigger(trigger2,d)
return trigger.strip()
def check_contain_chinese(check_str):
for ch in check_str.decode('utf-8'):
if u'\u4e00' <= ch <= u'\u9fff':
return True
return False
def sound2TAP(filePath):
#文件格式wav
#channels = 1 # 声道
#framerate = 16000 # 采样率
#num_samples = 2000 # 采样点
#sampwidth = 2 # 采样宽度2bytes
TOKEN = fetch_token() # 获取token
speech = get_audio(FILEPATH)
chinese = speech2text(speech, TOKEN, int(80001))
r = retrieval.Retrieval()
chinese_modified = r.retrieve(chinese)
eRequirements = c2e(chinese_modified).strip()
return eRequirements
def c2e(cRequirement):
cemap = initDict(MAPPATH)
rooms = ["客厅", "玄关"]
result = []
cRequirement = str(cRequirement)
cRequirement = cRequirement.replace("","")
cRequirement = cRequirement.replace("", "")
cRequirement = cRequirement.replace("", "")
cRequirement = cRequirement.replace("", "")
eRequirement = ''
room = ''
for temp in rooms:
if cRequirement.startswith(temp):
room = temp
cRequirement = cRequirement[cRequirement.index(room) + len(room):]
break
if room != '':
room = cemap[room].strip()
result.append(toTAP(cRequirement, room))
else:
for temp in rooms:
room = cemap[temp].strip()
result.append(toTAP(cRequirement, room))
return result
def toTAP(cRequirement, room):
cemap = initDict(MAPPATH)
devices = []
d = dict()
devices = []
for line in open(DEVICEPATH, 'r'):
if line.startswith('device'):
temp = line[line.find('{') + 1:line.find('}')]
attributes = temp.split(',')
deviceName = attributes[0].split(':')[1]
deviceType = attributes[1].split(':')[1]
location = attributes[2].split(':')[1]
d[deviceType + '//' + location] = deviceName
devices.append(deviceType)
rooms = ["客厅", "玄关"]
trigger = getTrigger(cRequirement.split("")[0], cemap).strip()
triggerRoom = room
if trigger.split('.')[0] in devices:
if not trigger.split('.')[0] + '//' + room in d:
return
trigger = d[trigger.split('.')[0] + '//' + room] + '.' + trigger.split('.')[1]
action = cRequirement.split("")[1].strip()
actionRoom = ''
actionRoomFlag = False
for temp in rooms:
if action.startswith(temp):
actionRoomFlag = True
actionRoom = cemap[temp.strip()].strip()
action = cemap[action[action.index(temp) + len(temp):]]
if action.split('.')[0] in devices:
if not action.split('.')[0] + '//' + actionRoom in d:
return
action = d[action.split('.')[0] + '//' + actionRoom] + '.' + action.split('.')[1]
break
if not actionRoomFlag:
actionRoom = triggerRoom
action = cemap[action]
if action.split('.')[0] in devices:
if not action.split('.')[0] + '//' + actionRoom in d:
return
action = d[action.split('.')[0] + '//' + actionRoom] + '.' + action.split('.')[1]
return "IF " + trigger + " THEN " + action;
place_list = ['卧室一', '卧室二', '卧室', '厕所一', '厕所二', '厕所', '走廊', '餐厅', '客厅', '厨房', '书房', '阳台', '户外', '屋内']
action_list = ['关灯', '开灯', '灯变亮', '灯变暗', '开热空调', '开冷空调', '空调升温', '空调降温', '关空调', '开电视', '发出警告', '开窗帘', '关窗帘', '开窗', '关窗',
'开门', '关门', '开氛围灯', '关氛围灯', '亮一点', '暗一点', '热一点', '冷一点', '温度高一点', '温度低一点', '允许通风',
'禁止通风', '开启回家模式', '开启离家模式', '开启观影模式']
trigger_list = ['下雨', '不下雨', '天晴', '有人', '按门铃', '没人', '有人移动', '没人移动', '着火', '起风', '起烟', '天黑', '灯打开', '灯关闭', '门打开',
'门关闭', '窗打开', '窗关闭', '窗帘打开', '窗帘关闭', '空调制冷', '空调制热', '空调关闭', '电视打开', '电视关闭']
time_list = ['超过?小时', '超过?分钟', '超过?秒']
re_chn = re.compile("([\u4E00-\u9Fa5a-zA-Z0-9+#&]+)")
def chn_to_arabic(text: str):
chn_numbers = re.findall(r'.*超过(.+)(秒|分钟|小时)时', text)
if len(chn_numbers) > 0:
arabic_number = cn2an.transform(chn_numbers[0][0], 'cn2an')
return text.replace('超过' + ''.join(chn_numbers[0]) + '', '超过' + str(arabic_number) + chn_numbers[0][1] + '')
else:
return text
def text_extract(sent: str):
text = ""
blks = re_chn.split(sent)
for blk in blks:
if not blk:
continue
if re_chn.match(blk):
text += blk
return text
def num_extract(text: str):
return re.sub(r'[\d]+', '', text), re.findall(r'[\d]+', text)
class Retrieval(object):
def __init__(self):
self.map_length_to_sent_and_pinyin = {}
self.initialized = False
def _initialize(self):
for action in action_list:
sent = action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for action in action_list:
sent = trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for action in action_list:
sent = place_one + trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + time + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = place_one + trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + time + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
self.initialized = True
def save_sent_data(self):
self._initialize()
with open('data/sent_data.pickle', 'wb+') as f:
pickle.dump(self.map_length_to_sent_and_pinyin, f, pickle.DEFAULT_PROTOCOL)
def load_sent_data(self):
with open('data/sent_data.pickle', 'rb') as f:
self.map_length_to_sent_and_pinyin = pickle.load(f)
self.initialized = True
def retrieve(self, sent):
if not sent:
return sent
text = text_extract(sent)
text = chn_to_arabic(text)
text, nums = num_extract(text)
number = ''
if len(nums) > 0:
number = nums[0]
if not text:
return text
if not self.initialized:
self.load_sent_data()
sent_pinyin = pypinyin.slug(text, separator='')
length = len(sent_pinyin)
interval = 10
top_sent = text
min_distance = math.inf
for cl in range(max(0, length - interval), length + interval):
if cl in self.map_length_to_sent_and_pinyin:
pair_list = self.map_length_to_sent_and_pinyin[cl]
for pair in pair_list:
distance = Levenshtein.distance(pair[0], sent_pinyin)
if min_distance > distance:
min_distance = distance
top_sent = pair[1]
res = top_sent.replace('超过?', '超过' + number)
return res
INPUTFILEPATH = src = sys.argv[1]
print(sound2TAP(INPUTFILEPATH))

@ -0,0 +1,58 @@
客厅->living_room
玄关->entryway
屋内->home
温度->temperature
湿度->humidity
亮度->brightness
二氧化碳浓度->co2ppm
关灯->Bulb.turn_bulb_off
开灯->Bulb.turn_bulb_on
开冷空调->AirConditioner.turn_ac_cool
开热空调->AirConditioner.turn_ac_heat
关空调->AirConditioner.turn_ac_off
开门->Door.open_door
关门->Door.close_door
开窗->Window.open_window
关窗->Window.close_window
开窗帘->Blind.open_blind
关窗帘->Blind.close_blind
关闭空气净化器->AirPurifier.turn_ap_off
打开空气净化器->AirPurifier.turn_ap_on
关闭加湿器->Humidifier.turn_hum_off
打开加湿器->Humidifier.turn_hum_on
关闭干燥器->Dehumidifier_0.turn_dehum_off
打开干燥器->Dehumidifier_0.turn_dehum_on
关电扇->Fan.turn_fan_off
开电扇->Fan.turn_fan_on
启动扫地机器人->Robot.start_robot
停止扫地机器人->Robot.dock_robot
允许监视室内->Camera.turn_camera_on
禁止监视室内->Camera.turn_camera_off
二氧化碳浓度需要降低->co2.ppm-
天黑->brightness<50
有人->NOT_Person.Out
没人->Person.Out
下雨->Rain.isRain
灯打开->Bulb.bon
灯关闭->Bulb.boff
门打开->Door.dopen
门关闭->Door.dclosed
窗打开->Window.wopen
窗关闭->Window.wclosed
窗帘打开->Blind.bopen
窗帘关闭->Blind.bclosed
空调制冷->AirConditioner.cool
空调制热->AirConditioner.heat
空调关闭->AirConditioner.acoff
空气净化器关闭->AirPurifier.apoff
空气净化器打开->AirPurifier.apon
加湿器关闭->Humidifier.hoff
加湿器打开->Humidifier.hon
干燥器关闭->Dehumidifier.dhoff
干燥器打开->Dehumidifier.dhon
电扇关闭->Fan.foff
电扇打开->Fan.fon
扫地机器人启动->Robot.roff
扫地机器人停止->Robot.ron
摄像头关闭->Camera.coff
摄像头打开->Camera.con

@ -0,0 +1,20 @@
#d:domain->event->state->service->type->effect
#s:binary->device_class->monitored entity->true type->false type
#s:numeric->device_class->monitored entity
d:light->lturnon->lon->turn_on->turned_on->light.brightness+
d:light->lturnoff->loff->turn_off->turned_off->light.brightness-
d:fan.fan->fturnon->fon->turn_on->turned_on->air.temperature-
d:fan.fan->fturnoff->foff->turn_off->turned_off->air.temperature+
d:fan.humidifier->hturnon->hon->turn_on->turned_on->air.humidity+
d:fan.humidifier->hturnoff->hoff->turn_off->turned_off->air.humidity-
d:fan.purifier->pturnon->pon->turn_on->turned_on->CO2.ppm-
d:fan.purifier->pturnoff->poff->turn_off->turned_off->CO2.ppm+
d:vacuum->vturnon->von->start->null->null
d:vacuum->vturnoff->voff->stop->null->null
d:camera->cturnon->con->turn_on->turned_on->null
d:camera->cturnoff->coff->turn_off->turned_off->null
s:binary->opening->door.open->opened->not_opened
s:binary->motion->person.in->motion->no_motion
s:numeric->temperature->air.temperature
s:numeric->illuminance->light.brightness
s:numeric->humidity->air.humidity

@ -0,0 +1,57 @@
import sys
import json
# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.parse import quote_plus
else:
import urllib2
from urllib import quote_plus
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
from urllib import urlencode
# 替换你的 API_KEY
API_KEY = 'uhKo4AmwYbRmgmR4So7jAQsV'
# 替换你的 SECRET_KEY
SECRET_KEY = 'oA56u220ScasGhy2dQ3UBSksNq4Oc2W0'
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
def fetch_token():
params = {'grant_type': 'client_credentials',
'client_id': API_KEY,
'client_secret': SECRET_KEY}
post_data = urlencode(params)
if (IS_PY3):
post_data = post_data.encode('utf-8')
req = Request(TOKEN_URL, post_data)
try:
f = urlopen(req, timeout=5)
result_str = f.read()
except URLError as err:
print('token http response http code : ' + str(err.code))
result_str = err.read()
if (IS_PY3):
result_str = result_str.decode()
result = json.loads(result_str)
if ('access_token' in result.keys() and 'scope' in result.keys()):
if not 'audio_tts_post' in result['scope'].split(' '):
print ('please ensure has check the tts ability')
return ''
return result['access_token']
else:
print ('please overwrite the correct API_KEY and SECRET_KEY')
return ''

@ -0,0 +1,3 @@
living room->living room
entryway->entryway
home->entryway,living room

@ -0,0 +1,40 @@
IF temperature<=15 THEN AirConditioner_0.turn_ac_heat
IF temperature>=28 THEN AirConditioner_0.turn_ac_cool,Heater_0.turn_heat_off
IF Person.Location1 AND temperature>25 THEN AirConditioner_0.turn_ac_cool
IF Person.Location1 AND temperature<25 THEN AirConditioner_0.turn_ac_heat
IF humidity<20 THEN Humidifier_0.turn_hum_on,Dehumidifier_0.turn_dehum_off
IF Person.Location1 THEN Bulb_0.turn_bulb_on,Bulb_1.turn_bulb_on
IF Person.Location1 THEN Window_1.open_window,Window_2.open_window
IF Person.Location1 THEN TV_0.turn_tv_on
IF TV_0.tvon THEN Bulb_0.turn_bulb_on,Bulb_1.turn_bulb_on
IF Person.Location2 THEN Bulb_2.turn_bulb_on,Bulb_3.turn_bulb_on,Window_3.open_window
IF Person.Location4 THEN Bulb_6.turn_bulb_on,Bulb_7.turn_bulb_on,Window_0.open_window
IF Person.Location3 THEN Bulb_4.turn_bulb_on,Bulb_5.turn_bulb_on
IF Person.Location5 THEN Bulb_8.turn_bulb_on,Window_4.open_window
IF Person.Out THEN Bulb_0.turn_bulb_off,Bulb_1.turn_bulb_off,Bulb_2.turn_bulb_off,Bulb_3.turn_bulb_off,Bulb_4.turn_bulb_off,Bulb_5.turn_bulb_off
IF Person.Out THEN Window_0.close_window,Window_1.close_window,Window_2.close_window,Window_3.close_window,Window_4.close_window
IF Person.Out THEN AirConditioner_0.turn_ac_off,Humidifier_0.turn_hum_off,Fan_0.turn_fan_off,TV_0.turn_tv_off
IF Rain.isRain THEN Window_0.close_window,Window_1.close_window,Window_2.close_window,Window_3.close_window
IF AirConditioner_0.cool THEN Window_0.close_window,Window_1.close_window,Window_2.close_window,Window_3.close_window,Window_4.close_window
IF AirConditioner_0.heat THEN Window_0.close_window,Window_1.close_window,Window_2.close_window,Window_3.close_window,Window_4.close_window
IF Wind.Gale THEN Window_3.close_window
IF Person.Out THEN Robot_0.dock_robot
IF NOT_Person.Out THEN Robot_0.start_robot
IF humidity>50 THEN Humidifier_0.turn_hum_off
IF Fire.OnFire THEN Alarm_0.turn_alarm_on
IF Fire.NoFire THEN Alarm_0.turn_alarm_off
IF co2ppm>800 THEN AirPurifier_0.turn_ap_on
IF pm_2_5>75 THEN AirPurifier_0.turn_ap_on
IF aqi>=150 THEN Window_0.close_window,Window_1.close_window,Window_2.close_window,Window_3.close_window
IF co2ppm<400 AND pm_2_5<20 THEN AirPurifier_0.turn_ap_off
IF NOT_Person.Location1 THEN Bulb_0.turn_bulb_off,Bulb_1.turn_bulb_off,Window_1.close_window,Window_2.close_window
IF NOT_Person.Location1 THEN TV_0.turn_tv_off
IF NOT_Person.Location2 THEN Bulb_2.turn_bulb_off,Bulb_3.turn_bulb_off
IF NOT_Person.Location4 THEN Bulb_6.turn_bulb_off,Bulb_7.turn_bulb_off,Window_0.close_window
IF NOT_Person.Location3 THEN Bulb_4.turn_bulb_off,Bulb_5.turn_bulb_off
IF NOT_Person.Location5 THEN Bulb_8.turn_bulb_off
IF NOT_Person.Out THEN Blind_0.open_blind,Blind_1.open_blind
IF temperature<10 THEN Heater_0.turn_heat_on
IF humidity>75 THEN Dehumidifier_0.turn_dehum_on,Humidifier_0.turn_hum_off
IF Door_0.dopen THEN Camera_0.turn_camera_on

@ -0,0 +1,16 @@
location={living_room,entryway}
device1={deviceName:Bulb_0,deviceType:Bulb,location:living_room}
device2={deviceName:Bulb_1,deviceType:Bulb,location:entryway}
device3={deviceName:Window_0,deviceType:Window,location:living_room}
device4={deviceName:Window_1,deviceType:Window,location:entryway}
device5={deviceName:AirConditioner_0,deviceType:AirConditioner,location:living_room}
device6={deviceName:Blind_0,deviceType:Blind,location:living_room}
device7={deviceName:Blind_1,deviceType:Blind,location:entryway}
device8={deviceName:TV_0,deviceType:TV,location:living_room}
device9={deviceName:Door_0,deviceType:Door,location:entryway}
device10={deviceName:Dehumidifier_0,deviceType:Dehumidifier,location:living_room}
device11={deviceName:Fan_0,deviceType:Fan,location:living_room}
device12={deviceName:Humidifier_0,deviceType:Humidifier,location:living_room}
device13={deviceName:Camera_0,deviceType:Camera,location:entryway}
device14={deviceName:Robot_0,deviceType:Robot,location:living_room}
device15={deviceName:AirPurifier_0,deviceType:AirPurifier,location:living_room}

@ -0,0 +1,229 @@
<?xml version="1.0" encoding="utf-8"?>
<ontology>
<environment>
<attribute name="person.number"/>
<attribute name="air.temperature"/>
<attribute name="air.humidity"/>
<attribute name="air.smoke"/>
<attribute name="light.brightness"/>
<attribute name="sound.loudness"/>
<attribute name="sound.ultrasonic"/>
<attribute name="co2.ppm"/>
</environment>
<devices>
<device name="bulb">
<states>
<state name="bon" init="false">
<adjust_entity name="light.brightness" energy="5" rate="50000" method="prompt"/>
</state>
</states>
</device>
<device name="heater">
<states>
<state name="hon" init="false">
<adjust_entity name="air.temperature" energy="2000" rate="0.4" method="/second"/>
</state>
</states>
</device>
<device name="ac">
<states>
<state name="coldon" init="false">
<adjust_entity name="air.temperature" energy="700" rate="-0.2" method="/second"/>
</state>
<state name="hoton" init="false">
<adjust_entity name="air.temperature" energy="1500" rate="0.2" method="/second"/>
</state>
</states>
</device>
<device name="fan">
<states>
<state name="fon" init="false">
<adjust_entity name="air.temperature" energy="30" rate="-0.05" method="/second"/>
</state>
</states>
</device>
<device name="af">
<states>
<state name="afon" init="false">
<adjust_entity name="co2.ppm" energy="500" rate="-10" method="/second"/>
</state>
</states>
</device>
<device name="ah">
<states>
<state name="ahon" init="false">
<adjust_entity name="air.humidity" energy="500" rate="0.2" method="/second"/>
</state>
</states>
</device>
</devices>
<statemachines>
<device name="bulb">
<events>
<event>bturnon</event>
<event>bturnoff</event>
</events>
<states>
<state init="false">bon</state>
<state init="true">boff</state>
</states>
<transitions>
<transition from="bon" event="bturnoff" action="boffpulse" to="boff"/>
<transition from="boff" event="bturnoff" action="boffpulse" to="boff"/>
<transition from="bon" event="bturnon" action="bonpulse" to="bon"/>
<transition from="boff" event="bturnon" action="bonpulse" to="bon"/>
</transitions>
</device>
<device name="blind">
<events>
<event>bopen</event>
<event>bclose</event>
</events>
<states>
<state init="false">bopen</state>
<state init="true">bclosed</state>
</states>
<transitions>
<transition from="bopen" event="bclose" action="bclosepulse" to="bclosed"/>
<transition from="bclosed" event="bclose" action="bclosepulse" to="bclosed"/>
<transition from="bopen" event="bopen" action="bopenpulse" to="bopen"/>
<transition from="bclosed" event="bopen" action="bopenpulse" to="bopen"/>
</transitions>
</device>
<device name="projector">
<events>
<event>pturnon</event>
<event>pturnoff</event>
</events>
<states>
<state init="false">pon</state>
<state init="true">poff</state>
</states>
<transitions>
<transition from="pon" event="pturnoff" action="poffpulse" to="poff"/>
<transition from="poff" event="pturnoff" action="poffpulse" to="poff"/>
<transition from="pon" event="pturnon" action="ponpulse" to="pon"/>
<transition from="poff" event="pturnon" action="ponpulse" to="pon"/>
</transitions>
</device>
<device name="mc">
<events>
<event>mturnon</event>
<event>mturnoff</event>
</events>
<states>
<state init="false">mon</state>
<state init="true">moff</state>
</states>
<transitions>
<transition from="mon" event="mturnoff" action="moffpulse" to="moff"/>
<transition from="moff" event="mturnoff" action="moffpulse" to="moff"/>
<transition from="mon" event="mturnon" action="monpulse" to="mon"/>
<transition from="moff" event="mturnon" action="monpulse" to="mon"/>
</transitions>
</device>
<device name="window">
<events>
<event>wopen</event>
<event>wclose</event>
</events>
<states>
<state init="false">wopen</state>
<state init="true">wclosed</state>
</states>
<transitions>
<transition from="wopen" event="wclose" action="wclosepulse" to="wclosed"/>
<transition from="wclosed" event="wclose" action="wclosepulse" to="wclosed"/>
<transition from="wopen" event="wopen" action="wopenpulse" to="wopen"/>
<transition from="wclosed" event="wopen" action="wopenpulse" to="wopen"/>
</transitions>
</device>
<device name="ac">
<events>
<event>turnoncold</event>
<event>turnonhot</event>
<event>aturnoff</event>
</events>
<states>
<state init="false">coldon</state>
<state init="false">hoton</state>
<state init="true">aoff</state>
</states>
<transitions>
<transition from="aoff" event="aturnoff" action="aoffpulse" to="aoff"/>
<transition from="aoff" event="turnoncold" action="coldpulse" to="coldon"/>
<transition from="aoff" event="turnonhot" action="hotpulse" to="hoton"/>
<transition from="coldon" event="aturnoff" action="aoffpulse" to="aoff"/>
<transition from="coldon" event="turnoncold" action="coldpulse" to="coldon"/>
<transition from="coldon" event="turnonhot" action="hotpulse" to="hoton"/>
<transition from="hoton" event="aturnoff" action="aoffpulse" to="aoff"/>
<transition from="hoton" event="turnoncold" action="coldpulse" to="coldon"/>
<transition from="hoton" event="turnonhot" action="hotpulse" to="hoton"/>
</transitions>
</device>
<device name="af">
<events>
<event>afturnon</event>
<event>afturnoff</event>
</events>
<states>
<state init="false">afon</state>
<state init="true">afoff</state>
</states>
<transitions>
<transition from="afon" event="afturnoff" action="afoffpulse" to="afoff"/>
<transition from="afoff" event="afturnoff" action="afoffpulse" to="afoff"/>
<transition from="afon" event="afturnon" action="afonpulse" to="afon"/>
<transition from="afoff" event="afturnon" action="afonpulse" to="afon"/>
</transitions>
</device>
<device name="ah">
<events>
<event>ahturnon</event>
<event>ahturnoff</event>
</events>
<states>
<state init="false">ahon</state>
<state init="true">ahoff</state>
</states>
<transitions>
<transition from="ahon" event="ahturnoff" action="ahoffpulse" to="ahoff"/>
<transition from="ahoff" event="ahturnoff" action="ahoffpulse" to="ahoff"/>
<transition from="ahon" event="ahturnon" action="ahonpulse" to="ahon"/>
<transition from="ahoff" event="ahturnon" action="ahonpulse" to="ahon"/>
</transitions>
</device>
<device name="fan">
<events>
<event>fturnon</event>
<event>fturnoff</event>
</events>
<states>
<state init="false">fon</state>
<state init="true">foff</state>
</states>
<transitions>
<transition from="fon" event="fturnoff" action="foffpulse" to="foff"/>
<transition from="foff" event="fturnoff" action="foffpulse" to="foff"/>
<transition from="fon" event="fturnon" action="fonpulse" to="fon"/>
<transition from="foff" event="fturnon" action="fonpulse" to="fon"/>
</transitions>
</device>
<device name="heater">
<events>
<event>hturnon</event>
<event>hturnoff</event>
</events>
<states>
<state init="false">hon</state>
<state init="true">hoff</state>
</states>
<transitions>
<transition from="hon" event="hturnoff" action="hoffpulse" to="hoff"/>
<transition from="hoff" event="hturnoff" action="hoffpulse" to="hoff"/>
<transition from="hon" event="hturnon" action="honpulse" to="hon"/>
<transition from="hoff" event="hturnon" action="honpulse" to="hon"/>
</transitions>
</device>
</statemachines>
</ontology>

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<ontology>
<environment>
<attribute name="person.number"/>
<attribute name="air.temperature" fluctuation="3"/>
<attribute name="air.humidity" fluctuation="10"/>
<attribute name="co2.ppm" fluctuation="30"/>
<attribute name="light.brightness" fluctuation="50"/>
<attribute name="person.in"/>
</environment>
<devices>
<device name="light">
<states>
<state name="lon" init="false">
<adjust_entity name="light.brightness" energy="5" rate="200" method="prompt"/>
</state>
</states>
</device>
<device name="fan">
<states>
<state name="fon" init="false">
<adjust_entity name="air.temperature" energy="30" rate="-0.05" method="/second"/>
</state>
</states>
</device>
<device name="humidifier">
<states>
<state name="hon" init="false">
<adjust_entity name="air.humidity" energy="30" rate="+1" method="/second"/>
</state>
</states>
</device>
<device name="purifier">
<states>
<state name="pon" init="false">
<adjust_entity name="co2.ppm" energy="30" rate="-3" method="/second"/>
</state>
</states>
</device>
</devices>
<statemachines>
<device name="light">
<events>
<event>lturnon</event>
<event>lturnoff</event>
</events>
<states>
<state init="false">lon</state>
<state init="true">loff</state>
</states>
<transitions>
<transition from="lon" event="lturnoff" action="loffpulse" to="loff"/>
<transition from="loff" event="lturnoff" action="loffpulse" to="loff"/>
<transition from="lon" event="lturnon" action="lonpulse" to="lon"/>
<transition from="loff" event="lturnon" action="lonpulse" to="lon"/>
</transitions>
</device>
<device name="fan">
<events>
<event>fturnon</event>
<event>fturnoff</event>
</events>
<states>
<state init="false">fon</state>
<state init="true">foff</state>
</states>
<transitions>
<transition from="fon" event="fturnoff" action="foffpulse" to="foff"/>
<transition from="foff" event="fturnoff" action="foffpulse" to="foff"/>
<transition from="fon" event="fturnon" action="fonpulse" to="fon"/>
<transition from="foff" event="fturnon" action="fonpulse" to="fon"/>
</transitions>
</device>
<device name="purifier">
<events>
<event>pturnon</event>
<event>pturnoff</event>
</events>
<states>
<state init="false">pon</state>
<state init="true">poff</state>
</states>
<transitions>
<transition from="pon" event="pturnoff" action="poffpulse" to="poff"/>
<transition from="poff" event="pturnoff" action="poffpulse" to="poff"/>
<transition from="pon" event="pturnon" action="ponpulse" to="pon"/>
<transition from="poff" event="pturnon" action="ponpulse" to="pon"/>
</transitions>
</device>
<device name="humidifier">
<events>
<event>hturnon</event>
<event>hturnoff</event>
</events>
<states>
<state init="false">hon</state>
<state init="true">hoff</state>
</states>
<transitions>
<transition from="hon" event="hturnoff" action="hoffpulse" to="hoff"/>
<transition from="hoff" event="hturnoff" action="hoffpulse" to="hoff"/>
<transition from="hon" event="hturnon" action="honpulse" to="hon"/>
<transition from="hoff" event="hturnon" action="honpulse" to="hon"/>
</transitions>
</device>
</statemachines>
</ontology>

@ -0,0 +1,11 @@
fan.humidifier->null->fan.xiaomi_air_humidifier->office
vacuum->null->vacuum.xiaomi_vacuum_1c->office
fan.purifier->null->fan.xiaomi_air_purifier_2s->office
light->2aa2d30f3b24d1a598d18d7a566a1de4->light.aqara_hub_m1s_4729->nonono
temperature->0e1726f9704dc3cfbf7c038f477d6be0->sensor.temperature_sensor_c5e1_temperature->office
opening->d894c20c03ba7e40263b8889e7e24b07->binary_sensor.window_and_door_sensor_2825->office
motion->3572f4248b12b2470d199d027a23d1b4->binary_sensor.motion_sensor_6dc9->office
light->0e9aaa2b980c2309c87d3f4720b1bcf4->light.midesklamppro_7a9b->office
illuminance->223eedf22b004368e7b9950dc7710c1e->sensor.light_sensor_2773_light_level->office
fan.fan->null->fan.xiaomi_smart_fan->office
humidity->0e1726f9704dc3cfbf7c038f477d6be0->sensor.temperature_sensor_c5e1_humidity->office

Binary file not shown.

@ -0,0 +1,72 @@
diff -Naur avs-sensory/pi.sh avs-kitt/pi.sh
--- pi.sh 2019-05-03 18:09:18.063849909 -0700
+++ pi.sh 2019-05-03 18:09:39.273744305 -0700
@@ -20,18 +20,19 @@
SOUND_CONFIG="$HOME/.asoundrc"
START_SCRIPT="$INSTALL_BASE/startsample.sh"
-CMAKE_PLATFORM_SPECIFIC=(-DSENSORY_KEY_WORD_DETECTOR=ON \
+CMAKE_PLATFORM_SPECIFIC=(-DKITTAI_KEY_WORD_DETECTOR=ON \
-DGSTREAMER_MEDIA_PLAYER=ON -DPORTAUDIO=ON \
-DPORTAUDIO_LIB_PATH="$THIRD_PARTY_PATH/portaudio/lib/.libs/libportaudio.$LIB_SUFFIX" \
-DPORTAUDIO_INCLUDE_DIR="$THIRD_PARTY_PATH/portaudio/include" \
- -DSENSORY_KEY_WORD_DETECTOR_LIB_PATH=$THIRD_PARTY_PATH/alexa-rpi/lib/libsnsr.a \
- -DSENSORY_KEY_WORD_DETECTOR_INCLUDE_DIR=$THIRD_PARTY_PATH/alexa-rpi/include)
+ -DKITTAI_KEY_WORD_DETECTOR_LIB_PATH=$THIRD_PARTY_PATH/snowboy/lib/rpi/libsnowboy-detect.a \
+ -DKITTAI_KEY_WORD_DETECTOR_INCLUDE_DIR=$THIRD_PARTY_PATH/snowboy/include \
+ -DCMAKE_BUILD_TYPE=MINSIZEREL)
GSTREAMER_AUDIO_SINK="alsasink"
install_dependencies() {
sudo apt-get update
- sudo apt-get -y install git gcc cmake build-essential libsqlite3-dev libcurl4-openssl-dev libssl-dev libfaad-dev libsoup2.4-dev libgcrypt20-dev libgstreamer-plugins-bad1.0-dev gstreamer1.0-plugins-good libasound2-dev sox gedit vim python3-pip
+ sudo apt-get -y install git gcc cmake build-essential libsqlite3-dev libcurl4-openssl-dev libssl-dev libfaad-dev libsoup2.4-dev libgcrypt20-dev libgstreamer-plugins-bad1.0-dev gstreamer1.0-plugins-good libasound2-dev sox gedit vim python3-pip python-pip libatlas-base-dev
pip install flask commentjson
}
@@ -64,18 +65,18 @@
build_kwd_engine() {
- #get sensory and build
+ #get kittai and build
echo
- echo "==============> CLONING AND BUILDING SENSORY =============="
+ echo "==============> CLONING AND BUILDING KITTAI =============="
echo
cd $THIRD_PARTY_PATH
- git clone git://github.com/Sensory/alexa-rpi.git
- bash ./alexa-rpi/bin/license.sh
+ git clone https://github.com/Kitt-AI/snowboy.git
+ cp snowboy/resources/alexa/alexa-avs-sample-app/alexa.umdl snowboy/resources/alexa.umdl
}
generate_start_script() {
cat << EOF > "$START_SCRIPT"
cd "$BUILD_PATH/SampleApp/src"
- ./SampleApp "$OUTPUT_CONFIG_FILE" "$THIRD_PARTY_PATH/alexa-rpi/models" DEBUG9
+ ./SampleApp "$OUTPUT_CONFIG_FILE" "$THIRD_PARTY_PATH/snowboy/resources" DEBUG9
EOF
}
diff -Naur avs-sensory/setup.sh avs-kitt/setup.sh
--- setup.sh 2019-05-03 18:09:24.383818365 -0700
+++ setup.sh 2019-05-03 18:09:35.193764563 -0700
@@ -50,6 +50,8 @@
LIB_SUFFIX="a"
ANDROID_CONFIG_FILE=""
+BUILDTYPE="MINSIZEREL"
+
# Default device serial number if nothing is specified
DEVICE_SERIAL_NUMBER="123456"
@@ -242,7 +244,7 @@
cmake "$SOURCE_PATH/avs-device-sdk" \
-DCMAKE_BUILD_TYPE=DEBUG \
"${CMAKE_PLATFORM_SPECIFIC[@]}"
-
+ sed -E -i "s:CXX_PLATFORM_DEPENDENT_FLAGS_"$BUILDTYPE"\s+\"(.*)\":CXX_PLATFORM_DEPENDENT_FLAGS_"$BUILDTYPE" \"\1 -D_GLIBCXX_USE_CXX11_ABI=0 -pg\":" ../avs-device-sdk/build/cmake/BuildOptions.cmake
cd $BUILD_PATH
make SampleApp -j1

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,179 @@
import math
import pickle
import re
import Levenshtein
import cn2an
import pypinyin
place_list = ['卧室一', '卧室二', '卧室', '厕所一', '厕所二', '厕所', '走廊', '餐厅', '客厅', '厨房', '书房', '阳台', '户外', '屋内']
action_list = ['关灯', '开灯', '灯变亮', '灯变暗', '开热空调', '开冷空调', '空调升温', '空调降温', '关空调', '开电视', '发出警告', '开窗帘', '关窗帘', '开窗', '关窗',
'开门', '关门', '开氛围灯', '关氛围灯', '亮一点', '暗一点', '热一点', '冷一点', '温度高一点', '温度低一点', '允许通风',
'禁止通风', '开启回家模式', '开启离家模式', '开启观影模式']
trigger_list = ['下雨', '不下雨', '天晴', '有人', '按门铃', '没人', '有人移动', '没人移动', '着火', '起风', '起烟', '天黑', '灯打开', '灯关闭', '门打开',
'门关闭', '窗打开', '窗关闭', '窗帘打开', '窗帘关闭', '空调制冷', '空调制热', '空调关闭', '电视打开', '电视关闭']
time_list = ['超过?小时', '超过?分钟', '超过?秒']
re_chn = re.compile("([\u4E00-\u9Fa5a-zA-Z0-9+#&]+)")
def chn_to_arabic(text: str):
chn_numbers = re.findall(r'.*超过(.+)(秒|分钟|小时)时', text)
if len(chn_numbers) > 0:
arabic_number = cn2an.transform(chn_numbers[0][0], 'cn2an')
return text.replace('超过' + ''.join(chn_numbers[0]) + '', '超过' + str(arabic_number) + chn_numbers[0][1] + '')
else:
return text
def text_extract(sent: str):
text = ""
blks = re_chn.split(sent)
for blk in blks:
if not blk:
continue
if re_chn.match(blk):
text += blk
return text
def num_extract(text: str):
return re.sub(r'[\d]+', '', text), re.findall(r'[\d]+', text)
class Retrieval(object):
def __init__(self):
self.map_length_to_sent_and_pinyin = {}
self.initialized = False
def _initialize(self):
for action in action_list:
sent = action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for action in action_list:
sent = trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for action in action_list:
sent = place_one + trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + time + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = place_one + trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + time + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
self.initialized = True
def save_sent_data(self):
self._initialize()
with open('data/sent_data.pickle', 'wb+') as f:
pickle.dump(self.map_length_to_sent_and_pinyin, f, pickle.DEFAULT_PROTOCOL)
def load_sent_data(self):
with open('data/sent_data.pickle', 'rb') as f:
self.map_length_to_sent_and_pinyin = pickle.load(f)
self.initialized = True
def retrieve(self, sent):
if not sent:
return sent
text = text_extract(sent)
text = chn_to_arabic(text)
text, nums = num_extract(text)
number = ''
if len(nums) > 0:
number = nums[0]
if not text:
return text
if not self.initialized:
self.load_sent_data()
sent_pinyin = pypinyin.slug(text, separator='')
length = len(sent_pinyin)
interval = 10
top_sent = text
min_distance = math.inf
for cl in range(max(0, length - interval), length + interval):
if cl in self.map_length_to_sent_and_pinyin:
pair_list = self.map_length_to_sent_and_pinyin[cl]
for pair in pair_list:
distance = Levenshtein.distance(pair[0], sent_pinyin)
if min_distance > distance:
min_distance = distance
top_sent = pair[1]
res = top_sent.replace('超过?', '超过' + number)
return res
if __name__ == '__main__':
r = Retrieval()
r.save_sent_data()

@ -0,0 +1,550 @@
import snowboydecoder
import signal
import wave
import sys
import json
import requests
import time
import os
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
from fetchToken import fetch_token
import time
import unicodedata
import math
import pickle
import Levenshtein
import cn2an
import pypinyin
import re
import retrieval
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.parse import quote_plus
else:
import urllib2
from urllib import quote_plus
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
from urllib import urlencode
interrupted = False # snowboy监听唤醒结束标志
endSnow = False # 程序结束标志
framerate = 16000 # 采样率
num_samples = 2000 # 采样点
channels = 1 # 声道
sampwidth = 2 # 采样宽度2bytes
pid = ''
music_exit = 'audio/exit.wav' # 唤醒系统退出语音
music_open = 'audio/open.wav' # 唤醒系统打开语音
music_alarm = 'audio/alarm.wav'
music_listen = 'audio/listen.wav'
music_over = 'audio/over.wav'
FILEPATH = 'audio/audio.wav'
MAPPATH = 'cemap.txt'
DEVICEPATH = 'my-case-study.properties'
SRC = 'ChineseRequirements.txt'
requirementTexts = ''
# os.close(sys.stderr.fileno()) # 去掉错误警告
def signal_handler(signal, frame):
"""
监听键盘结束
"""
global interrupted
interrupted = True
def interrupt_callback():
"""
监听唤醒
"""
global interrupted
return interrupted
def detected():
"""
唤醒成功
"""
print('唤醒成功')
play(music_open)
global interrupted
interrupted = True
detector.terminate()
def play(filename):
"""
播放音频
"""
wf = wave.open(filename, 'rb') # 打开audio.wav
p = PyAudio() # 实例化 pyaudio
# 打开流
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(1024)
while data != b'':
data = wf.readframes(1024)
stream.write(data)
# 释放IO
stream.stop_stream()
stream.close()
p.terminate()
def save_wave_file(filepath, data):
"""
存储文件
"""
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b''.join(data))
wf.close()
def my_record():
"""
录音
"""
pa = PyAudio()
global requirementTexts
text = ''
TOKEN = fetch_token() # 获取token
while text != '再见。':
stream = pa.open(format=paInt16, channels=channels, rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
print('开始录音...')
for i in range(0, int(framerate / num_samples * 5)):
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
save_wave_file(FILEPATH, my_buf)
speech = get_audio(FILEPATH)
result = speech2text(speech, TOKEN, int(80001))
text = result
print(text)
r = retrieval.Retrieval()
text_modified = r.retrieve(text)
print(text_modified)
if text == '' : text = '再见。'
if text != '再见。':
try:
eRequirement = c2e(text_modified).strip()
print(eRequirement)
play(music_listen)
except Exception as e:
pass
stream.close()
print('再见!')
play(music_over)
def speech2text(speech_data, token, dev_pid=1537):
"""
音频转文字
"""
FORMAT = 'wav'
RATE = '16000'
CHANNEL = 1
CUID = 'baidu_workshop'
SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid': dev_pid
}
# 语音转文字接口 该接口可能每个人不一样,取决于你需要哪种语音识别功能,本文使用的是 语音识别极速版
url = 'https://vop.baidu.com/pro_api'
headers = {'Content-Type': 'application/json'} # 请求头
print('正在识别...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
return Result
def get_audio(file):
"""
获取音频文件
"""
with open(file, 'rb') as f:
data = f.read()
return data
def initDict(mapPath):
d = dict()
for line in open(mapPath, 'r'):
if line.find('->') != -1:
d[line.split('->')[0]] = line.split('->')[1]
return d
def getValue(tempValue):
value = ''
for char in tempValue:
if is_number(char):
value = value + char
return value
def is_number(s):
try: # 如果能运行float(s)语句返回True字符串s是浮点数
float(s)
return True
except ValueError: # ValueError为Python的一种标准异常表示"传入无效的参数"
pass # 如果引发了ValueError这种异常不做任何事情pass不做任何事情一般用做占位语句
try:
import unicodedata # 处理ASCii码的包
unicodedata.numeric(s) # 把一个表示数字的字符串转换为浮点数返回的函数
return True
except (TypeError, ValueError):
pass
return False
def getTrigger(trigger, d):
if trigger.find("") == -1:
if trigger in d:
trigger = d[trigger]
else:
if trigger.find('高于') != -1:
attribute = trigger.split("高于")[0]
tempValue = trigger.split("高于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + ">" + value
elif trigger.find('低于') != -1:
attribute = trigger.split("低于")[0]
tempValue = trigger.split("低于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + "<" + value
elif trigger.find('等于') != -1:
attribute = trigger.split("等于")[0]
tempValue = trigger.split("等于")[1]
value = getValue(tempValue)
trigger = d[attribute].strip() + "=" + value
else:
trigger1 = trigger.split('')[0]
trigger2 = trigger.split('')[1]
trigger = getTrigger(trigger1, d) + " AND " + getTrigger(trigger2,d)
return trigger.strip()
def getTime(time):
if time.find('') != -1:
value = time.split("")[0]
return value + 's'
elif time.find('分钟') != -1:
value = time.split("分钟")[0]
return value + 'm'
elif time.find('小时') != -1:
value = time.split("小时")[0]
return value + 'h'
def toDigit(timeValue):
if timeValue.isdigit():
return timeValue
else:
return str(int(unicodedata.numeric(timeValue)))
def getProcessID(process):
result = os.popen("pgrep -f \'" + process + '\'');
res = result.read()
for line in res.splitlines():
return line
def check_contain_chinese(check_str):
for ch in check_str.decode('utf-8'):
if u'\u4e00' <= ch <= u'\u9fff':
return True
return False
# print(c2e('办公室窗户打开和灯打开不能同时发生'))
place_list = ['卧室一', '卧室二', '卧室', '厕所一', '厕所二', '厕所', '走廊', '餐厅', '客厅', '厨房', '书房', '阳台', '户外', '屋内']
action_list = ['关灯', '开灯', '灯变亮', '灯变暗', '开热空调', '开冷空调', '空调升温', '空调降温', '关空调', '开电视', '发出警告', '开窗帘', '关窗帘', '开窗', '关窗',
'开门', '关门', '开氛围灯', '关氛围灯', '亮一点', '暗一点', '热一点', '冷一点', '温度高一点', '温度低一点', '允许通风',
'禁止通风', '开启回家模式', '开启离家模式', '开启观影模式']
trigger_list = ['下雨', '不下雨', '天晴', '有人', '按门铃', '没人', '有人移动', '没人移动', '着火', '起风', '起烟', '天黑', '灯打开', '灯关闭', '门打开',
'门关闭', '窗打开', '窗关闭', '窗帘打开', '窗帘关闭', '空调制冷', '空调制热', '空调关闭', '电视打开', '电视关闭']
time_list = ['超过?小时', '超过?分钟', '超过?秒']
re_chn = re.compile("([\u4E00-\u9Fa5a-zA-Z0-9+#&]+)")
def chn_to_arabic(text: str):
chn_numbers = re.findall(r'.*超过(.+)(秒|分钟|小时)时', text)
if len(chn_numbers) > 0:
arabic_number = cn2an.transform(chn_numbers[0][0], 'cn2an')
return text.replace('超过' + ''.join(chn_numbers[0]) + '', '超过' + str(arabic_number) + chn_numbers[0][1] + '')
else:
return text
def text_extract(sent: str):
text = ""
blks = re_chn.split(sent)
for blk in blks:
if not blk:
continue
if re_chn.match(blk):
text += blk
return text
def num_extract(text: str):
return re.sub(r'[\d]+', '', text), re.findall(r'[\d]+', text)
class Retrieval(object):
def __init__(self):
self.map_length_to_sent_and_pinyin = {}
self.initialized = False
def _initialize(self):
for action in action_list:
sent = action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for action in action_list:
sent = trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for action in action_list:
sent = place_one + trigger + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place in place_list:
for action in action_list:
sent = trigger + time + '' + place + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_one in place_list:
for trigger in trigger_list:
for time in time_list:
for action in action_list:
sent = place_one + trigger + time + '' + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
for place_two in place_list:
for action in action_list:
sent = place_one + trigger + time + '' + place_two + action
sent_pinyin = pypinyin.slug(sent, separator='')
if len(sent_pinyin) in self.map_length_to_sent_and_pinyin:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)].append((sent_pinyin, sent))
else:
self.map_length_to_sent_and_pinyin[len(sent_pinyin)] = [(sent_pinyin, sent)]
self.initialized = True
def save_sent_data(self):
self._initialize()
with open('data/sent_data.pickle', 'wb+') as f:
pickle.dump(self.map_length_to_sent_and_pinyin, f, pickle.DEFAULT_PROTOCOL)
def load_sent_data(self):
with open('data/sent_data.pickle', 'rb') as f:
self.map_length_to_sent_and_pinyin = pickle.load(f)
self.initialized = True
def retrieve(self, sent):
if not sent:
return sent
text = text_extract(sent)
text = chn_to_arabic(text)
text, nums = num_extract(text)
number = ''
if len(nums) > 0:
number = nums[0]
if not text:
return text
if not self.initialized:
self.load_sent_data()
sent_pinyin = pypinyin.slug(text, separator='')
length = len(sent_pinyin)
interval = 10
top_sent = text
min_distance = math.inf
for cl in range(max(0, length - interval), length + interval):
if cl in self.map_length_to_sent_and_pinyin:
pair_list = self.map_length_to_sent_and_pinyin[cl]
for pair in pair_list:
distance = Levenshtein.distance(pair[0], sent_pinyin)
if min_distance > distance:
min_distance = distance
top_sent = pair[1]
res = top_sent.replace('超过?', '超过' + number)
return res
def sound2TAP(filePath):
TOKEN = fetch_token() # 获取token
speech = get_audio(FILEPATH)
chinese = speech2text(speech, TOKEN, int(80001))
r = retrieval.Retrieval()
chinese_modified = r.retrieve(chinese)
eRequirements = c2e(chinese_modified).strip()
return eRequirements
def c2e(cRequirement):
cemap = initDict(MAPPATH)
rooms = ["客厅", "玄关"]
result = []
cRequirement = str(cRequirement)
cRequirement = cRequirement.replace("","")
cRequirement = cRequirement.replace("", "")
cRequirement = cRequirement.replace("", "")
cRequirement = cRequirement.replace("", "")
eRequirement = ''
room = ''
for temp in rooms:
if cRequirement.startswith(temp):
room = temp
cRequirement = cRequirement[cRequirement.index(room) + len(room):]
break
if room != '':
room = cemap[room].strip()
result.append(toTAP(cRequirement, room))
else:
for temp in rooms:
room = cemap[temp].strip()
result.append(toTAP(cRequirement, room))
return result
def toTAP(cRequirement, room):
cemap = initDict(MAPPATH)
devices = []
d = dict()
devices = []
for line in open(DEVICEPATH, 'r'):
if line.startswith('device'):
temp = line[line.find('{') + 1:line.find('}')]
attributes = temp.split(',')
deviceName = attributes[0].split(':')[1]
deviceType = attributes[1].split(':')[1]
location = attributes[2].split(':')[1]
d[deviceType + '//' + location] = deviceName
devices.append(deviceType)
rooms = ["客厅", "玄关"]
trigger = getTrigger(cRequirement.split("")[0], cemap).strip()
triggerRoom = room
if trigger.split('.')[0] in devices:
if not trigger.split('.')[0] + '//' + room in d:
return
trigger = d[trigger.split('.')[0] + '//' + room] + '.' + trigger.split('.')[1]
action = cRequirement.split("")[1].strip()
actionRoom = ''
actionRoomFlag = False
for temp in rooms:
if action.startswith(temp):
actionRoomFlag = True
actionRoom = cemap[temp.strip()].strip()
action = cemap[action[action.index(temp) + len(temp):]]
if action.split('.')[0] in devices:
if not action.split('.')[0] + '//' + actionRoom in d:
return
action = d[action.split('.')[0] + '//' + actionRoom] + '.' + action.split('.')[1]
break
if not actionRoomFlag:
actionRoom = triggerRoom
action = cemap[action]
if action.split('.')[0] in devices:
if not action.split('.')[0] + '//' + actionRoom in d:
return
action = d[action.split('.')[0] + '//' + actionRoom] + '.' + action.split('.')[1]
return "IF " + trigger + " THEN " + action;
# print(c2e('客厅温度低于25度时开冷空调'))
#
while 1:
interrupted = False
# 实例化snowboy第一个参数就是唤醒识别模型位置
detector = snowboydecoder.HotwordDetector('xiaoxin.pmdl', sensitivity=0.5)
print('等待唤醒')
# snowboy监听循环
detector.start(detected_callback=detected,
interrupt_check=interrupt_callback,
sleep_time=0.03)
my_record() # 唤醒成功开始录音

@ -0,0 +1,277 @@
#!/usr/bin/env python
import collections
import pyaudio
import snowboydetect
import time
import wave
import os
import logging
from ctypes import *
from contextlib import contextmanager
logging.basicConfig()
logger = logging.getLogger("snowboy")
logger.setLevel(logging.INFO)
TOP_DIR = os.path.dirname(os.path.abspath(__file__))
RESOURCE_FILE = os.path.join(TOP_DIR, "resources/common.res")
DETECT_DING = os.path.join(TOP_DIR, "resources/ding.wav")
DETECT_DONG = os.path.join(TOP_DIR, "resources/dong.wav")
def py_error_handler(filename, line, function, err, fmt):
pass
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def no_alsa_error():
try:
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
except:
yield
pass
class RingBuffer(object):
"""Ring buffer to hold audio from PortAudio"""
def __init__(self, size=4096):
self._buf = collections.deque(maxlen=size)
def extend(self, data):
"""Adds data to the end of buffer"""
self._buf.extend(data)
def get(self):
"""Retrieves data from the beginning of buffer and clears it"""
tmp = bytes(bytearray(self._buf))
self._buf.clear()
return tmp
def play_audio_file(fname=DETECT_DING):
"""Simple callback function to play a wave file. By default it plays
a Ding sound.
:param str fname: wave file name
:return: None
"""
ding_wav = wave.open(fname, 'rb')
ding_data = ding_wav.readframes(ding_wav.getnframes())
with no_alsa_error():
audio = pyaudio.PyAudio()
stream_out = audio.open(
format=audio.get_format_from_width(ding_wav.getsampwidth()),
channels=ding_wav.getnchannels(),
rate=ding_wav.getframerate(), input=False, output=True)
stream_out.start_stream()
stream_out.write(ding_data)
time.sleep(0.2)
stream_out.stop_stream()
stream_out.close()
audio.terminate()
class HotwordDetector(object):
"""
Snowboy decoder to detect whether a keyword specified by `decoder_model`
exists in a microphone input stream.
:param decoder_model: decoder model file path, a string or a list of strings
:param resource: resource file path.
:param sensitivity: decoder sensitivity, a float of a list of floats.
The bigger the value, the more senstive the
decoder. If an empty list is provided, then the
default sensitivity in the model will be used.
:param audio_gain: multiply input volume by this factor.
:param apply_frontend: applies the frontend processing algorithm if True.
"""
def __init__(self, decoder_model,
resource=RESOURCE_FILE,
sensitivity=[],
audio_gain=1,
apply_frontend=False):
tm = type(decoder_model)
ts = type(sensitivity)
if tm is not list:
decoder_model = [decoder_model]
if ts is not list:
sensitivity = [sensitivity]
model_str = ",".join(decoder_model)
self.detector = snowboydetect.SnowboyDetect(
resource_filename=resource.encode(), model_str=model_str.encode())
self.detector.SetAudioGain(audio_gain)
self.detector.ApplyFrontend(apply_frontend)
self.num_hotwords = self.detector.NumHotwords()
if len(decoder_model) > 1 and len(sensitivity) == 1:
sensitivity = sensitivity * self.num_hotwords
if len(sensitivity) != 0:
assert self.num_hotwords == len(sensitivity), \
"number of hotwords in decoder_model (%d) and sensitivity " \
"(%d) does not match" % (self.num_hotwords, len(sensitivity))
sensitivity_str = ",".join([str(t) for t in sensitivity])
if len(sensitivity) != 0:
self.detector.SetSensitivity(sensitivity_str.encode())
self.ring_buffer = RingBuffer(
self.detector.NumChannels() * self.detector.SampleRate() * 5)
def start(self, detected_callback=play_audio_file,
interrupt_check=lambda: False,
sleep_time=0.03,
audio_recorder_callback=None,
silent_count_threshold=15,
recording_timeout=100):
"""
Start the voice detector. For every `sleep_time` second it checks the
audio buffer for triggering keywords. If detected, then call
corresponding function in `detected_callback`, which can be a single
function (single model) or a list of callback functions (multiple
models). Every loop it also calls `interrupt_check` -- if it returns
True, then breaks from the loop and return.
:param detected_callback: a function or list of functions. The number of
items must match the number of models in
`decoder_model`.
:param interrupt_check: a function that returns True if the main loop
needs to stop.
:param float sleep_time: how much time in second every loop waits.
:param audio_recorder_callback: if specified, this will be called after
a keyword has been spoken and after the
phrase immediately after the keyword has
been recorded. The function will be
passed the name of the file where the
phrase was recorded.
:param silent_count_threshold: indicates how long silence must be heard
to mark the end of a phrase that is
being recorded.
:param recording_timeout: limits the maximum length of a recording.
:return: None
"""
self._running = True
def audio_callback(in_data, frame_count, time_info, status):
self.ring_buffer.extend(in_data)
play_data = chr(0) * len(in_data)
return play_data, pyaudio.paContinue
with no_alsa_error():
self.audio = pyaudio.PyAudio()
self.stream_in = self.audio.open(
input=True, output=False,
format=self.audio.get_format_from_width(
self.detector.BitsPerSample() / 8),
channels=self.detector.NumChannels(),
rate=self.detector.SampleRate(),
frames_per_buffer=2048,
stream_callback=audio_callback)
if interrupt_check():
logger.debug("detect voice return")
return
tc = type(detected_callback)
if tc is not list:
detected_callback = [detected_callback]
if len(detected_callback) == 1 and self.num_hotwords > 1:
detected_callback *= self.num_hotwords
assert self.num_hotwords == len(detected_callback), \
"Error: hotwords in your models (%d) do not match the number of " \
"callbacks (%d)" % (self.num_hotwords, len(detected_callback))
logger.debug("detecting...")
state = "PASSIVE"
while self._running is True:
if interrupt_check():
logger.debug("detect voice break")
break
data = self.ring_buffer.get()
if len(data) == 0:
time.sleep(sleep_time)
continue
status = self.detector.RunDetection(data)
if status == -1:
logger.warning("Error initializing streams or reading audio data")
#small state machine to handle recording of phrase after keyword
if state == "PASSIVE":
if status > 0: #key word found
self.recordedData = []
self.recordedData.append(data)
silentCount = 0
recordingCount = 0
message = "Keyword " + str(status) + " detected at time: "
message += time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(time.time()))
logger.info(message)
callback = detected_callback[status-1]
if callback is not None:
callback()
if audio_recorder_callback is not None:
state = "ACTIVE"
continue
elif state == "ACTIVE":
stopRecording = False
if recordingCount > recording_timeout:
stopRecording = True
elif status == -2: #silence found
if silentCount > silent_count_threshold:
stopRecording = True
else:
silentCount = silentCount + 1
elif status == 0: #voice found
silentCount = 0
if stopRecording == True:
fname = self.saveMessage()
audio_recorder_callback(fname)
state = "PASSIVE"
continue
recordingCount = recordingCount + 1
self.recordedData.append(data)
logger.debug("finished.")
def saveMessage(self):
"""
Save the message stored in self.recordedData to a timestamped file.
"""
filename = 'output' + str(int(time.time())) + '.wav'
data = b''.join(self.recordedData)
#use wave to save data
wf = wave.open(filename, 'wb')
wf.setnchannels(1)
wf.setsampwidth(self.audio.get_sample_size(
self.audio.get_format_from_width(
self.detector.BitsPerSample() / 8)))
wf.setframerate(self.detector.SampleRate())
wf.writeframes(data)
wf.close()
logger.debug("finished saving: " + filename)
return filename
def terminate(self):
"""
Terminate audio stream. Users can call start() again to detect.
:return: None
"""
self.stream_in.stop_stream()
self.stream_in.close()
self.audio.terminate()
self._running = False

@ -0,0 +1,144 @@
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
# Import the low-level C/C++ module
if __package__ or "." in __name__:
from . import _snowboydetect
else:
import _snowboydetect
try:
import builtins as __builtin__
except ImportError:
import __builtin__
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value):
if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
set(self, name, value)
else:
raise AttributeError("You cannot add instance attributes to %s" % self)
return set_instance_attr
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value):
if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
set(cls, name, value)
else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper
class _SwigNonDynamicMeta(type):
"""Meta class to enforce nondynamic attributes (no new attributes) for a class"""
__setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
class SnowboyDetect(object):
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, resource_filename, model_str):
_snowboydetect.SnowboyDetect_swiginit(self, _snowboydetect.new_SnowboyDetect(resource_filename, model_str))
def Reset(self):
return _snowboydetect.SnowboyDetect_Reset(self)
def RunDetection(self, *args):
return _snowboydetect.SnowboyDetect_RunDetection(self, *args)
def SetSensitivity(self, sensitivity_str):
return _snowboydetect.SnowboyDetect_SetSensitivity(self, sensitivity_str)
def SetHighSensitivity(self, high_sensitivity_str):
return _snowboydetect.SnowboyDetect_SetHighSensitivity(self, high_sensitivity_str)
def GetSensitivity(self):
return _snowboydetect.SnowboyDetect_GetSensitivity(self)
def SetAudioGain(self, audio_gain):
return _snowboydetect.SnowboyDetect_SetAudioGain(self, audio_gain)
def UpdateModel(self):
return _snowboydetect.SnowboyDetect_UpdateModel(self)
def NumHotwords(self):
return _snowboydetect.SnowboyDetect_NumHotwords(self)
def ApplyFrontend(self, apply_frontend):
return _snowboydetect.SnowboyDetect_ApplyFrontend(self, apply_frontend)
def SampleRate(self):
return _snowboydetect.SnowboyDetect_SampleRate(self)
def NumChannels(self):
return _snowboydetect.SnowboyDetect_NumChannels(self)
def BitsPerSample(self):
return _snowboydetect.SnowboyDetect_BitsPerSample(self)
__swig_destroy__ = _snowboydetect.delete_SnowboyDetect
# Register SnowboyDetect in _snowboydetect:
_snowboydetect.SnowboyDetect_swigregister(SnowboyDetect)
class SnowboyVad(object):
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, resource_filename):
_snowboydetect.SnowboyVad_swiginit(self, _snowboydetect.new_SnowboyVad(resource_filename))
def Reset(self):
return _snowboydetect.SnowboyVad_Reset(self)
def RunVad(self, *args):
return _snowboydetect.SnowboyVad_RunVad(self, *args)
def SetAudioGain(self, audio_gain):
return _snowboydetect.SnowboyVad_SetAudioGain(self, audio_gain)
def ApplyFrontend(self, apply_frontend):
return _snowboydetect.SnowboyVad_ApplyFrontend(self, apply_frontend)
def SampleRate(self):
return _snowboydetect.SnowboyVad_SampleRate(self)
def NumChannels(self):
return _snowboydetect.SnowboyVad_NumChannels(self)
def BitsPerSample(self):
return _snowboydetect.SnowboyVad_BitsPerSample(self)
__swig_destroy__ = _snowboydetect.delete_SnowboyVad
# Register SnowboyVad in _snowboydetect:
_snowboydetect.SnowboyVad_swigregister(SnowboyVad)

Binary file not shown.

310
mvnw vendored

@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mvnw.cmd vendored

@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>simulation-visualization</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>simulation-visualization</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,56 @@
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrossOriginConfig implements WebMvcConfigurer{
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins("*")
// .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
// .allowCredentials(true)
// .allowedHeaders("*")
// .maxAge(3600);
//
// }
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
//默认的跨域请求不会发送cookie等用户认证凭据
//必须前端设置withCredentials=true且后端设置AllowCredentials(true)
//才能使cookie+session认证生效;
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 是否允许证书cookies
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(3600);
}
}

@ -0,0 +1,13 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimulationVisualizationApplication {
public static void main(String[] args) {
SpringApplication.run(SimulationVisualizationApplication.class, args);
}
}

@ -0,0 +1,70 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class Action {
public String action=""; ////////Bulb_0.turn_bulb_on
public String actionPulse=""; ////////turn_bulb_on
public String device=""; ////////Bulb_0
public String toState=""; ////////bon
public String value=""; ////////1 bulb=1
public String actionNum=""; ////////action1 用在生成IFD上作为节点id
////////////是不是会改变属性 attrVal[0]=attribute,attrVal[1]="'"||"=",attrVal[2]=value
// public List<String[]> attrVal=new ArrayList<String[]>();
public List<Rule> rules=new ArrayList<Rule>();
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getDevice() {
return device;
}
public String getActionPulse() {
return actionPulse;
}
public void setActionPulse(String actionPulse) {
this.actionPulse = actionPulse;
}
public String getActionNum() {
return actionNum;
}
public void setActionNum(String actionNum) {
this.actionNum = actionNum;
}
public void setDevice(String device) {
this.device = device;
}
public String getToState() {
return toState;
}
public void setToState(String toState) {
this.toState = toState;
}
// public List<String[]> getAttrVal() {
// return attrVal;
// }
// public void setAttrVal(List<String[]> attrVal) {
// this.attrVal = attrVal;
// }
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.actionNum+" : "+this.action;
}
}

@ -0,0 +1,26 @@
package com.example.demo.bean;
public class Attribute {
private String content=""; ///内容 temperature'==dtemper 更改了模型添加了一个Attribute模型用来表示各个属性的变化
private String attribute=""; ////temperature
private String delta=""; ////dtemper
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getDelta() {
return delta;
}
public void setDelta(String delta) {
this.delta = delta;
}
}

@ -0,0 +1,20 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class BiddableType extends Entity{
//////lobby position 1
public List<String[]> stateAttributeValues =new ArrayList<String[]>();
public List<String[]> getStateAttributeValues() {
return stateAttributeValues;
}
public void setStateAttributeValues(List<String[]> stateAttributeValues) {
this.stateAttributeValues = stateAttributeValues;
}
}

@ -0,0 +1,30 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class CauseRule {
/////导致某个状态的原因规则
private String state=""; ///状态
private int value=-1; ////对应的值
private List<RuleNode> stateCausingRules=new ArrayList<RuleNode>(); ////对应的规则
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public List<RuleNode> getStateCausingRules() {
return stateCausingRules;
}
public void setStateCausingRules(List<RuleNode> stateCausingRules) {
this.stateCausingRules = stateCausingRules;
}
}

@ -0,0 +1,23 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class Conflict {
////状态冲突
private double time; ///冲突时间
private List<Integer> conflictValues=new ArrayList<>(); //////冲突的值(对应状态)
public double getTime() {
return time;
}
public void setTime(double time) {
this.time = time;
}
public List<Integer> getConflictValues() {
return conflictValues;
}
public void setConflictValues(List<Integer> conflictValues) {
this.conflictValues = conflictValues;
}
}

@ -0,0 +1,24 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class ConflictReason {
/////冲突即原因
private Conflict conflict=new Conflict(); /////某个冲突
private List<CauseRule> causingRules=new ArrayList<>(); //////原因
public Conflict getConflict() {
return conflict;
}
public void setConflict(Conflict conflict) {
this.conflict = conflict;
}
public List<CauseRule> getCausingRules() {
return causingRules;
}
public void setCausingRules(List<CauseRule> causingRules) {
this.causingRules = causingRules;
}
}

@ -0,0 +1,22 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class DataTimeValue {
/////仿真结果数据格式
public String name=""; ////////数据名
public List<double[]> timeValues=new ArrayList<double[]>(); ////(time,value)列表,为仿真结果
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<double[]> getTimeValues() {
return timeValues;
}
public void setTimeValues(List<double[]> timeValues) {
this.timeValues = timeValues;
}
}

@ -0,0 +1,30 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class DeviceAnalysisResult {
///////设备分析结果
private String deviceName=""; ////设备名
private List<ConflictReason> conflictReasons=new ArrayList<>(); ////是否有冲突及原因
private List<JitterReason> jitterReasons=new ArrayList<>(); /////是否有抖动及原因
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public List<ConflictReason> getConflictReasons() {
return conflictReasons;
}
public void setConflictReasons(List<ConflictReason> conflictReasons) {
this.conflictReasons = conflictReasons;
}
public List<JitterReason> getJitterReasons() {
return jitterReasons;
}
public void setJitterReasons(List<JitterReason> jitterReasons) {
this.jitterReasons = jitterReasons;
}
}

@ -0,0 +1,59 @@
package com.example.demo.bean;
/** ///////////设备细节信息
*
* xmlBulb_0=Bulb(0)Bulb(0),constructionNum=0
*/
public class DeviceDetail {
private String deviceName=""; //////设备名 Bulb_0
private String location=""; //////位置 lobby
private DeviceType deviceType=new DeviceType(); ///////哪类设备 Bulb
private int constructionNum=-1; ///////0 对应uppaal的Bulb_0=Bulb(0);默认未设置-1
public String getDeviceName() {
return deviceName;
}
public DeviceDetail() {
}
public DeviceDetail(String deviceName, String location, String deviceTypeName) {
super();
this.deviceName = deviceName;
this.location = location;
this.deviceType.name=deviceTypeName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public DeviceType getDeviceType() {
return deviceType;
}
public void setDeviceType(DeviceType deviceType) {
this.deviceType = deviceType;
}
public int getConstructionNum() {
return constructionNum;
}
public void setConstructionNum(int constructionNum) {
this.constructionNum = constructionNum;
}
@Override
public String toString() {
return "DeviceDetail [deviceName=" + deviceName + ", location=" + location + ", deviceType=" + deviceType.name + "]";
}
public void setDeviceTypeName(String deviceTypeName) {
DeviceType deviceType=new DeviceType();
deviceType.setName(deviceTypeName);
this.deviceType=deviceType;
}
}

@ -0,0 +1,55 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class DeviceType extends Entity{
// [0] state, [1]action [2]value
//Bulb------bon, turn_bulb_on, 1
public List<String[]> stateActionValues=new ArrayList<String[]>();
public int deviceNumber=0;
public List<StateEffect> stateEffects=new ArrayList<>();
public List<StateEffect> getStateEffects() {
return stateEffects;
}
public void setStateEffects(List<StateEffect> stateEffects) {
this.stateEffects = stateEffects;
}
public int getDeviceNumber() {
return deviceNumber;
}
public void setDeviceNumber(int deviceNumber) {
this.deviceNumber = deviceNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String[]> getStateActionValues() {
return stateActionValues;
}
public void setStateActionValues(List<String[]> stateActionValues) {
this.stateActionValues = stateActionValues;
}
public static class StateEffect{
private String state="";
private List<String[]> effects=new ArrayList<>();
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public List<String[]> getEffects() {
return effects;
}
public void setEffects(List<String[]> effects) {
this.effects = effects;
}
}
}

@ -0,0 +1,16 @@
package com.example.demo.bean;
public class Entity {
////实体类
protected String name="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@ -0,0 +1,50 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class EnvironmentModel {
private List<DeviceDetail> devices=new ArrayList<DeviceDetail>();
private List<SensorType> sensors=new ArrayList<SensorType>();
private List<BiddableType> biddables=new ArrayList<BiddableType>();
private List<DeviceType> deviceTypes=new ArrayList<>();
/////添加Attribute
private List<Attribute> attributes=new ArrayList<>();
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public List<DeviceType> getDeviceTypes() {
return deviceTypes;
}
public void setDeviceTypes(List<DeviceType> deviceTypes) {
this.deviceTypes = deviceTypes;
}
public List<DeviceDetail> getDevices() {
return devices;
}
public void setDevices(List<DeviceDetail> devices) {
this.devices = devices;
}
public List<SensorType> getSensors() {
return sensors;
}
public void setSensors(List<SensorType> sensors) {
this.sensors = sensors;
}
public List<BiddableType> getBiddables() {
return biddables;
}
public void setBiddables(List<BiddableType> biddables) {
this.biddables = biddables;
}
public EnvironmentModel() {
super();
}
}

@ -0,0 +1,20 @@
package com.example.demo.bean;
public class ErrorReason {
////用于静态分析
public Rule rule=new Rule(); ///错误的规则
public String reason=""; /////规则错误原因
public Rule getRule() {
return rule;
}
public void setRule(Rule rule) {
this.rule = rule;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}

@ -0,0 +1,121 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class IFDGraph {
public static class GraphNode {
private String name=""; ///////节点名 trigger1
private String shape=""; ///////节点形状 oval
private String fillcolor=""; ////节点填充色
private String label=""; //////节点内容
public boolean flag=false;
private List<GraphNodeArrow> pNodeList=new ArrayList<GraphNodeArrow>();
private List<GraphNodeArrow> cNodeList=new ArrayList<GraphNodeArrow>();
public void addpNodeList(GraphNodeArrow pNodeList) {
this.pNodeList.add(pNodeList);
}
public void addcNodeList(GraphNodeArrow cNodeList) {
this.cNodeList.add(cNodeList);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
public String getFillcolor() {
return fillcolor;
}
public void setFillcolor(String fillcolor) {
this.fillcolor = fillcolor;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<GraphNodeArrow> getpNodeList() {
return pNodeList;
}
public void setpNodeList(List<GraphNodeArrow> pNodeList) {
this.pNodeList = pNodeList;
}
public List<GraphNodeArrow> getcNodeList() {
return cNodeList;
}
public void setcNodeList(List<GraphNodeArrow> cNodeList) {
this.cNodeList = cNodeList;
}
}
public static class GraphNodeArrow {
/////节点的边
private GraphNode graphNode=new GraphNode();
private String label="";
private String color="";
private String style="";
public GraphNode getGraphNode() {
return graphNode;
}
public void setGraphNode(GraphNode graphNode) {
this.graphNode = graphNode;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
}

@ -0,0 +1,99 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class InputConstruct {
public static class EnvironmentRule{
private EnvironmentModel environmentModel;
private List<Rule> rules=new ArrayList<Rule>();
public EnvironmentModel getEnvironmentModel() {
return environmentModel;
}
public void setEnvironmentModel(EnvironmentModel environmentModel) {
this.environmentModel = environmentModel;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
public EnvironmentRule(EnvironmentModel environmentModel, List<Rule> rules) {
super();
this.environmentModel = environmentModel;
this.rules = rules;
}
public EnvironmentRule() {
super();
}
}
public static class SceneEnvironmentProperty{
private List<Scene> scenes=new ArrayList<>();
private EnvironmentModel environmentModel;
private List<String> properties=new ArrayList<>();
private List<Rule> rules=new ArrayList<>();
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
public List<String> getProperties() {
return properties;
}
public void setProperties(List<String> properties) {
this.properties = properties;
}
public List<Scene> getScenes() {
return scenes;
}
public void setScenes(List<Scene> scenes) {
this.scenes = scenes;
}
public EnvironmentModel getEnvironmentModel() {
return environmentModel;
}
public void setEnvironmentModel(EnvironmentModel environmentModel) {
this.environmentModel = environmentModel;
}
}
public static class SceneEnvironmentRule{
private Scene scene;
private EnvironmentModel environmentModel;
private List<Rule> rules=new ArrayList<>();
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public EnvironmentModel getEnvironmentModel() {
return environmentModel;
}
public void setEnvironmentModel(EnvironmentModel environmentModel) {
this.environmentModel = environmentModel;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
}

@ -0,0 +1,24 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class JitterReason {
//////抖动及原因
private List<double[]> jitter=new ArrayList<>(); ///某段抖动 time-value,time-value...
private List<CauseRule> causingRules=new ArrayList<>(); //////原因
public List<double[]> getJitter() {
return jitter;
}
public void setJitter(List<double[]> jitter) {
this.jitter = jitter;
}
public List<CauseRule> getCausingRules() {
return causingRules;
}
public void setCausingRules(List<CauseRule> causingRules) {
this.causingRules = causingRules;
}
}

@ -0,0 +1,159 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class ModelGraph {
//////表示uppaal模型的类
public static class TemplGraph {
private String name=""; /////模型名
private String declaration="";
private String parameter="";
private String init="";
private List<TemplGraphNode> templGraphNodes=new ArrayList<TemplGraphNode>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeclaration() {
return declaration;
}
public void setDeclaration(String declaration) {
this.declaration = declaration;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public String getInit() {
return init;
}
public void setInit(String init) {
this.init = init;
}
public List<TemplGraphNode> getTemplGraphNodes() {
return templGraphNodes;
}
public void setTemplGraphNodes(List<TemplGraphNode> templGraphNodes) {
this.templGraphNodes = templGraphNodes;
}
public void addTemplGraphNode(TemplGraphNode node) {
this.templGraphNodes.add(node);
}
}
/////节点类
public static class TemplGraphNode {
public String name="";
public String id="";
public String invariant="";
public String style=""; //location or branchpoint or committed urgent?
public boolean flag=false;
public List<TemplTransition> inTransitions=new ArrayList<TemplTransition>();
public List<TemplTransition> outTransitions=new ArrayList<TemplTransition>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInvariant() {
return invariant;
}
public void setInvariant(String invariant) {
this.invariant = invariant;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public List<TemplTransition> getInTransitions() {
return inTransitions;
}
public void setInTransitions(List<TemplTransition> inTransitions) {
this.inTransitions = inTransitions;
}
public List<TemplTransition> getOutTransitions() {
return outTransitions;
}
public void setOutTransitions(List<TemplTransition> outTransitions) {
this.outTransitions = outTransitions;
}
}
/////边类
public static class TemplTransition {
public String source="";
public String target="";
public TemplGraphNode node=new TemplGraphNode();
public String assignment="";
public String synchronisation="";
public String guard="";
public String probability=""; //source or target中有branchpoint则有这一项
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public TemplGraphNode getNode() {
return node;
}
public void setNode(TemplGraphNode node) {
this.node = node;
}
public String getAssignment() {
return assignment;
}
public void setAssignment(String assignment) {
this.assignment = assignment;
}
public String getSynchronisation() {
return synchronisation;
}
public void setSynchronisation(String synchronisation) {
this.synchronisation = synchronisation;
}
public String getGuard() {
return guard;
}
public void setGuard(String guard) {
this.guard = guard;
}
public String getProbability() {
return probability;
}
public void setProbability(String probability) {
this.probability = probability;
}
}
}

@ -0,0 +1,35 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class OutputConstruct {
public static class EnvironmentStatic{
private EnvironmentModel environmentModel;
private StaticAnalysisResult staticAnalysisResult;
public EnvironmentStatic() {
super();
}
public EnvironmentStatic(EnvironmentModel environmentModel, StaticAnalysisResult staticAnalysisResult) {
super();
this.environmentModel = environmentModel;
this.staticAnalysisResult = staticAnalysisResult;
}
public EnvironmentModel getEnvironmentModel() {
return environmentModel;
}
public void setEnvironmentModel(EnvironmentModel environmentModel) {
this.environmentModel = environmentModel;
}
public StaticAnalysisResult getStaticAnalysisResult() {
return staticAnalysisResult;
}
public void setStaticAnalysisResult(StaticAnalysisResult staticAnalysisResult) {
this.staticAnalysisResult = staticAnalysisResult;
}
}
}

@ -0,0 +1,30 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class ReachableReason {
///property可达原因
private double[] satisfyIntervalTime; ////满足的区间
private String scenarioName="";
private List<CauseRule> causingRules=new ArrayList<CauseRule>();
public double[] getSatisfyIntervalTime() {
return satisfyIntervalTime;
}
public void setSatisfyIntervalTime(double[] satisfyIntervalTime) {
this.satisfyIntervalTime = satisfyIntervalTime;
}
public List<CauseRule> getCausingRules() {
return causingRules;
}
public void setCausingRules(List<CauseRule> causingRules) {
this.causingRules = causingRules;
}
public String getScenarioName() {
return scenarioName;
}
public void setScenarioName(String scenarioName) {
this.scenarioName = scenarioName;
}
}

@ -0,0 +1,80 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class Rule {
private String ruleName=""; ///规则名序号 rulei
private String ruleContent=""; ///规则内容
private List<String> trigger=new ArrayList<String>(); ////所有triggers
private List<String> action=new ArrayList<String>(); ////所有actions
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getRuleContent() {
return ruleContent;
}
public void setRuleContent(String ruleContent) {
this.ruleContent = ruleContent;
}
public List<String> getTrigger() {
return trigger;
}
public void setTrigger(List<String> trigger) {
this.trigger = trigger;
}
public List<String> getAction() {
return action;
}
public void setAction(List<String> action) {
this.action = action;
}
public boolean contentEquals(Rule rule) {
if(ruleName.equals(rule.getRuleName())) {
return true;
}
if(ruleContent.equals(rule.getRuleContent())) {
return true;
}
if(trigger.size()==rule.getTrigger().size()&&action.size()==rule.getAction().size()) {
boolean equal=true;
for(String tri:trigger) {
boolean exist=false;
for(String tri2:rule.getTrigger()) {
if(tri.equals(tri2)) {
exist=true;
break;
}
}
if(!exist) {
equal=false;
break;
}
}
if(equal) {
for(String act:action) {
boolean exist=false;
for(String act2:rule.getAction()) {
if(act.equals(act2)) {
exist=true;
break;
}
}
if(!exist) {
equal=false;
break;
}
}
}
if(equal) {
return true;
}
}
return false;
}
}

@ -0,0 +1,55 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class RuleNode {
/////用于locate error ,当前规则和会引发这个规则的其他规则
private Rule rule=new Rule(); //////当前规则
private List<RuleNode> preRules=new ArrayList<RuleNode>(); ////会触发该规则的规则
public Rule getRule() {
return rule;
}
public void setRule(Rule rule) {
this.rule = rule;
}
public List<RuleNode> getPreRules() {
return preRules;
}
public void setPreRules(List<RuleNode> preRules) {
this.preRules = preRules;
}
public void setPreRules(int i,RuleNode preRule) {
this.preRules.set(i, preRule);
}
@Override
public String toString() {
StringBuilder preRules=new StringBuilder();
for(RuleNode ruleNode:this.preRules) {
preRules.append(ruleNode.getRule().getRuleName()+" ");
}
return this.rule.getRuleName()+"<---"+preRules.toString();
}
////删除某个pre
public void removePreRule(String ruleName) {
for(RuleNode ruleNode:this.preRules) {
if(ruleNode.getRule().getRuleName().equals(ruleName)) {
this.preRules.remove(ruleNode);
break;
}
}
}
// @Override
// public boolean equals(Object obj) {
// if(obj instanceof RuleNode) {
// RuleNode otherRuleNode=(RuleNode) obj;
// if(otherRuleNode.getRule().getRuleName().equals(otherRuleNode.getRule().getRuleName())) {
// return true;
// }
// }
// return false;
// }
}

@ -0,0 +1,63 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Scene {
/////各个场景分析结果
private String scenarioName=""; ///场景名
private List<DataTimeValue> dataTimeValues=new ArrayList<DataTimeValue>(); ////仿真数据存储格式
private List<DataTimeValue> triggeredRulesName=new ArrayList<DataTimeValue>(); ////可触发的规则
private List<String> cannotTriggeredRulesName=new ArrayList<String>(); //////不可触发的规则
private List<DeviceAnalysisResult> deviceAnalysisResults=new ArrayList<>(); ////各个设备动态分析结果
/////key: dataName, value: [time,value]list
private HashMap<String, List<double[]>> dataTimeValuesHashMap=new HashMap<>();
////keydataName, value: [startTime,Value,EndTime,Value]List
private HashMap<String,List<double[]>> dataStartTimeValueEndTimeValuesHashMap=new HashMap<>();
public String getScenarioName() {
return scenarioName;
}
public void setScenarioName(String scenarioName) {
this.scenarioName = scenarioName;
}
public List<DataTimeValue> getDataTimeValues() {
return dataTimeValues;
}
public void setDataTimeValues(List<DataTimeValue> dataTimeValues) {
this.dataTimeValues = dataTimeValues;
}
public HashMap<String, List<double[]>> getDataTimeValuesHashMap() {
return dataTimeValuesHashMap;
}
public void setDataTimeValuesHashMap(HashMap<String, List<double[]>> dataTimeValuesHashMap) {
this.dataTimeValuesHashMap = dataTimeValuesHashMap;
}
public HashMap<String, List<double[]>> getDataStartTimeValueEndTimeValuesHashMap() {
return dataStartTimeValueEndTimeValuesHashMap;
}
public void setDataStartTimeValueEndTimeValuesHashMap(
HashMap<String, List<double[]>> dataStartTimeValueEndTimeValuesHashMap) {
this.dataStartTimeValueEndTimeValuesHashMap = dataStartTimeValueEndTimeValuesHashMap;
}
public List<DataTimeValue> getTriggeredRulesName() {
return triggeredRulesName;
}
public void setTriggeredRulesName(List<DataTimeValue> triggeredRulesName) {
this.triggeredRulesName = triggeredRulesName;
}
public List<String> getCannotTriggeredRulesName() {
return cannotTriggeredRulesName;
}
public void setCannotTriggeredRulesName(List<String> cannotTriggeredRulesName) {
this.cannotTriggeredRulesName = cannotTriggeredRulesName;
}
public List<DeviceAnalysisResult> getDeviceAnalysisResults() {
return deviceAnalysisResults;
}
public void setDeviceAnalysisResults(List<DeviceAnalysisResult> deviceAnalysisResults) {
this.deviceAnalysisResults = deviceAnalysisResults;
}
}

@ -0,0 +1,19 @@
package com.example.demo.bean;
public class SensorType extends Entity{
public String attribute=""; ///传感器检测什么属性
public String style=""; ///该属性的类型
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}

@ -0,0 +1,53 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class StaticAnalysisResult {
////静态分析结果
private List<ErrorReason> incorrectRules=new ArrayList<ErrorReason>();
private List<ErrorReason> unusedRules=new ArrayList<ErrorReason>();
private List<List<Rule>> redundantRules=new ArrayList<List<Rule>>();
private List<String> incompleteness=new ArrayList<String>();
private List<Rule> usableRules=new ArrayList<Rule>();
private List<Rule> totalRules=new ArrayList<>();
public List<Rule> getTotalRules() {
return totalRules;
}
public void setTotalRules(List<Rule> totalRules) {
this.totalRules = totalRules;
}
public List<ErrorReason> getIncorrectRules() {
return incorrectRules;
}
public void setIncorrectRules(List<ErrorReason> incorrectRules) {
this.incorrectRules = incorrectRules;
}
public List<ErrorReason> getUnusedRules() {
return unusedRules;
}
public void setUnusedRules(List<ErrorReason> unusedRules) {
this.unusedRules = unusedRules;
}
public List<List<Rule>> getRedundantRules() {
return redundantRules;
}
public void setRedundantRules(List<List<Rule>> redundantRules) {
this.redundantRules = redundantRules;
}
public List<String> getIncompleteness() {
return incompleteness;
}
public void setIncompleteness(List<String> incompleteness) {
this.incompleteness = incompleteness;
}
public List<Rule> getUsableRules() {
return usableRules;
}
public void setUsableRules(List<Rule> usableRules) {
this.usableRules = usableRules;
}
}

@ -0,0 +1,42 @@
package com.example.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class Trigger {
public String trigger=""; ///////temperature>=30 //////Bulb_0.bon ///Person.lobby(人在客厅)
public String triggerNum=""; ///////trigger1 //////trigger2 ///trigger3
public String device=""; ///////temperature_sensor //////Bulb_0 ///person_sensor
public String[] attrVal=new String[3]; ///////temperature >= 30 //////Bulb_0 . bon ///position = 1
public List<Rule> rules=new ArrayList<Rule>();
public String getTrigger() {
return trigger;
}
public void setTrigger(String trigger) {
this.trigger = trigger;
}
public String getTriggerNum() {
return triggerNum;
}
public void setTriggerNum(String triggerNum) {
this.triggerNum = triggerNum;
}
public String[] getAttrVal() {
return attrVal;
}
public void setAttrVal(String[] attrVal) {
this.attrVal = attrVal;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.triggerNum+" : "+this.trigger;
}
}

@ -0,0 +1,239 @@
package com.example.demo.controller;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.bean.Attribute;
import com.example.demo.bean.BiddableType;
import com.example.demo.bean.DeviceDetail;
import com.example.demo.bean.DeviceType;
import com.example.demo.bean.EnvironmentModel;
import com.example.demo.bean.Rule;
import com.example.demo.bean.Scene;
import com.example.demo.bean.SensorType;
import com.example.demo.bean.StaticAnalysisResult;
import com.example.demo.bean.IFDGraph.GraphNode;
import com.example.demo.bean.InputConstruct.EnvironmentRule;
import com.example.demo.bean.OutputConstruct.EnvironmentStatic;
import com.example.demo.service.AddressService;
import com.example.demo.service.DynamicAnalysisService;
import com.example.demo.service.RuleService;
import com.example.demo.service.StaticAnalysisService;
import com.example.demo.service.SystemModelService;
import com.example.demo.service.TemplGraphService;
@CrossOrigin
@RestController
//@Controller
@RequestMapping("/visual")
public class Controller {
// @RequestMapping("/upload")
// @ResponseBody
// public void uploadFile(@RequestParam("file") MultipartFile uploadedFile) throws DocumentException, IOException {
// //////////////上传的环境本体文件存储在D:\\workspace位置
// if (uploadedFile == null) {
// System.out.println("上传失败,无法找到文件!");
// }
// //上传xml文件和properties文件
// String fileName = uploadedFile.getOriginalFilename();
// String filePath=AddressService.MODEL_FILE_PATH+fileName;
// BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
//
// outputStream.write(uploadedFile.getBytes());
// outputStream.flush();
// outputStream.close();
// //逻辑处理
// System.out.println(fileName + "上传成功");
// }
@RequestMapping("/upload")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile uploadedFile,HttpServletRequest request) throws DocumentException, IOException {
//////////////上传的环境本体文件存储在D:\\workspace位置
if (uploadedFile == null) {
System.out.println("上传失败,无法找到文件!");
}
//上传xml文件和properties文件
String fileName = uploadedFile.getOriginalFilename();
String filePath=AddressService.MODEL_FILE_PATH+fileName;
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
outputStream.write(uploadedFile.getBytes());
outputStream.flush();
outputStream.close();
//逻辑处理
System.out.println(fileName + "上传成功");
String rules=RuleService.getAudioToRules(fileName, AddressService.MODEL_FILE_PATH, AddressService.CONVERT_TOOL_PATH);
System.out.println(rules);
return rules;
}
// /////静态分析
// @RequestMapping(value="/getStaticAnalysisResult",method = RequestMethod.POST)
// @ResponseBody
// public static EnvironmentStatic getStaticAnalysisResult(@RequestBody List<String> ruleTextLines,String initModelFileName,String propertyFileName) throws DocumentException, IOException {
// /////生成规则结构
// List<Rule> rules=RuleService.getRuleList(ruleTextLines);
// ////设置更改后的模型文件名
// AddressService.setChangedModelFileName(initModelFileName);
// ////获得环境模型
// EnvironmentModel environmentModel=TemplGraphService.getEnvironmentModel(initModelFileName, AddressService.changed_model_file_Name, AddressService.MODEL_FILE_PATH, propertyFileName);
// ////静态分析
// StaticAnalysisResult staticAnalysisResult=StaticAnalysisService.getStaticAnalaysisResult(rules, AddressService.IFD_FILE_NAME, AddressService.IFD_FILE_PATH, environmentModel);
// EnvironmentStatic environmentStatic=new EnvironmentStatic(environmentModel, staticAnalysisResult);
// return environmentStatic;
// }
//
//
// /////生成单个场景模型,并仿真获得分析结果
// @RequestMapping(value="/generateBestScenarioModelAndSimulate",method = RequestMethod.POST)
// @ResponseBody
// public static Scene generateBestScenarioModelAndSimulate(@RequestBody List<String> ruleTextLines,String initModelFileName,String propertyFileName,String simulationTime) throws DocumentException, IOException {
// ////更改后的模型文件名
// EnvironmentStatic environmentStatic=getStaticAnalysisResult(ruleTextLines,initModelFileName,propertyFileName);
// EnvironmentModel environmentModel=environmentStatic.getEnvironmentModel();
//
// String fileNameWithoutSuffix=initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"));
// List<Rule> rules=environmentStatic.getStaticAnalysisResult().getUsableRules();
// List<DeviceDetail> devices=environmentModel.getDevices();
// List<DeviceType> deviceTypes=environmentModel.getDeviceTypes();
// List<BiddableType> biddableTypes=environmentModel.getBiddables();
// List<SensorType> sensorTypes=environmentModel.getSensors();
// List<Attribute> attributes=environmentModel.getAttributes();
// ////ruleMap
// HashMap<String,Rule> ruleMap=new HashMap<>();
// for(Rule rule:rules) {
// ruleMap.put(rule.getRuleName(), rule);
// }
// /////获得ifd上各节点
// List<GraphNode> graphNodes=StaticAnalysisService.getIFDNode(AddressService.IFD_FILE_NAME, AddressService.IFD_FILE_PATH);
// SystemModelService.generateContrModel(AddressService.MODEL_FILE_PATH+AddressService.changed_model_file_Name, rules, biddableTypes, devices);
// SystemModelService.generateBestScenarioModel(rules, devices, deviceTypes, biddableTypes, sensorTypes, attributes, AddressService.changed_model_file_Name, AddressService.MODEL_FILE_PATH, graphNodes, fileNameWithoutSuffix+"-scenario-best.xml", simulationTime);
//
// ///仿真
// Scene scene=DynamicAnalysisService.getSingleSimulationResult(devices, AddressService.UPPAAL_PATH, fileNameWithoutSuffix, "best", AddressService.MODEL_FILE_PATH, AddressService.SIMULATE_RESULT_FILE_PATH);
// ///动态分析
// DynamicAnalysisService.getSingleScenarioDynamicAnalysis(scene, devices, graphNodes, ruleMap);
// return scene;
// }
//
// /////仿真结果可视化返回video存放路径
// @RequestMapping(value="/getVisualizationResult",method = RequestMethod.GET)
// @ResponseBody
// public static List<String> getVisualizationResult(String initModelFileName) throws DocumentException, IOException {
//// String fileNameWithoutSuffix=initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"));
//// String bestResultFileName=fileNameWithoutSuffix+"-scenario-best.txt";
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// String path=AddressService.VIDEO_PATH+"video.mp4";
// List<String> path0=new ArrayList<String>();
// System.out.println(path);
// path0.add("video.mp4");
//
// return path0;
// }
@RequestMapping(value="/getRules",method = RequestMethod.POST)
@ResponseBody
public static String getRules(String audioFileName,String audioFilePath) throws DocumentException, IOException {
/////生成规则结构
RuleService.getAudioToRules(audioFileName, audioFilePath, AddressService.CONVERT_TOOL_PATH);
return "good";
}
/////静态分析
@RequestMapping(value="/getStaticAnalysisResult",method = RequestMethod.POST)
@ResponseBody
public static EnvironmentStatic getStaticAnalysisResult(@RequestBody List<String> ruleTextLines,String initModelFileName,String propertyFileName) throws DocumentException, IOException {
/////生成规则结构
List<Rule> rules=RuleService.getRuleList(ruleTextLines);
////设置更改后的模型文件名
AddressService.setChangedModelFileName(initModelFileName);
////获得环境模型
EnvironmentModel environmentModel=TemplGraphService.getEnvironmentModel(initModelFileName, AddressService.changed_model_file_Name, AddressService.MODEL_FILE_PATH, propertyFileName);
////静态分析
StaticAnalysisResult staticAnalysisResult=StaticAnalysisService.getStaticAnalaysisResult(rules, AddressService.IFD_FILE_NAME, AddressService.IFD_FILE_PATH, environmentModel);
EnvironmentStatic environmentStatic=new EnvironmentStatic(environmentModel, staticAnalysisResult);
return environmentStatic;
}
/////生成单个场景模型,并仿真获得分析结果
@RequestMapping(value="/generateBestScenarioModelAndSimulate",method = RequestMethod.POST)
@ResponseBody
public static Scene generateBestScenarioModelAndSimulate(@RequestBody List<String> ruleTextLines) throws DocumentException, IOException {
////更改后的模型文件名
EnvironmentStatic environmentStatic=getStaticAnalysisResult(ruleTextLines,AddressService.ONTOLOGY_FILE_NAME,AddressService.DEVICE_POSITION_INFORMATION_FILE_NAME);
EnvironmentModel environmentModel=environmentStatic.getEnvironmentModel();
//固定仿真时间
String simulationTime="300";
String fileNameWithoutSuffix=AddressService.ONTOLOGY_FILE_NAME.substring(0, AddressService.ONTOLOGY_FILE_NAME.lastIndexOf(".xml"));
List<Rule> rules=environmentStatic.getStaticAnalysisResult().getUsableRules();
List<DeviceDetail> devices=environmentModel.getDevices();
List<DeviceType> deviceTypes=environmentModel.getDeviceTypes();
List<BiddableType> biddableTypes=environmentModel.getBiddables();
List<SensorType> sensorTypes=environmentModel.getSensors();
List<Attribute> attributes=environmentModel.getAttributes();
////ruleMap
HashMap<String,Rule> ruleMap=new HashMap<>();
for(Rule rule:rules) {
ruleMap.put(rule.getRuleName(), rule);
}
/////获得ifd上各节点
List<GraphNode> graphNodes=StaticAnalysisService.getIFDNode(AddressService.IFD_FILE_NAME, AddressService.IFD_FILE_PATH);
SystemModelService.generateContrModel(AddressService.MODEL_FILE_PATH+AddressService.changed_model_file_Name, rules, biddableTypes, devices);
SystemModelService.generateBestScenarioModel(rules, devices, deviceTypes, biddableTypes, sensorTypes, attributes, AddressService.changed_model_file_Name, AddressService.MODEL_FILE_PATH, graphNodes, fileNameWithoutSuffix+"-scenario-best.xml", simulationTime);
///仿真
Scene scene=DynamicAnalysisService.getSingleSimulationResult(devices, AddressService.UPPAAL_PATH, fileNameWithoutSuffix, "best", AddressService.MODEL_FILE_PATH, AddressService.SIMULATE_RESULT_FILE_PATH);
///动态分析
DynamicAnalysisService.getSingleScenarioDynamicAnalysis(scene, devices, graphNodes, ruleMap);
return scene;
}
/////仿真结果可视化返回video存放路径
@RequestMapping(value="/getVisualizationResult",method = RequestMethod.GET)
@ResponseBody
public static List<String> getVisualizationResult() throws DocumentException, IOException {
// String fileNameWithoutSuffix=initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"));
// String bestResultFileName=fileNameWithoutSuffix+"-scenario-best.txt";
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String path="video.mp4";
List<String> path0=new ArrayList<String>();
System.out.println(path);
path0.add("video.mp4");
return path0;
}
}

@ -0,0 +1,36 @@
package com.example.demo.service;
public class AddressService {
public final static String MODEL_FILE_PATH= "D:\\workspace\\modelFile\\";
public final static String UPPAAL_PATH="D:\\tools\\uppaal-4.1.24\\uppaal-4.1.24\\bin-Windows\\";
public final static String IFD_FILE_PATH="D:\\workspace\\ifdFile\\";
public final static String IFD_FILE_NAME="ifd.dot";
public final static String SIMULATE_RESULT_FILE_PATH="D:\\workspace\\resultFile\\";
public final static String VIDEO_PATH="D:\\workspace\\videoFile\\";
public final static String CONVERT_TOOL_PATH="D:\\workspace\\c2t\\c2t\\";
// public final static String MODEL_FILE_PATH= "/root/TAPs-Visual/workspace/modelFile/";
// public final static String UPPAAL_PATH="/root/TAPs/workspace/uppaal64-4.1.24/bin-Linux/";
// public final static String IFD_FILE_PATH="/root/TAPs-Visual/workspace/ifdFile/";
// public final static String IFD_FILE_NAME="ifd.dot";
// public final static String SIMULATE_RESULT_FILE_PATH="/root/TAPs-Visual/workspace/resultFile/";
// public final static String VIDEO_PATH="/root/public_html/TAPs-Visual/assets/";
public final static String ONTOLOGY_FILE_NAME="ontology.xml";
public final static String DEVICE_POSITION_INFORMATION_FILE_NAME="devicePositionInformation.properties";
public static String changed_model_file_Name;
public static String best_model_file_name;
public static String getBest_model_file_name() {
return best_model_file_name;
}
public static void setBest_model_file_name(String initModelFileName) {
AddressService.best_model_file_name = initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"))+"-scenario-best.xml";
}
private AddressService() {
}
public final static void setChangedModelFileName(String initModelFileName) {
changed_model_file_Name=initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"))+"-changed.xml";
}
}

@ -0,0 +1,379 @@
package com.example.demo.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
@Service
public class GetTemplate {
//////该类解析uppaal的xml文件
public static void main(String[] args) throws DocumentException {
// // TODO Auto-generated method stub
// String path1 = "D:\\window16.xml";
// String path2="D:\\win16.xml";
// //删除xml文件第二行
//
// GetTemplate parse=new GetTemplate();
//
// parse.deletLine(path1, path2, 2);
// List<Template> templates=parse.getTemplate(path2);
// List<ControlledDevice> controlledDevices=parse.getControlled(templates);
// List<Sensor> sensors=parse.getSensor(templates);
// Rain rain=parse.getRain(templates);
}
////////////////Template///////////////////////////////
public class Template{
public String name="";
public String declaration="";
public String parameter="";
public List<Location> locations= new ArrayList<Location>();
public List<Branchpoint> branchpoints=new ArrayList<Branchpoint>();
public String init="";
public List<Transition> transitions=new ArrayList<Transition>();
}
class Location{
String id="";
String name="";
String invariant="";
String style="";
}
class Branchpoint{
String id="";
}
class Transition{
String sourceId="";
String targetId="";
List<Label> labels=new ArrayList<Label>();
}
class Label{
String kind="";
String content="";
}
public List<Template> getTemplate(File file) throws DocumentException{
List<Template> templates=new ArrayList<Template>();
if(file.getName().indexOf(".xml")>=0) {
SAXReader reader= new SAXReader();
Document document = reader.read(file);
Element rootElement=document.getRootElement();
System.out.println(rootElement.getName());
List<Element> templateElements=rootElement.elements("template");
for(Element tempElement:templateElements) {
System.out.println(tempElement.getName());
//解析获得template
Template template=new Template();
//name
Element nameElement=tempElement.element("name");
template.name=nameElement.getTextTrim();
System.out.println(nameElement.getName());
//declaration
Element declarElement=tempElement.element("declaration");
if(declarElement!=null) {
template.declaration=declarElement.getText();
System.out.println(declarElement.getName());
}
//parameter
Element paraElement=tempElement.element("parameter");
if(paraElement!=null) {
template.parameter=paraElement.getTextTrim();
System.out.println(paraElement.getName());
}
//locations
List<Element> locaElements=tempElement.elements("location");
for(Element locaElement:locaElements) {
System.out.println(locaElement.getName());
Location location=new Location();
Attribute attr=locaElement.attribute("id");
location.id=attr.getValue();
System.out.println();
System.out.println(location.id);
System.out.println();
Element locaNameElement=locaElement.element("name");
if(locaNameElement!=null) {
location.name=locaNameElement.getTextTrim();
System.out.println(locaElement.getName());
}
Element invaElement=locaElement.element("label");
if(invaElement!=null) {
location.invariant=invaElement.getTextTrim();
System.out.println(invaElement.getName());
}
Element urgentElement=locaElement.element("urgent");
if(urgentElement!=null) {
location.style="urgent";
}
Element committedElement=locaElement.element("committed");
if(committedElement!=null) {
location.style="committed";
}
if(urgentElement==null&&committedElement==null) {
location.style="location";
}
template.locations.add(location);
}
//branchpoint
List<Element> branElements=tempElement.elements("branchpoint");
if(branElements!=null) {
for(Element branElement:branElements) {
Branchpoint branchpoint=new Branchpoint();
Attribute attr=branElement.attribute("id");
branchpoint.id=attr.getValue();
template.branchpoints.add(branchpoint);
System.out.println(branElement.getName());
}
}
//init
Element initElement=tempElement.element("init");
Attribute initAttr=initElement.attribute("ref");
template.init=initAttr.getValue();
System.out.println(initElement.getName());
//transitions
List<Element> tranElements=tempElement.elements("transition");
for(Element tranElement:tranElements) {
System.out.println(tranElement.getName());
Transition transition=new Transition();
Element sourceElement=tranElement.element("source");
Attribute sourAttr=sourceElement.attribute("ref");
transition.sourceId=sourAttr.getValue();
System.out.println(sourceElement.getName());
Element targetElement=tranElement.element("target");
Attribute tarAttr=targetElement.attribute("ref");
transition.targetId=tarAttr.getValue();
System.out.println(targetElement.getName());
List<Element> labelElements=tranElement.elements("label");
if(labelElements!=null) {
for(Element labelElement:labelElements) {
System.out.println(labelElement.getName());
Label label=new Label();
Attribute kindAttr=labelElement.attribute("kind");
label.kind=kindAttr.getValue();
label.content=labelElement.getTextTrim();
transition.labels.add(label);
}
}
template.transitions.add(transition);
}
//添加template
templates.add(template);
}
}else {
System.out.println("please upload .xml file");
}
return templates;
}
//解析xml文件获得template
public List<Template> getTemplate(String path) throws DocumentException{
SAXReader reader= new SAXReader();
Document document = reader.read(new File(path));
Element rootElement=document.getRootElement();
// System.out.println(rootElement.getName());
List<Element> templateElements=rootElement.elements("template");
List<Template> templates=new ArrayList<Template>();
for(Element tempElement:templateElements) {
// System.out.println(tempElement.getName());
//解析获得template
Template template=new Template();
//name
Element nameElement=tempElement.element("name");
template.name=nameElement.getTextTrim();
// System.out.println(nameElement.getName());
//declaration
Element declarElement=tempElement.element("declaration");
if(declarElement!=null) {
template.declaration=declarElement.getText();
// System.out.println(declarElement.getName());
}
//parameter
Element paraElement=tempElement.element("parameter");
if(paraElement!=null) {
template.parameter=paraElement.getTextTrim();
// System.out.println(paraElement.getName());
}
//locations
List<Element> locaElements=tempElement.elements("location");
for(Element locaElement:locaElements) {
// System.out.println(locaElement.getName());
Location location=new Location();
Attribute attr=locaElement.attribute("id");
location.id=attr.getValue();
// System.out.println();
// System.out.println(location.id);
// System.out.println();
Element locaNameElement=locaElement.element("name");
if(locaNameElement!=null) {
location.name=locaNameElement.getTextTrim();
// System.out.println(locaElement.getName());
}
Element invaElement=locaElement.element("label");
if(invaElement!=null) {
location.invariant=invaElement.getTextTrim();
// System.out.println(invaElement.getName());
}
Element urgentElement=locaElement.element("urgent");
if(urgentElement!=null) {
location.style="urgent";
}
Element committedElement=locaElement.element("committed");
if(committedElement!=null) {
location.style="committed";
}
if(urgentElement==null&&committedElement==null) {
location.style="location";
}
template.locations.add(location);
}
//branchpoint
List<Element> branElements=tempElement.elements("branchpoint");
if(branElements!=null) {
for(Element branElement:branElements) {
Branchpoint branchpoint=new Branchpoint();
Attribute attr=branElement.attribute("id");
branchpoint.id=attr.getValue();
template.branchpoints.add(branchpoint);
// System.out.println(branElement.getName());
}
}
//init
Element initElement=tempElement.element("init");
Attribute initAttr=initElement.attribute("ref");
template.init=initAttr.getValue();
// System.out.println(initElement.getName());
//transitions
List<Element> tranElements=tempElement.elements("transition");
for(Element tranElement:tranElements) {
// System.out.println(tranElement.getName());
Transition transition=new Transition();
Element sourceElement=tranElement.element("source");
Attribute sourAttr=sourceElement.attribute("ref");
transition.sourceId=sourAttr.getValue();
// System.out.println(sourceElement.getName());
Element targetElement=tranElement.element("target");
Attribute tarAttr=targetElement.attribute("ref");
transition.targetId=tarAttr.getValue();
// System.out.println(targetElement.getName());
List<Element> labelElements=tranElement.elements("label");
if(labelElements!=null) {
for(Element labelElement:labelElements) {
// System.out.println(labelElement.getName());
Label label=new Label();
Attribute kindAttr=labelElement.attribute("kind");
label.kind=kindAttr.getValue();
label.content=labelElement.getTextTrim();
transition.labels.add(label);
}
}
template.transitions.add(transition);
}
//添加template
templates.add(template);
}
return templates;
}
public static void deleteFileLine(String path1,String path2,int lineNum) {
try (FileReader fr=new FileReader(path1);
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter(path2);
BufferedWriter bw=new BufferedWriter(fw)){
StringBuilder sb=new StringBuilder();
String line="";
int count=0;
while((line=br.readLine())!=null) {
count++;
if(count==lineNum) {
line="\r\n";
}
sb.append(line+"\r\n");
}
bw.write(sb.toString());
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
// //删除文档中的特定行,并写到新文档
// public void deletLine(String path1,String path2,int lineNum) {
// try {
// FileReader fr= new FileReader(path1);
// BufferedReader br=new BufferedReader(fr);
// File file = new File(path2);
// if(!file.exists()) {
// try {
// file.createNewFile();
// }catch(IOException e) {
// e.printStackTrace();
// }
// }
//
// String line="";
// int count=1;
// write(file,br.readLine(),false);
// count++;
// while((line=br.readLine())!=null) {
// if(count==lineNum) {
// write(file,"",true);
// count++;
// continue;
// }
// write(file,line,true);
// count++;
// }
//
// br.close();
// fr.close();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// //写文档
// public void write(File file, String line, boolean conti) throws IOException {
// Writer writer=new FileWriter(file, conti);
// StringBuilder stringBuilder=new StringBuilder();
// stringBuilder.append(line+"\r\n");
// writer.write(stringBuilder.toString());
// writer.close();
// }
//
// //split
// public List<String> splitStr(String str,String splitStr){
// return Arrays.asList(str.split(splitStr));
// }
//
}

@ -0,0 +1,17 @@
package com.example.demo.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.stereotype.Service;
@Service
public class PropertyService {
public static Properties getProperties(String filePath,String propertyFileName) throws FileNotFoundException, IOException {
Properties properties=new Properties();
properties.load(new FileInputStream(filePath+propertyFileName));
return properties;
}
}

@ -0,0 +1,470 @@
package com.example.demo.service;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.demo.bean.Action;
import com.example.demo.bean.BiddableType;
import com.example.demo.bean.DeviceDetail;
import com.example.demo.bean.Rule;
import com.example.demo.bean.SensorType;
import com.example.demo.bean.Trigger;
@Service
public class RuleService {
public static void main(String[] args) throws IOException {
RuleService ruleService=new RuleService();
String ruleStrList="1. IF SmartHomeSecurity.homeMode AND temperature<=15 THEN Heater.turn_heat_on\r\n" +
"\r\n" +
"2. IF SmartHomeSecurity.homeMode AND temperature>=30 THEN AirConditioner.turn_ac_cool\r\n" +
"\r\n" +
"3. IF SmartHomeSecurity.homeMode AND humidity<20 THEN Humidifier.turn_hum_on\r\n" +
"\r\n" +
"4. IF SmartHomeSecurity.homeMode AND humidity>=45 THEN Humidifier.turn_hum_off\r\n" +
"\r\n" +
"5. IF SmartHomeSecurity.homeMode AND humidity>65 THEN Fan.turn_fan_on\r\n" +
"\r\n" +
"6. IF SmartHomeSecurity.homeMode AND temperature>28 THEN Fan.turn_fan_on\r\n" +
"\r\n" +
"7. IF SmartHomeSecurity.homeMode AND temperature<20 THEN Fan.turn_fan_off\r\n" +
"\r\n" +
"8. IF SmartHomeSecurity.homeMode AND rain=1 THEN PhilipsHueLight.turn_phl_white\r\n" +
"\r\n" +
"9. IF SmartHomeSecurity.homeMode AND temperature<=10 THEN PhilipsHueLight.turn_phl_blue\r\n" +
"\r\n" +
"10. IF SmartHomeSecurity.homeMode AND leak=1 THEN PhilipsHueLight.turn_phl_blue\r\n" +
"\r\n" +
"11. IF SmartHomeSecurity.awayMode THEN PhilipsHueLight.turn_phl_off\r\n" +
"\r\n" +
"12. IF SmartHomeSecurity.homeMode THEN PhilipsHueLight.turn_phl_white\r\n" +
"\r\n" +
"13. IF Door.dopen THEN PhilipsHueLight.turn_phl_white\r\n" +
"\r\n" +
"14. IF SmartHomeSecurity.homeMode AND co2ppm>=1000 THEN PhilipsHueLight.turn_phl_red\r\n" +
"\r\n" +
"15. IF SmartHomeSecurity.awayMode THEN Fan.turn_fan_on\r\n" +
"\r\n" +
"16. IF Door.dopen THEN Heater.turn_heat_off\r\n" +
"\r\n" +
"17. IF Window.wopen THEN Heater.turn_heat_off\r\n" +
"\r\n" +
"18. IF SmartHomeSecurity.awayMode THEN Heater.turn_heat_off,AirConditioner.turn_ac_off,Fan.turn_fan_off,Blind.close_blind,Bulb.turn_bulb_off\r\n" +
"\r\n" +
"19. IF SmartHomeSecurity.homeMode AND temperature<18 THEN AirConditioner.turn_ac_heat\r\n" +
"\r\n" +
"20. IF SmartHomeSecurity.homeMode AND temperature>30 THEN AirConditioner.turn_ac_cool\r\n" +
"\r\n" +
"21. IF SmartHomeSecurity.homeMode THEN Robot.dock_robot\r\n" +
"\r\n" +
"22. IF SmartHomeSecurity.awayMode THEN Robot.start_robot\r\n" +
"\r\n" +
"23. IF SmartHomeSecurity.awayMode THEN Window.close_window,Door.close_door\r\n" +
"\r\n" +
"24. IF number>0 THEN SmartHomeSecurity.turn_sms_home\r\n" +
"\r\n" +
"25. IF number=0 THEN SmartHomeSecurity.turn_sms_away\r\n" +
"\r\n" +
"26. IF SmartHomeSecurity.homeMode AND temperature>28 THEN Blind.open_blind\r\n" +
"\r\n" +
"27. IF SmartHomeSecurity.homeMode THEN Bulb.turn_on_bulb\r\n" +
"\r\n" +
"28. IF SmartHomeSecurity.homeMode AND co2ppm>=800 THEN Fan.turn_on_fan,Window.open_window\r\n" +
"\r\n" +
"29. IF AirConditioner.cool THEN Window.close_window\r\n" +
"\r\n" +
"30. IF AirConditioner.heat THEN Window.close_window";
List<Rule> rules=getRuleList(ruleStrList);
System.out.println(rules);
String rulePath="D:\\rules0105new.txt";
List<Rule> txtRules=ruleService.getRuleListFromTxt(rulePath);
System.out.println(txtRules);
}
//////////////////////////////解析rule//////////////////////////////
public static Rule getRule(String ruleStr,int num) {
Rule rule=null;
if(ruleStr.endsWith("\r\n")) {
ruleStr=ruleStr.substring(0, ruleStr.indexOf("\r\n"));
}
if(ruleStr.endsWith("\n")) {
ruleStr=ruleStr.substring(0, ruleStr.indexOf("\n"));
}
ruleStr=ruleStr.trim();
if(ruleStr!=null && ruleStr.toUpperCase().indexOf("IF ")>=0 &&
ruleStr.toUpperCase().indexOf(" THEN ")>0) {
rule=new Rule();
int ifIndex=ruleStr.toUpperCase().indexOf("IF "); //////IF 的下标
int thenIndex=ruleStr.toUpperCase().indexOf(" THEN "); //////THEN 的下标
if(ifIndex>=thenIndex) {
System.out.println(ruleStr+"\n not rule!");
rule=null;
}else {
rule.setRuleName("rule"+num); ///////规则的序号 rule1
rule.setRuleContent(ruleStr.substring(ruleStr.toUpperCase().indexOf("IF "))); /////规则内容 IF...THEN...
String triggerStr=ruleStr.substring(ifIndex, thenIndex).substring("IF ".length()).trim(); ////trigger字符串串
String actionStr=ruleStr.substring(thenIndex).substring(" THEN ".length()).trim(); /////action字符串
List<String> triggers=Arrays.asList(triggerStr.split("AND")); ////trigger列表
List<String> actions=Arrays.asList(actionStr.split(",")); /////action列表
for(int i=0;i<triggers.size();i++) {
String trigger=triggers.get(i).trim();
triggers.set(i, trigger);
}
rule.setTrigger(triggers);
for(int i=0;i<actions.size();i++) {
String action=actions.get(i).trim();
actions.set(i, action);
}
rule.setAction(actions);
}
}
return rule;
}
/////////////////解析所有规则
public static List<Rule> getRuleList(List<String> ruleTextLines){
List<Rule> rules=new ArrayList<Rule>();
List<String> ruleStrList=new ArrayList<String>();;
for(String ruleTextLine:ruleTextLines) {
////////找到含IF...THEN...的行
if(ruleTextLine!=null && ruleTextLine.toUpperCase().indexOf("IF ")>=0 &&
ruleTextLine.toUpperCase().indexOf(" THEN ")>0) {
ruleTextLine=ruleTextLine.substring(ruleTextLine.toUpperCase().indexOf("IF "));
ruleStrList.add(ruleTextLine);
}
}
for(int i=0;i<ruleStrList.size();i++) {
String ruleStr=ruleStrList.get(i);
////////解析IF...THEN... 获得Rule结构的rule
Rule rule=getRule(ruleStr, i+1);
if(rule!=null) {
rules.add(rule);
}
}
return rules;
}
public static List<Action> getAllActions(List<Rule> rules,List<DeviceDetail> devices){
List<Action> actions=new ArrayList<Action>(); ///存所有actions
for(Rule rule:rules) {
for(String action:rule.getAction()) { //////遍历一条规则的所有actions
boolean exist=false;
for(Action act:actions) {
if(act.action.equals(action)) { ////看是否已经存在于 actions 中
exist=true;
break;
}
}
if(!exist) { ////不存在就添加
Action act=new Action();
act.action=action; /////action内容 Bulb_0.turn_bulb_on
act.actionNum="action"+actions.size(); ///action序号用于ifd中action0
if(action.indexOf(".")>0) {
act.actionPulse=action.substring(action.indexOf(".")).substring(1).trim(); ///actionPulse: turn_bulb)on
act.device=action.substring(0, action.indexOf(".")); /////device: Bulb_0
}else {
act.actionPulse=action;
}
for(DeviceDetail device:devices) {
if(device.getDeviceName().equals(act.device)) {
for(String[] stateActionValue:device.getDeviceType().stateActionValues) {
if(stateActionValue[1].equals(act.actionPulse)) {
act.toState=stateActionValue[0]; //////找到这个action对应的状态
act.value=stateActionValue[2]; //////和标识符的取值
break;
}
}
break;
}
}
for(Rule otherRule:rules) {
for(String oAction:otherRule.getAction()) {
////////获得有这个action的所有规则
if(oAction.equals(act.action)) {
act.rules.add(otherRule);
break;
}
}
}
actions.add(act);
}
}
}
return actions;
}
//////////获得一组规则的所有triggers
public static List<Trigger> getAllTriggers(List<Rule> rules,List<SensorType> sensors,List<BiddableType> biddables){
List<Trigger> triggers=new ArrayList<Trigger>(); ///存所有triggers
for(Rule rule:rules) {
for(String trigger:rule.getTrigger()) { //////遍历一条规则的所有triggers
boolean exist=false;
for(Trigger tri:triggers) {
if(tri.trigger.equals(trigger)) { ////看是否已经存在于 triggers 中
exist=true;
break;
}
}
if(!exist) { ////不存在就添加
Trigger tri=new Trigger();
tri.trigger=trigger; /////trigger内容
tri.triggerNum="trigger"+triggers.size(); ///trigger序号用于ifd中
tri.attrVal=getTriAttrVal(trigger,biddables); /////分析trigger
if(!tri.attrVal[1].equals(".")){
for(SensorType sensor:sensors) {
if(sensor.attribute.equals(tri.attrVal[0])) {
tri.device=sensor.getName();
break;
}
}
}else {
tri.device=tri.attrVal[0];
}
for(Rule otherRule:rules) {
////////获得有这个trigger的所有规则
for(String oTrigger:otherRule.getTrigger()) {
if(oTrigger.equals(tri.trigger)) {
tri.rules.add(otherRule);
break;
}
}
}
triggers.add(tri);
}
}
}
return triggers;
}
public static String[] getTriAttrVal(String trigger,List<BiddableType> biddables) {
String[] attrVal=new String[3];
if(trigger.contains(">=")) {
attrVal[1]=">=";
attrVal[0]=trigger.substring(0,trigger.indexOf(">=")).trim();
attrVal[2]=trigger.substring(trigger.indexOf(">=")).substring(2).trim();
}else if(trigger.contains(">")) {
attrVal[1]=">";
attrVal[0]=trigger.substring(0, trigger.indexOf(">")).trim();
attrVal[2]=trigger.substring(trigger.indexOf(">")).substring(1).trim();
}else if(trigger.contains("<=")) {
attrVal[1]="<=";
attrVal[0]=trigger.substring(0,trigger.indexOf("<=")).trim();
attrVal[2]=trigger.substring(trigger.indexOf("<=")).substring(2).trim();
}else if(trigger.contains("<")) {
attrVal[1]="<";
attrVal[0]=trigger.substring(0, trigger.indexOf("<")).trim();
attrVal[2]=trigger.substring(trigger.indexOf("<")).substring(1).trim();
}else if(trigger.contains("=")) {
attrVal[1]="=";
attrVal[0]=trigger.substring(0,trigger.indexOf("=")).trim();
attrVal[2]=trigger.substring(trigger.indexOf("=")).substring(1).trim();
}else if(trigger.contains(".")) {
//////表示实体状态 Bulb_0.bon Person.lobby
attrVal[1]=".";
attrVal[0]=trigger.substring(0, trigger.indexOf(".")).trim();
attrVal[2]=trigger.substring(trigger.indexOf(".")).substring(1).trim();
boolean isNot=false;
////非
if(attrVal[0].toUpperCase().startsWith("NOT_")) {
attrVal[0]=attrVal[0].substring("NOT_".length());
isNot=true;
}
for(BiddableType biddable:biddables) {
if(biddable.getName().equals(attrVal[0])) { /////不是设备而是biddable实体的状态如Person
for(String[] stateAttributeValue:biddable.stateAttributeValues) {
if(stateAttributeValue[0].equals(attrVal[2])) {
/////////找到state对应的属性值
attrVal[0]=stateAttributeValue[1];
if(isNot) {
attrVal[1]="!=";
}else {
attrVal[1]="=";
}
attrVal[2]=stateAttributeValue[2];
break;
}
}
}
}
}
return attrVal;
}
///////////////////////////从字符串获得所有规则//////////////////////////////////
public static List<Rule> getRuleList(String ruleTxt){
List<String> ruleStrList=new ArrayList<String>();
int changeLine=0;
if(ruleTxt.indexOf("\r\n")>0) {
changeLine=1;
}else if(ruleTxt.indexOf("\n")>0) {
changeLine=2;
}
//////////////////////换行了才能算///////////////////////
List<String> strList=new ArrayList<String>();
if(changeLine==1) {
strList=Arrays.asList(ruleTxt.split("\r\n"));
}else if(changeLine==2) {
strList=Arrays.asList(ruleTxt.split("\n"));
}
for(String str:strList) {
if(str!=null && str.toUpperCase().indexOf("IF ")>=0 &&
str.toUpperCase().indexOf(" THEN ")>0) {
ruleStrList.add(str);
}
}
List<Rule> rules=new ArrayList<Rule>();
for(int i=0;i<ruleStrList.size();i++) {
String ruleStr=ruleStrList.get(i);
Rule rule=getRule(ruleStr, i+1);
if(rule!=null) {
rules.add(rule);
}
}
return rules;
}
public List<Rule> getRuleListFromTxt(String path){
List<String> ruleStrList=new ArrayList<String>();
List<Rule> rules=new ArrayList<Rule>();
try {
FileReader fr=new FileReader(path);
BufferedReader br=new BufferedReader(fr);
String str="";
while((str=br.readLine())!=null) {
if(str!=null && str.toUpperCase().indexOf("IF ")>=0 &&
str.toUpperCase().indexOf(" THEN ")>0) {
ruleStrList.add(str);
}
}
br.close();
fr.close();
} catch(IOException e) {
e.printStackTrace();
}
for(int i=0;i<ruleStrList.size();i++) {
String ruleStr=ruleStrList.get(i);
Rule rule=getRule(ruleStr, i+1);
if(rule!=null) {
rules.add(rule);
}
}
return rules;
}
public static String getAudioToRules(String audioFileName,String audioPath,String convertToolPath) {
InputStream error = null;
try {
// System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(getCMDCommand(convertToolPath, audioFileName, audioPath));
error = process.getErrorStream();
// long startTime0=System.currentTimeMillis();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(),Charset.forName("UTF-8")));
BufferedReader errorReader=new BufferedReader(new InputStreamReader(error,Charset.forName("GBK")));
// long endTime0=System.currentTimeMillis();
// System.out.println("simulationData time: "+(endTime0-startTime0));
StringBuffer resultBuffer = new StringBuffer();
String s = "";
s = bufferedReader.readLine();
if(s==null) {
System.out.println("null");
}
while (s != null) {
System.out.println(s);
// System.out.println(s);
s=s.substring(1, s.length()-1);
String[] ss=s.split(",");
for(int i=0;i<ss.length;i++) {
ss[i]=ss[i].trim();
if(ss[i].startsWith("'")&&ss[i].endsWith("'")) {
ss[i]=ss[i].substring(1, ss[i].length()-1);
System.out.println(ss[i]);
resultBuffer.append(ss[i]+"\n");
}
}
// long startTime=System.currentTimeMillis();
s = bufferedReader.readLine();
// long endTime=System.currentTimeMillis();
// System.out.println("readline time: "+(endTime-startTime));
// if(s!=null) {
// System.out.println(s.toString());
// }
}
s=errorReader.readLine();
while(s!=null) {
System.out.println(s);
s=errorReader.readLine();
}
bufferedReader.close();
errorReader.close();
process.waitFor();
String result=resultBuffer.toString();
// int formulaIsSatisfiedIndex=result.indexOf("Formula is satisfied.");
// if(formulaIsSatisfiedIndex>=0) {
// result=result.substring(formulaIsSatisfiedIndex).substring("Formula is satisfied.".length());
// }
return result;
} catch (Exception ex) {
if (error != null) {
try {
error.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ex.getMessage();
}
}
public static String getCMDCommand(String convertToolPath,String audioFileName,String audioFilePath) {
StringBuffer command = new StringBuffer();
command.append("cmd /c d:");
//这里的&&在多条语句的情况下使用,表示等上一条语句执行成功后在执行下一条命令,
//也可以使用&表示执行上一条后台就立刻执行下一条语句
command.append(String.format("&& cd %s",convertToolPath));
command.append(String.format(" && python %s %s","c2t.py",audioFilePath+audioFileName));
System.out.println(command.toString());
return command.toString();
}
public static String getLinuxCommand(String convertToolPath,String audioFileName,String audioFilePath) {
StringBuffer command = new StringBuffer();
//这里的&&在多条语句的情况下使用,表示等上一条语句执行成功后在执行下一条命令,
//也可以使用&表示执行上一条后台就立刻执行下一条语句
command.append(String.format("cd %s", convertToolPath));
command.append(String.format("&& python %s %s", "c2t.py",audioFilePath+audioFileName));
return command.toString();
}
}

@ -0,0 +1,94 @@
package com.example.demo.service;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.demo.bean.DataTimeValue;
import com.example.demo.bean.DeviceDetail;
import com.example.demo.bean.Scene;
import com.example.demo.service.DynamicAnalysisService;
public class SimulationThreadService extends Thread{
//////仿真线程,每个场景为一个线程
private List<Scene> scenes;
private List<DeviceDetail> devices;
private String uppaalPath;
private String fileNameWithoutSuffix; ////xml文件去掉后缀名
private String scenarioNum; /////场景号
private String simulateResultFilePath; /////文件存放位置
private String modelFilePath;
public SimulationThreadService(List<Scene> scenes, List<DeviceDetail> devices, String uppaalPath,
String fileNameWithoutSuffix, String scenarioNum, String modelFilePath,String simulateResultFilePath) {
super();
this.scenes = scenes;
this.devices = devices;
this.uppaalPath = uppaalPath;
this.fileNameWithoutSuffix = fileNameWithoutSuffix;
this.scenarioNum = scenarioNum;
this.modelFilePath = modelFilePath;
this.simulateResultFilePath=simulateResultFilePath;
}
@Override
public void run() {
String newModelFileName=fileNameWithoutSuffix+"-scenario-"+scenarioNum+".xml";
String resultFileName=fileNameWithoutSuffix+"-scenario-"+scenarioNum+".txt";
String simulationResult=DynamicAnalysisService.getSimulationResult(uppaalPath, newModelFileName, modelFilePath);
simulationResult=simulationResult.replace("\n[0]:", ""); ///删掉“\n[0]”
//生成仿真结果数据文件
for(DeviceDetail device:devices) {
//获得设备标识符表示identifier转为设备名并给出位置信息和设备类型
//如 bulb[0] => deviceName=Bulb_0,deviceType=Bulb,location=Lobby
String identifier=device.getDeviceType().getName().substring(0, 1).toLowerCase()+device.getDeviceType().getName().substring(1)+"["+device.getConstructionNum()+"]";
simulationResult=simulationResult.replace("\n"+identifier, "\ndeviceName="+device.getDeviceName()+",deviceType="+device.getDeviceType().getName()+",location="+device.getLocation());
}
try (FileWriter fr=new FileWriter(simulateResultFilePath+resultFileName);
PrintWriter pw=new PrintWriter(fr)){
pw.write(simulationResult);
}catch(IOException e) {
e.printStackTrace();
}
/////将仿真结果解析成 (数据名,(时间,值)) 的格式
List<DataTimeValue> dataTimeValues=DynamicAnalysisService.getAllDataTimeValues(simulationResult);
Scene scene=new Scene();
scene.setScenarioName("scenario-"+scenarioNum);
scene.setDataTimeValues(dataTimeValues);
List<DataTimeValue> triggeredRuleDataTimeValues=new ArrayList<DataTimeValue>();
List<String> cannotTriggeredRules=new ArrayList<>();
for(DataTimeValue dataTimeValue:dataTimeValues) {
if(dataTimeValue.getName().contains("rule")) {
////找到trigger的和cannot triggered rules
boolean canTriggered=false;
for(double[] dataTime:dataTimeValue.getTimeValues()) {
if(dataTime[1]>0.5) {
///能triggered
canTriggered=true;
triggeredRuleDataTimeValues.add(dataTimeValue);
break;
}
}
if(!canTriggered) {
cannotTriggeredRules.add(dataTimeValue.getName());
}
}
}
scene.setCannotTriggeredRulesName(cannotTriggeredRules);
scene.setTriggeredRulesName(triggeredRuleDataTimeValues);
////加锁避免出问题
synchronized (scenes){
scenes.add(scene);
}
System.out.println(Thread.currentThread().getName()+" end.");
}
}

@ -0,0 +1,836 @@
package com.example.demo.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;
import com.example.demo.bean.DeviceType;
import com.example.demo.bean.DeviceType.StateEffect;
import com.example.demo.bean.EnvironmentModel;
import com.example.demo.bean.ModelGraph.TemplGraph;
import com.example.demo.bean.ModelGraph.TemplGraphNode;
import com.example.demo.bean.ModelGraph.TemplTransition;
import com.example.demo.bean.Rule;
import com.example.demo.bean.SensorType;
import com.example.demo.bean.StaticAnalysisResult;
import com.example.demo.bean.Action;
import com.example.demo.bean.Attribute;
import com.example.demo.bean.BiddableType;
import com.example.demo.bean.DeviceDetail;
import com.example.demo.bean.Trigger;
import com.example.demo.service.GetTemplate.Branchpoint;
import com.example.demo.service.GetTemplate.Label;
import com.example.demo.service.GetTemplate.Location;
import com.example.demo.service.GetTemplate.Template;
import com.example.demo.service.GetTemplate.Transition;
@Service
public class TemplGraphService {
public static void main(String[] args) throws DocumentException, IOException {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
String[] locations= {"Lobby","Kitchen","Bathroom","Bedroom"};
List<DeviceDetail> devices=new ArrayList<DeviceDetail>();
for(int i=0;i<20;i++) {
String location=locations[new Random().nextInt(4)];
System.out.println("deviceTypeName");
String deviceTypeName=s.next();
DeviceDetail device=new DeviceDetail("", location, deviceTypeName);
devices.add(device);
}
System.out.println(devices);
String modelFileName="anewtry.xml";
String filePath="D:\\example";
String modelFileName2="anewtry2.xml";
String ifdFileName="ifd.dot";
GetTemplate.deleteFileLine(filePath+"\\"+modelFileName, filePath+"\\"+modelFileName2, 2);
List<TemplGraph> templGraphs=TemplGraphService.getTemplGraphs(modelFileName2, filePath);
List<TemplGraph> controlledDevices=new ArrayList<TemplGraph>();
List<TemplGraph> sensors=new ArrayList<TemplGraph>();
List<TemplGraph> biddables=new ArrayList<TemplGraph>();
for(TemplGraph templGraph:templGraphs) {
if(templGraph.getDeclaration().indexOf("controlled_device")>=0) {
controlledDevices.add(templGraph);
}else if(templGraph.getDeclaration().indexOf("sensor")>=0) {
sensors.add(templGraph);
}else {
if(templGraph.getName().equals("Person")) {
TemplGraph person=templGraph=getPersonTeml(Arrays.asList(locations));
if(person!=null) {
templGraph=person;
}
SystemModelService.generatePersonModel(templGraph, filePath+"\\"+modelFileName2);
}
biddables.add(templGraph);
}
}
// List<DeviceType> deviceTypes=getDeviceTypes(controlledDevices,attributes);
List<SensorType> sensorTypes=getSensorTypes(sensors);
List<BiddableType> biddableTypes=getBiddableTypes(biddables, sensorTypes);
// setDeviceType(devices, deviceTypes);
// setDeviceConstructionNum(devices, deviceTypes);
EnvironmentModel environmentModel=new EnvironmentModel();
environmentModel.setBiddables(biddableTypes);
environmentModel.setDevices(devices);
environmentModel.setSensors(sensorTypes);
String ruleText="1. IF SmartHomeSecurity_0.homeMode AND temperature<=15 THEN Heater_0.turn_heat_on\r\n" +
"\r\n" +
"2. IF SmartHomeSecurity_0.homeMode AND temperature>=30 THEN AirConditioner_0.turn_ac_cool\r\n" +
"\r\n" +
"3. IF SmartHomeSecurity_0.homeMode AND humidity<20 THEN Humidifier_0.turn_hum_on\r\n" +
"\r\n" +
"4. IF SmartHomeSecurity_0.homeMode AND humidity>=45 THEN Humidifier_0.turn_hum_off\r\n" +
"\r\n" +
"5. IF SmartHomeSecurity_0.homeMode AND humidity>65 THEN Fan_0.turn_fan_on\r\n" +
"\r\n" +
"6. IF SmartHomeSecurity_0.homeMode AND temperature>28 THEN Fan_0.turn_fan_on\r\n" +
"\r\n" +
"7. IF SmartHomeSecurity_0.homeMode AND temperature<20 THEN Fan_0.turn_fan_off\r\n" +
"\r\n" +
"15. IF SmartHomeSecurity_0.awayMode THEN Fan_0.turn_fan_on\r\n" +
"\r\n" +
"17. IF Window_0.wopen THEN Heater_0.turn_heat_off\r\n" +
"\r\n" +
"IF Window_0.wopen AND temperature>28 THEN AirConditioner_0.turn_ac_cool, Bulb_0.turn_bulb_off\r\n"+
"\r\n"+
"18. IF SmartHomeSecurity_0.awayMode THEN Heater_0.turn_heat_off,AirConditioner_0.turn_ac_off,Fan_0.turn_fan_off,Blind_0.close_blind,Bulb_0.turn_bulb_off\r\n" +
"\r\n" +
"19. IF SmartHomeSecurity_0.homeMode AND temperature<18 THEN AirConditioner_0.turn_ac_heat\r\n" +
"\r\n" +
"20. IF SmartHomeSecurity_0.homeMode AND temperature>30 THEN AirConditioner_0.turn_ac_cool\r\n" +
"\r\n" +
"21. IF SmartHomeSecurity_0.homeMode THEN Robot_0.dock_robot\r\n" +
"\r\n" +
"22. IF SmartHomeSecurity_0.awayMode THEN Robot_0.start_robot\r\n" +
"\r\n" +
"23. IF SmartHomeSecurity_0.awayMode THEN Window_0.close_window\r\n" +
"\r\n" +
"24. IF Person.Lobby THEN SmartHomeSecurity_0.turn_sms_home\r\n" +
"\r\n" +
"25. IF Person.Out THEN SmartHomeSecurity_0.turn_sms_away\r\n" +
"\r\n" +
"26. IF SmartHomeSecurity_0.homeMode AND temperature>28 THEN Blind_0.open_blind\r\n" +
"\r\n" +
"27. IF SmartHomeSecurity_0.homeMode THEN Bulb_0.turn_bulb_on\r\n" +
"\r\n" +
"28. IF SmartHomeSecurity_0.homeMode AND co2ppm>=800 THEN Fan_0.turn_fan_on,Window_0.open_window\r\n" +
"\r\n" +
"29. IF AirConditioner_0.cool THEN Window_0.close_window\r\n" +
"\r\n" +
"30. IF AirConditioner_0.heat THEN Window_0.close_window\r\n"+
"\r\n" +
"19. IF SmartHomeSecurity_0.homeMode AND temperature<18 THEN AirConditioner_0.turn_ac_heat\r\n"+
"\r\n" +
"19. IF temperature>20 AND temperature<18 THEN AirConditioner_0.turn_heat_ac\r\n" +
"\r\n" +
"19. IF SmartHomeSecurity_0.homeMode AND SmartHomeSecurity_0.awayMode THEN AirConditioner_0.turn_ac_heat\r\n"+
"\r\n" +
"19. IF temperature<18 AND temperature>21 THEN AirConditioner_0.turn_ac_heat\r\n"+
"\r\n"+
"IF temperature>18 THEN Window_0.open_window,AirConditioner_0.turn_ac_heat\r\n"+
"\r\n"+
"IF temperature>18 THEN Window_0.open_window\r\n"+
"\r\n"+
"IF temperature>18 THEN Fan_0.turn_fan_on\r\n"+
"\r\n"+
"IF Fan_0.fon THEN AirConditioner_0.turn_ac_heat\r\n";
List<Rule> rules=RuleService.getRuleList(ruleText);
StaticAnalysisResult staticAnalsisResult=StaticAnalysisService.getStaticAnalaysisResult(rules, ifdFileName, filePath, environmentModel);
SystemModelService.generateContrModel(filePath+"\\"+modelFileName2, staticAnalsisResult.getUsableRules(), biddableTypes, devices);
// List<String[]> declarations=SystemModelService.generateDeclaration(rules, biddableTypes, deviceTypes, sensorTypes,controlledDevices);
// List<Action> actions=RuleService.getAllActions(staticAnalsisResult.usableRules, devices);
// List<Trigger> triggers=RuleService.getAllTriggers(staticAnalsisResult.usableRules, sensorTypes, biddableTypes);
// SystemModelService.generateAllScenarios(actions, triggers, declarations, devices, deviceTypes, biddableTypes, sensorTypes, modelFileName2, filePath, "300");
// ScenesTree scenesTree=SystemModelService.generateAllScenarios(staticAnalsisResult.getUsableRules(), devices, deviceTypes, biddableTypes, sensorTypes, modelFileName2, filePath, "300");
// DynamicAnalysisService.getAllSimulationResults(scenesTree,devices, modelFileName2, filePath, "D:\\tools\\uppaal-4.1.24\\uppaal-4.1.24\\bin-Windows",filePath);
System.out.println(devices);
s.close();
}
public static EnvironmentModel getEnvironmentModel(String initModelFileName,String changedModelFileName,String filePath,String propertyFileName) throws DocumentException, IOException {
Properties properties=PropertyService.getProperties(filePath, propertyFileName);
List<String> locations=new ArrayList<>();
List<DeviceDetail> devices=new ArrayList<>();
for(String key:properties.stringPropertyNames()) {
if(key.equals("location")) {
////是location,存下房间里的空间信息
String location=properties.getProperty(key).trim();
location=location.substring(1, location.length()-1);
locations=Arrays.asList(location.split(","));
for(int i=0;i<locations.size();i++) {
locations.set(i, locations.get(i).trim());
}
}else {
////为设备信息
String deviceInfo=properties.getProperty(key).trim();
deviceInfo=deviceInfo.substring(1, deviceInfo.length()-1);
String[] deviceInfos=deviceInfo.split(",");
DeviceDetail device=new DeviceDetail();
for(String deInfo:deviceInfos) {
if(deInfo.contains("deviceName")) {
device.setDeviceName(deInfo.substring(deInfo.indexOf(":")+1).trim());
}else if(deInfo.contains("num")) {
device.setConstructionNum(Integer.parseInt(deInfo.substring(deInfo.indexOf(":")+1).trim()));
}else if(deInfo.contains("deviceType")) {
device.setDeviceTypeName(deInfo.substring(deInfo.indexOf(":")+1).trim());
}else if(deInfo.contains("location")) {
device.setLocation(deInfo.substring(deInfo.indexOf(":")+1).trim());
}
}
devices.add(device);
}
}
/////初始模型文件删掉第二行,更改文件名
// String changedModelFileName=initModelFileName.substring(0, initModelFileName.lastIndexOf(".xml"))+"-changed.xml";
///删除第二行
GetTemplate.deleteFileLine(filePath+initModelFileName, filePath+changedModelFileName, 2);
/////获得所有环境模型对应的结构
List<TemplGraph> templGraphs=TemplGraphService.getTemplGraphs(changedModelFileName, filePath);
List<TemplGraph> controlledDevices=new ArrayList<TemplGraph>();
List<TemplGraph> sensors=new ArrayList<TemplGraph>();
List<TemplGraph> biddables=new ArrayList<TemplGraph>();
List<Attribute> attributes=new ArrayList<>();
boolean existAttribute=false;//用来判断有没有attribute模型
for(TemplGraph templGraph:templGraphs) {
if(templGraph.getDeclaration().indexOf("controlled_device")>=0) {
////controlled devices
controlledDevices.add(templGraph);
}else if(templGraph.getDeclaration().indexOf("sensor")>=0) {
////sensors
sensors.add(templGraph);
}else if(templGraph.getDeclaration().indexOf("biddable")>=0){
////biddables
if(templGraph.getName().equals("Person")) {
////Person model generation
TemplGraph person=templGraph=TemplGraphService.getPersonTeml(locations);
if(person!=null) {
templGraph=person;
}
//////生成Person模型
SystemModelService.generatePersonModel(templGraph, filePath+changedModelFileName);
}
biddables.add(templGraph);
}else if(templGraph.getName().equals("Attribute")) {
////获得attribute
existAttribute=true;
attributes=getAttributes(templGraph);
}
}
if(!existAttribute) {
/////不存在Attribute模型
attributes=null;
}
/////设备类型
List<DeviceType> deviceTypes=TemplGraphService.getDeviceTypes(controlledDevices,attributes);
///传感器类型
List<SensorType> sensorTypes=TemplGraphService.getSensorTypes(sensors);
////被控实体类型
List<BiddableType> biddableTypes=TemplGraphService.getBiddableTypes(biddables, sensorTypes);
TemplGraphService.setDeviceType(devices, deviceTypes);
TemplGraphService.setDeviceConstructionNum(devices, deviceTypes);
EnvironmentModel environmentModel=new EnvironmentModel();
environmentModel.setBiddables(biddableTypes);
environmentModel.setDevices(devices);
environmentModel.setSensors(sensorTypes);
environmentModel.setDeviceTypes(deviceTypes);
////attributes
environmentModel.setAttributes(attributes);
return environmentModel;
}
public static List<TemplGraph> getTemplGraphs(File file) throws DocumentException{
GetTemplate getTemplate=new GetTemplate();
List<Template> templates=getTemplate.getTemplate(file);
List<TemplGraph> templGraphs=new ArrayList<TemplGraph>();
for(Template template:templates) {
TemplGraph templGraph=getTemplGraph(template);
templGraphs.add(templGraph);
}
return templGraphs;
}
//////////////获得状态机
public static List<TemplGraph> getTemplGraphs(String modelFileName,String modelFilePath) throws DocumentException{
String modelPath=modelFilePath+modelFileName;
GetTemplate getTemplate=new GetTemplate();
List<Template> templates=getTemplate.getTemplate(modelPath);
List<TemplGraph> templGraphs=new ArrayList<TemplGraph>();
for(Template template:templates) {
TemplGraph templGraph=getTemplGraph(template);
templGraphs.add(templGraph);
}
return templGraphs;
}
//template->templGraph
public static TemplGraph getTemplGraph(Template template) {
TemplGraph templGraph=new TemplGraph();
templGraph.setName(template.name);
templGraph.setDeclaration(template.declaration);
templGraph.setParameter(template.parameter);
templGraph.setInit(template.init);
List<TemplGraphNode> templGraphNodes=new ArrayList<TemplGraphNode>();
for(Location location:template.locations) {
////SHA的location---state
TemplGraphNode templGraphNode=new TemplGraphNode();
templGraphNode.name=location.name;
templGraphNode.id=location.id;
templGraphNode.invariant=location.invariant;
templGraphNode.style=location.style;
templGraphNodes.add(templGraphNode);
}
for(Branchpoint branchpoint:template.branchpoints) {
TemplGraphNode templGraphNode=new TemplGraphNode();
templGraphNode.id=branchpoint.id;
templGraphNode.style="branchpoint";
templGraphNodes.add(templGraphNode);
}
for(TemplGraphNode templGraphNode:templGraphNodes) {
for(Transition transition:template.transitions) {
if(transition.targetId.equals(templGraphNode.id)) {
TemplTransition inTransition=new TemplTransition();
inTransition.source=transition.sourceId;
inTransition.target=transition.targetId;
for(Label label:transition.labels) {
if(label.kind.equals("assignment")) {
inTransition.assignment=label.content;
}
if(label.kind.equals("synchronisation")) {
inTransition.synchronisation=label.content;
}
if(label.kind.equals("probability")) {
inTransition.probability=label.content;
}
if(label.kind.equals("guard")) {
inTransition.guard=label.content;
}
}
for(TemplGraphNode node:templGraphNodes) {
if(transition.sourceId.equals(node.id)) {
inTransition.node=node;
}
}
templGraphNode.inTransitions.add(inTransition);
}
if(transition.sourceId.equals(templGraphNode.id)) {
TemplTransition outTransition=new TemplTransition();
outTransition.source=transition.sourceId;
outTransition.target=transition.targetId;
for(Label label:transition.labels) {
if(label.kind.equals("assignment")) {
outTransition.assignment=label.content;
}
if(label.kind.equals("synchronisation")) {
outTransition.synchronisation=label.content;
}
if(label.kind.equals("probability")) {
outTransition.probability=label.content;
}
if(label.kind.equals("guard")) {
outTransition.guard=label.content;
}
}
for(TemplGraphNode node:templGraphNodes) {
if(transition.targetId.equals(node.id)) {
outTransition.node=node;
}
}
templGraphNode.outTransitions.add(outTransition);
}
}
}
templGraph.setTemplGraphNodes(templGraphNodes);;
return templGraph;
}
////////设置deviceDetail的deviceType
public static void setDeviceType(List<DeviceDetail> devices,List<DeviceType> deviceTypes) {
for(DeviceDetail device:devices) {
for(DeviceType deviceType:deviceTypes) {
if(device.getDeviceType().getName().equals(deviceType.getName())) {
device.setDeviceType(deviceType);
break;
}
}
}
}
////////设置constructionNum,并设置deviceType的device个数
public static void setDeviceConstructionNum(List<DeviceDetail> devices,List<DeviceType> deviceTypes) {
for(DeviceType deviceType:deviceTypes) {
List<DeviceDetail> relatedDevices=new ArrayList<DeviceDetail>();
for(DeviceDetail device:devices) {
if(device.getDeviceType().equals(deviceType)) {
relatedDevices.add(device);
}
}
for(int i=0;i<relatedDevices.size();i++) {
DeviceDetail device=relatedDevices.get(i);
if(device.getDeviceName().equals("")&&device.getConstructionNum()==-1) {
////名字未设置,设备号未设置
device.setDeviceName(device.getDeviceType().getName()+"_"+i);
device.setConstructionNum(i);
}else if(device.getDeviceName().equals("")) {
device.setDeviceName(device.getDeviceType().getName()+"_"+i);
}else if(device.getConstructionNum()==-1) {
device.setConstructionNum(i);
}
}
deviceType.deviceNumber=relatedDevices.size();
}
}
//////////device, state, action, value
public static List<DeviceType> getDeviceTypes(List<TemplGraph> controlledDevices,List<Attribute> attributes){
List<DeviceType> devices=new ArrayList<DeviceType>();
for(TemplGraph controlledDevice:controlledDevices) {
if(controlledDevice.getDeclaration().indexOf("controlled_device")>=0) {
DeviceType device=getDeviceType(controlledDevice,attributes);
devices.add(device);
}
}
return devices;
}
public static DeviceType getDeviceType(TemplGraph controlledDevice,List<Attribute> attributes) {
/////添加设备对环境属性的影响
DeviceType device=new DeviceType();
device.setName(controlledDevice.getName());;
for(TemplGraphNode stateNode:controlledDevice.getTemplGraphNodes()) {
////获得当前节点的状态、对应action和value
////添加设备对环境属性的影响
if(stateNode.getName()!=null) {
String[] stateActionValue=new String[3];
StateEffect stateEffect=new StateEffect();
stateEffect.setState(stateNode.getName());
stateActionValue[0]=stateNode.getName();
/////可以只需要看一条边
for(TemplTransition inTransition:stateNode.getInTransitions()) {
if(inTransition.synchronisation!=null&&inTransition.assignment!=null) {
////只看一条边
if(inTransition.synchronisation.indexOf("?")>0) {
String synchronisation=inTransition.synchronisation;
//synchronisation: turn_bulb_on[i]? => turn_bulb_on
stateActionValue[1]=synchronisation.substring(0, synchronisation.indexOf("["));
}
String[] assisnments=inTransition.assignment.split(",");
for(String assignment:assisnments) {
assignment=assignment.trim();
String identifier=device.getName().substring(0, 1).toLowerCase()+device.getName().substring(1);
if(assignment.indexOf(identifier)>=0) {
stateActionValue[2]=assignment.substring(assignment.indexOf("=")).substring("=".length());
}else {
/////添加设备状态对环境属性的影响
///dtemper=dtemper+(cooldt-heatdt)
if(assignment.indexOf("(")>0) {
String delta=assignment.substring(0, assignment.indexOf("="));
String stateDelta=assignment.substring(assignment.indexOf("("), assignment.indexOf("-")).substring("(".length()); ///cooldt
for(Attribute attribute:attributes) {
if(attribute.getDelta().equals(delta)) {
////找到对应属性
String[] effect=new String[3];
effect[0]=attribute.getAttribute();
effect[1]="'==";
////从declaration里找到对应的值
effect[2]=controlledDevice.getDeclaration().substring(controlledDevice.getDeclaration().indexOf(stateDelta+"=")).substring((stateDelta+"=").length());
effect[2]=effect[2].substring(0,effect[2].indexOf(";"));
stateEffect.getEffects().add(effect);
break;
}
}
}
}
}
break;
}
}
device.getStateEffects().add(stateEffect);
device.stateActionValues.add(stateActionValue);
}
}
return device;
}
//////获得sensors类型的设备 sensor名字检测什么属性
public static List<SensorType> getSensorTypes(List<TemplGraph> sensors){
List<SensorType> sensorTypes=new ArrayList<SensorType>();
for(TemplGraph sensor:sensors) {
if(sensor.getDeclaration().indexOf("sensor")>=0) {
SensorType sensorType=getSensorType(sensor);
sensorTypes.add(sensorType);
}
}
return sensorTypes;
}
//////获得sensor类型的设备 sensor名字检测什么属性
public static SensorType getSensorType(TemplGraph sensor) {
SensorType sensorType=new SensorType();
sensorType.setName(sensor.getName());
if(sensor.getTemplGraphNodes().size()>0) {
TemplGraphNode node=sensor.getTemplGraphNodes().get(0);
if(node.getInTransitions().size()>0) {
TemplTransition inTransition=node.getInTransitions().get(0);
String[] assignments=inTransition.assignment.split(",");
for(String assignment:assignments) {
assignment=assignment.trim();
if(assignment.endsWith("=get()")){
String attribute=assignment.substring(0, assignment.indexOf("=get()"));
sensorType.attribute=attribute;
}
}
}
}
if(sensor.getDeclaration().indexOf("biddable")>=0) {
sensorType.style="biddable";
}else if(sensor.getDeclaration().indexOf("causal")>=0) {
sensorType.style="causal";
}
return sensorType;
}
//////获得biddables biddable模型名属性各个状态值
public static List<BiddableType> getBiddableTypes(List<TemplGraph> biddables,List<SensorType> sensors) {
List<BiddableType> biddableTypes=new ArrayList<BiddableType>();
for(TemplGraph biddable:biddables) {
if(biddable.getDeclaration().indexOf("biddable")>=0) {
biddableTypes.add(getBiddableType(biddable, sensors));
}
}
return biddableTypes;
}
public static BiddableType getBiddableType(TemplGraph biddable, List<SensorType> sensors) {
BiddableType biddableType=new BiddableType();
biddableType.setName(biddable.getName());
for(TemplGraphNode node:biddable.getTemplGraphNodes()) {
if(!node.getName().equals("")) {
/////////是状态
String[] stateAttributeValue=new String[3];
stateAttributeValue[0]=node.getName();
if(!node.inTransitions.isEmpty()) {
String[] assignments=node.inTransitions.get(0).assignment.split(",");
for(String assignment:assignments) {
assignment=assignment.trim();
if(!assignment.startsWith("t=")) {
for(SensorType sensor:sensors) {
if(!assignment.startsWith(sensor.attribute)) {
stateAttributeValue[1]=assignment.substring(0, assignment.indexOf("=")).trim();
stateAttributeValue[2]=assignment.substring(assignment.indexOf("=")).substring(1).trim();
break;
}
}
}
break;
}
}
biddableType.stateAttributeValues.add(stateAttributeValue);
}
}
return biddableType;
}
public static List<Attribute> getAttributes(TemplGraph attributeTempl){
////根据模型获得各属性参数,该模型只有一个状态,状态上是不变式
List<Attribute> attributes=new ArrayList<>();
TemplGraphNode node=attributeTempl.getTemplGraphNodes().get(0);
String invariantContent=node.getInvariant();
String[] invariants=invariantContent.split("&&");
for(String invariant : invariants) {
invariant=invariant.trim();
Attribute attribute=new Attribute();
attribute.setContent(invariant);
attribute.setAttribute(invariant.substring(0, invariant.indexOf("'==")));
attribute.setDelta(invariant.substring(invariant.indexOf("'==")+"'==".length()).trim());
attributes.add(attribute);
}
return attributes;
}
/////////获得device在xml中的构造方法 deviceDetail 中的constructionNum
// public static void getDeviceConstruction(List<DeviceDetail> devices,List<TemplGraph> templGraphs) {
// for(TemplGraph templGraph:templGraphs) {
// if(templGraph.getDeclaration().contains("controlled_devcie")) {
// List<DeviceDetail> relatedDevices=new ArrayList<DeviceDetail>();
// for(DeviceDetail device:devices) {
// if(device.getDeviceName().equals(templGraph.getName())) {
// relatedDevices.add(device);
// }
// }
// for(int i=0;i<relatedDevices.size();i++) {
// DeviceDetail relatedDevice=relatedDevices.get(i);
// relatedDevice.setConstructionNum(i);
// }
// }
// }
// }
/////////生成person的templGraph
public static TemplGraph getPersonTeml(List<String> locations) {
/////doorway->locations->out
if(locations.size()<=0) {
return null;
}
TemplGraph person=new TemplGraph();
person.setName("Person");
TemplGraphNode startNode=new TemplGraphNode();
startNode.id="id0";
startNode.style="committed";
person.addTemplGraphNode(startNode);
person.setInit(startNode.id);
person.setDeclaration("//biddable");
StringBuilder parameter=new StringBuilder();
//////////out
// TemplGraphNode outNode=new TemplGraphNode();
// outNode.id="id1";
// outNode.name="Out";
// outNode.invariant="time<=t0";
// person.addTemplGraphNode(outNode);
// parameter.append("double t0");
//////////
/////////doorway///////
TemplGraphNode doorwayNode=new TemplGraphNode();
doorwayNode.id="id1";
doorwayNode.name="Doorway";
doorwayNode.invariant="time<=t0";
person.addTemplGraphNode(doorwayNode);
parameter.append("double t0");
//////location/////////
getTwoNodesRelation(startNode, doorwayNode, "position=0", "", "", "");
TemplGraphNode sourceNode=doorwayNode;
for(int i=0;i<locations.size();i++) {
TemplGraphNode locationNode=new TemplGraphNode();
locationNode.id="id"+(i+2);
locationNode.name=locations.get(i);
// if(i<locations.size()-1) {
// locationNode.invariant="time<=t"+(i+1);
// parameter.append(",double t"+(i+1));
// }
locationNode.invariant="time<=t"+(i+1);
parameter.append(",double t"+(i+1));
person.addTemplGraphNode(locationNode);
getTwoNodesRelation(sourceNode, locationNode, "position="+(i+1), "", "time>=t"+i, "");
sourceNode=locationNode;
}
//////Out//////
TemplGraphNode outNode=new TemplGraphNode();
outNode.id="id"+(1+locations.size()+1);
outNode.name="Out";
person.addTemplGraphNode(outNode);
getTwoNodesRelation(sourceNode, outNode, "position="+(1+locations.size()), "", "time>=t"+locations.size(), "");
person.setParameter(parameter.toString());
return person;
}
/////templGraph中source->target 的transition边
public static void getTwoNodesRelation(TemplGraphNode sourceNode,TemplGraphNode targetNode,
String assignment, String synchronisation,String guard,String probability) {
TemplTransition outTransition=new TemplTransition();
TemplTransition inTransition=new TemplTransition();
outTransition.assignment=assignment;
outTransition.guard=guard;
outTransition.synchronisation=synchronisation;
outTransition.probability=probability;
outTransition.source=sourceNode.id;
outTransition.target=targetNode.id;
inTransition.assignment=assignment;
inTransition.guard=guard;
inTransition.synchronisation=synchronisation;
inTransition.probability=probability;
inTransition.source=sourceNode.id;
inTransition.target=targetNode.id;
sourceNode.outTransitions.add(outTransition);
outTransition.node=targetNode;
targetNode.inTransitions.add(inTransition);
inTransition.node=sourceNode;
}
// //clone graph
// public TemplGraph cloneTemplGraph(TemplGraph templGraph) {
// TemplGraph cloneGraph=new TemplGraph();
// for(TemplGraphNode templGraphNode:templGraph.getTemplGraphNodes()) {
// TemplGraphNode cloneNode=cloneTemplGraphNode(templGraphNode);
// cloneGraph.addTemplGraphNode(cloneNode);
// }
// connectNode(cloneGraph);
// return cloneGraph;
// }
//
// //connect
// public void connectNode(TemplGraph templGraph) {
// for(TemplGraphNode node:templGraph.getTemplGraphNodes()) {
// Iterator<TemplTransition> inTransitions=node.inTransitions .iterator();
// while(inTransitions.hasNext()) {
// TemplTransition inTransition=inTransitions.next();
// boolean hasNode=false;
// for(TemplGraphNode otherNode:templGraph.getTemplGraphNodes()) {
// if(inTransition.node.id.equals(otherNode.id)) {
// hasNode=true;
// inTransition.node=otherNode;
// boolean existTran=false;
// for(TemplTransition outTransition:otherNode.outTransitions) {
// if(outTransition.node.id.equals(node.id)) {
// existTran=true;
// outTransition.node=node;
// break;
// }
// }
// if(!existTran) {
// //如果没有这条边,就添加这条边
// TemplTransition outTransition=new TemplTransition();
// outTransition.assignment=inTransition.assignment;
// outTransition.guard=inTransition.guard;
// outTransition.probability=inTransition.probability;
// outTransition.synchronisation=inTransition.synchronisation;
// outTransition.source=inTransition.source;
// outTransition.target=inTransition.target;
// outTransition.node=node;
// otherNode.outTransitions.add(outTransition);
// }
// break;
// }
// }
// if(!hasNode) {
// //delet
// inTransitions.remove();
// }
// }
// Iterator<TemplTransition> outTransitions=node.outTransitions.iterator();
// while(outTransitions.hasNext()) {
// TemplTransition outTransition=outTransitions.next();
// boolean hasNode=false;
// for(TemplGraphNode otherNode:templGraph.getTemplGraphNodes()) {
// if(outTransition.node.id.equals(otherNode.id)) {
// hasNode=true;
// outTransition.node=otherNode;
// boolean existTran=false;
// for(TemplTransition inTransition:otherNode.inTransitions) {
// if(inTransition.node.id.equals(node.id)) {
// existTran=true;
// inTransition.node=node;
// break;
// }
// }
// if(!existTran) {
// //如果没有这条边,就添加这条边
// TemplTransition inTransition=new TemplTransition();
// inTransition.assignment=outTransition.assignment;
// inTransition.guard=outTransition.guard;
// inTransition.probability=outTransition.probability;
// inTransition.synchronisation=outTransition.synchronisation;
// inTransition.source=outTransition.source;
// inTransition.target=outTransition.target;
// inTransition.node=node;
// otherNode.inTransitions.add(inTransition);
// }
// break;
// }
// }
// if(!hasNode) {
// outTransitions.remove();
// }
// }
//
// }
// }
//
// //clone node
// public TemplGraphNode cloneTemplGraphNode(TemplGraphNode node) {
// TemplGraphNode cloneNode=new TemplGraphNode();
// cloneNode.id=node.id;
// cloneNode.invariant=node.invariant;
// cloneNode.name=node.name;
// cloneNode.style=node.style;
// for(TemplTransition inTransition:node.inTransitions) {
// TemplTransition cloneinT=new TemplTransition();
// cloneinT.assignment=inTransition.assignment;
// cloneinT.guard=inTransition.guard;
// cloneinT.node=inTransition.node;
// cloneinT.probability=inTransition.probability;
// cloneinT.source=inTransition.source;
// cloneinT.synchronisation=inTransition.synchronisation;
// cloneinT.target=inTransition.target;
// cloneNode.inTransitions.add(cloneinT);
// }
// for(TemplTransition outTransition:node.outTransitions) {
// TemplTransition cloneoutT=new TemplTransition();
// cloneoutT.assignment=outTransition.assignment;
// cloneoutT.guard=outTransition.guard;
// cloneoutT.node=outTransition.node;
// cloneoutT.probability=outTransition.probability;
// cloneoutT.source=outTransition.source;
// cloneoutT.synchronisation=outTransition.synchronisation;
// cloneoutT.target=outTransition.target;
// cloneNode.outTransitions.add(cloneoutT);
// }
// return cloneNode;
// }
//
// //删除节点的某条边
// public void deletNodeEdge(TemplTransition transition,TemplGraphNode node) {
// for(TemplTransition inTransition:node.inTransitions) {
// if(inTransition==transition) {
// node.inTransitions.remove(inTransition);
// return;
// }
// }
// for(TemplTransition outTransition:node.outTransitions) {
// if(outTransition==transition) {
// node.outTransitions.remove(outTransition);
// return;
// }
// }
// }
//
// //删除节点某条边以及对应节点该边
// public void deletEdge(TemplTransition transition,TemplGraphNode node) {
// deletNodeEdge(transition, node);
// TemplGraphNode anotherNode=transition.node;
// deletNodeEdge(transition, anotherNode);
// }
}

@ -0,0 +1,4 @@
server.port=8085
spring.servlet.multipart.max-request-size=200MB
spring.servlet.multipart.max-file-size=200MB

@ -0,0 +1,13 @@
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SimulationVisualizationApplicationTests {
@Test
void contextLoads() {
}
}
Loading…
Cancel
Save