1.概述
经过4周的柿饼课程入门学习,终于迎来了最后作业。那么这次的作业题目是什么呢?
两选择:
- 炫酷汽车仪表盘实现
- 网络音频流播放器实现
恩,考虑再三。看着汽车仪表盘挺高大上,心里想着是不是可以把这个网络音频流播放器也集成上去。
所以就决定是你了-“炫酷汽车仪表盘”。
2.素材收集
如何实现一个炫酷的汽车仪表盘,心里也不知道。看看前辈是怎么做的。俗话说:“站得高,才能看得远”。
所以素材收集也就很自然的事了。
素材收集渠道
-
现实世界的仪表盘
有豪车的朋友看看能不能让我给您的仪表盘拍张靓照…
可惜我是没有…
-
如果可以科学上网,架个梯子什么的,谷歌是不错的选择。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dXqiBjcX-1609289351237)(D:\Persimmon\project\introduction-to-persimmon\4th_week\res\快照6.png)]
-
阿里图库有很多图标,免费,支持SVG、PNG、EPS等格式,使用起来非常方便。
3.制作效果图
在网上找了很久图片,获取很多灵感。把各个元素集合起来,动起手来,先这样,然后这样,最后就是下面这样了。
4.功能概设
-
速度指示
- 数据显示
- 指针显示
-
充电指示
- 当用户进行充电时,电池图标进行动画播放。充电量进行数值显示。
- 在充电过程中,指针动态地指向相应的数值。
- 充电完成后,自动断开充电。
-
水温指示
- 当用户行进时,水温逐渐升高。
- 当用户停止行进时,水温逐渐降低。
-
油量指示
- 动画效果
-
里程显示
- 用户行进时,里程进行累加。
-
转向指示
- 指示交替显示
-
wifi
- wifi扫描
- wifi密码输入
- wifi联接状态显示
-
音乐播放
- 上一曲
- 播放/暂停
- 下一曲
- 音量调节
- 歌曲总时长显示
- 歌曲实时时长显示
- 歌曲播放进度显示
- 歌曲进度条拖放播放
- 歌曲播放模式设置(顺序播放、单曲循环、随机播放)
- 歌曲列表显示
- 歌曲列表点击播放
-
系统设置
- 屏幕亮度调节
-
定位与天气
- 城市列表显示
- 根据选择的城市获取实时天气信息。
- 根据实时天气信息进行语音播放。
-
视频播放
以上为汽车仪表盘的相关功能设计。
5.功能实现
1.主要应用的控件
- animatedImage
- button
- clock
- imagebox
- label
- listctrl
- panel
- progressbar
- slider
- textbox
2.主要应用的接口
- timer
- audioplayer
- 自定义面板
3.硬件外设
- wifi模块
- 8欧1W喇叭
4.仪表指示实现
仪表构建主要运用clock控件,将指针设置为“秒针图片”,表盘设置为“背景图片”。如下所示:
-
指定指针旋转点
//设置指针旋转点 this.setData({ speed_yb: { second: { x: 124, y: 126 }, } }); this.setData({ charge_yb: { second: { x: 124, y: 126 }, } });
-
指针旋转驱动
this.setData({ speed_yb: { value: this.sec }, });
在这里,改变“this.sec”的值,即可变更指针指向的角度。
再根据仪表盘刻度,计算出每1度指对应的值,即可完成速度值、电量值的转换。从而实现指针的动态显示。
举个例子:
注意:由于Clock控制对秒针的控制是整型的,也就是要么是1秒,要么2秒等,没有1.5秒这种显示。所以对于仪表盘指针的显示精确度会较低,所以刻度跨度不宜太大,否则指示精度会很低。
-
加速、减速、刹车实现
有了指针旋转的驱动,则汽车的加速、减速,刹车实际上是对clock控件的value值控制。
为了摸拟减速或阻力的效果。在定时器中对value值进行自减
//速度表自动降速 this.timer1 = setInterval(function () { if (37 < that.sec) { that.setData({ speed_yb: { value: that.sec-- }, }); } }, 100); //加速按钮 btn_up_click function(event){ if (82 > this.sec) {//当为82时,达到满刻度 this.sec += 3; if (79 < this.sec) { this.sec = 82; } } this.setData({ speed_yb: { value: this.sec }, }); } //刹车按钮 btn_down_click function(event){ if (37 < this.sec) { this.sec -= 2; if (40 > this.sec) { this.sec = 37; } this.setData({ speed_yb: { value: this.sec }, }); } }
充电效果同理。
5.水温、油量指示实现
-
业务逻辑实现
对水温、油表的控制,实际上是对progressbar的控制。
在定时器中,实现对水温的降低处理。
在加速按钮中实现测量检测,当油量小于2时,给了警告信息、耗油处理。
this.timer1 = setInterval(function () { ... //水温自动降低 if (20 < that.water_temp && 0 == (that.time_cnt % 5)) { that.setData({ water_temp_bar: that.water_temp-- }); } ... .. . }, 100); //加速按钮 btn_up_click function(event){ ..... //油量检测 if (2 > this.cur_oil_vol) { this.setData({ panel_warning: { hide: false } }); break; } //水温升高实现 if (100 > this.water_temp) { this.speed_up_cnt++; if (2 == this.speed_up_cnt) { this.speed_up_cnt = 0; this.setData({ water_temp_bar: this.water_temp++ }); } } //耗油实现 if (0 < this.cur_oil_vol) { if (0 == (this.time_cnt % 5)) { this.cur_oil_vol--; var vol = 100 - this.cur_oil_vol; this.setData({ fuel_bar: vol }); } } ... .. . }
6.wifi
wifi接口在帮助文档中其实已经很详细了。这里分享一下wifi扫描列表的实现。
wifi列表的实现用到了自定义面板。由3个imagebox和1个button组成。如下所示:
代码实现:
onLoad: function (event) {
var that = this;
//--------------wifi start------------------
this.wifi = pm.createWifi();
// 监听扫描 WiFi 结束事件,并配置事件回调函数
this.wifi.onScanEvent(function (res) {
if (res) {
that.wifiArray = new Array();
for (var i = 0; i < res.length; i++) {
var item = res[i];
var wifiItem = new Object();
wifiItem.wifi_name = new Object();
wifiItem.wifi_name.value = item.ssid;
wifiItem.wifi_name.id = wifi_button + i;
wifiItem.wifi_conn = new Object();
wifiItem.wifi_conn.id = 'wifi_conn' + i;
that.wifiArray.push(wifiItem);
}
// 将搜索到的wifi信息绑定到自定义面板
that.setData({
wifi_list: {
list: {
empty: true,
page: that,
items: [{
xml: "Panels/wifi",
items: that.wifiArray
}]
}
}
});
}
else {
console.log("WiFi cannot be scanned.");
}
});
this.wifi.onConnectEvent(function (res) {
if (res) {
console.log("wifi is connected");
console.dir(res);
} else {
console.log("wifi is connected fail");
}
});
this.wifi.onNetworkEvent(function (res) {
if (res) {
that.setData({ lbl_tips: 'wifi - \"' + that.wifiArray[that.sel_wifi_index].wifi_name.value + '\"连接成功' });
var conn = that.wifiArray[that.sel_wifi_index].wifi_conn.id;
that.setData({ conn: { value: 'wifi_tick.png' } });
}
});
//--------------wifi end------------------
this.wifiScan();
}
//选择wifi
sel_wifi_index: 0,
on_wifi_select: function (event) {
if (typeof (this.wifiArray) == "object") {
this.sel_wifi_index = parseInt(event.target.id.substring(wifi_button.length));
this.setData({ panel_link: { hide: false } });
}
},
//连接wifi
on_btn_wifi_link_click: function (event) {
var info = new Object();
info.ssid = this.wifiArray[this.sel_wifi_index].wifi_name.value;
info.password = this.wifi_passwd;
console.log('wifi info >>');
console.dir(info)
if (this.wifi.connect(info) == true) {
console.log("connect success wifi password :" + info.password);
} else {
console.log("connect fail");
}
this.setData({ panel_link: { hide: true } });
},
//记录输入的密码信息
onTextbox: function (event) {
this.wifi_passwd = event.detail.value;
console.log("passwd:" + this.wifi_passwd);
},
//wifi扫描
wifiScan: function (event) {
if (this.wifi.scan() == true) {
console.log("scan WiFi success");
} else {
console.log("scan WiFi fail");
}
},
7.音乐播放器
Audio Player 接口在帮助文档中也有很详细的介绍。
其主要功能:上一曲、播放/暂停、下一曲,音量调节、总时长显示、当前时长显示、播放模式选择、进度条拖放等。
audioplayer在播放的时候,会触发onPlay函数,得到歌曲的总时长,注意单位是秒。在播放过程中,会不断触发onTimeUpdate函数,得到歌曲当前的播放时长,注意单位是毫秒。利用这两个值和进度条,即可实现总时长、当前播放时长、进度条显示和进度条拖放功能。
关键代码:
volume = 50; //音量调节
process = 0; //当前歌曲播放时长
music_max_time = 0; //歌曲总时长
is_set_voice = 0; //是否在进行音量设置
is_music_play = 0; //是否播放
music_sel_no = 0; //歌曲序号
music_play_mode = 0; //播放模式:0,顺序播放;1,单曲循环;2,随机播放
var page = {
musics: [
{ ename: 'bubi', name: '不必' },
{ ename: 'dayu', name: '大鱼' },
{ ename: 'qiangu', name: '千古' },
{ ename: 'zuoshou', name: '左手' },
{ ename: 'lvse', name: '绿色' },
{ ename: 'xiangyu', name: '像鱼' },
{ ename: 'tianxiawushuan', name: '天下无双' },
{ ename: 'youhebuke', name: '有何不可' },
{ ename: 'fuxishaonv', name: '佛系少女' },
],
onLoad: function (event) {
//音乐列表
this.setData({ panel_voice: { hide: true } });
var v = audio.getVolume();
this.setData({ slider_voice: v });
var music_item = new Array();
// 循环或得到 musics 内的音乐信息
for (var i = 0; i < this.musics.length; i++) {
var item = new Object();
item.btn_music_select = new Object();
item.btn_music_select.value = this.musics[i].name;
item.btn_music_select.id = 'music' + i;
item.lbl_music_index = new Object();
item.lbl_music_index.value = (i + 1) + ".";
music_item.push(item);
}
// 绑定音乐信息到页面music_list列表控件
this.setData({
music_list: {
list: {
page: this,
items: [{
xml: 'Panels/music',
items: music_item
}]
}
}
})
//显示歌曲播放时长、总时长
audio.onTimeUpdate(function (e) {
progress = e / music_max_time;
that.setData({ slider_process: { value: progress } });
var time_str = that.get_music_time(e / 1000) + "/" + that.get_music_time(music_max_time);
that.setData({ lbl_music_time: { value: time_str } });
});
//显示歌曲总时长
audio.onPlay(function (e) {
music_max_time = e;
var time_str = that.get_music_time(0) + "/" + that.get_music_time(e);
that.setData({ lbl_music_time: { value: time_str } });
});
this.timer1 = setInterval(function () {
...
//更新音乐播放声音与时间
if (1 == update) {
audio.setVolume(volume);
update = 0;
}
else if (2 == update) {
audio.seek(progress);
update = 0;
}
that.time_cnt %= 10000000;
...
..
.
}, 100);
}
//根据秒获取“00:00”格式的字符串
get_music_time: function (time) {
var m = Math.floor((time / 60 % 60)) < 10 ? '0' + Math.floor((time / 60 % 60)) : Math.floor((time / 60 % 60));
var s = Math.floor((time % 60)) < 10 ? '0' + Math.floor((time % 60)) : Math.floor((time % 60));
return result = m + ":" + s;
},
//点击歌曲列表时,播放对应的歌曲
on_music_select: function (event) {
audio.stop();
music_sel_no = parseInt(event.target.id.substring(5));
console.log("music select no:" + music_sel_no);
audio.setSrc("/mnt/sd0/filesystem/" + this.musics[music_sel_no].ename + ".mp3");
audio.play();
},
//上一曲
on_music_pre: function (event) {
audio.stop();
if (0 == music_play_mode) {
if (0 < music_sel_no) {
music_sel_no--;
}
else {
music_sel_no = this.musics.length;
}
}
else if (2 == music_play_mode) {
music_sel_no = get_range_num(0, this.musics.length);
}
audio.setSrc("/mnt/sd0/filesystem/" + this.musics[music_sel_no].ename + ".mp3");
audio.play();
},
//播放
on_music_play: function (event) {
is_music_play = !is_music_play;
if (is_music_play) {
audio.play();
audio.seek(progress);
this.setData({ btn_music_play: { norImg: 'pause.png' } });
return;
}
audio.pause();
this.setData({ btn_music_play: { norImg: 'play_music.png' } });
},
//下一曲
on_music_next: function (event) {
audio.stop();
if (0 == music_play_mode) {
if (this.musics.length > music_sel_no) {
music_sel_no++;
}
else {
music_sel_no = 0;
}
}
else if (2 == music_play_mode) {
music_sel_no = get_range_num(0, this.musics.length);
}
audio.setSrc("/mnt/sd0/filesystem/" + this.musics[music_sel_no].ename + ".mp3");
audio.play();
},
//音量调节面板显示与隐藏
on_music_voice: function (event) {
is_set_voice = !is_set_voice;
this.setData({ panel_voice: { visible: is_set_voice } });
},
//音量调节
on_vol_change: function (event) {
volume = event.detail.value;
update = 1;
},
//进度条拖放
on_proc_change: function (event) {
console.log("silder value:" + event.detail.value);
console.log("music_max_time:" + music_max_time);
progress = event.detail.value / 1000 * music_max_time;
update = 2;
console.log("on_proc_change=>" + progress);
},
//播放模式选择
on_play_mode_change: function (event) {
music_play_mode++;
music_play_mode = music_play_mode % 3;
switch (music_play_mode) {
case 0:
this.setData({ btn_play_mode: { norImg: 'shunxu.png' } });
break;
case 1:
this.setData({ btn_play_mode: { norImg: 'danquxunhuan.png' } });
break;
case 2:
this.setData({ btn_play_mode: { norImg: 'music_sj.png' } });
break;
default:
break;
}
},
}
8.获取天气及语音播报
这个部分的功能是建立上联网成功后的。
-
获取天气信息
选择不同的地区,通过HTTP协议调用网络上的天气获取服务器提供的API链接进行请求,网络服务器返回Json字符串,然后本地解析得到选择的地区的天气相关参数,然后进行显示即可。
-
获取天气播报语音
在得到相关的天气参数后,自定义需要播放的语音字符串,向网络上的TTS(如百度语音、讯飞语音等)服务器发出语音合成请求,成功后将语音文件存储到本地,然后进行播放,最终实现天气语音播报功能。
关键代码如下:
// 获取天气 get_weather: function (event) { var that = this; // 按钮获取天气 func = function () { that.loadWeatherInfo(); } this.getFeatureWeather(func); }, // 获取未来天气 getFeatureWeather: function (func) { console.log('currentCity >>> ') console.dir(currentCity) var uurl = 'http://api.caiyunapp.com/v2/您申请的令牌/' + currentCity.location + '/forecast.json'; console.log(uurl) pm.request({ // 获取天气预报的API,返回数据 url: uurl, method: 'GET', header: { "Content-Type": "application/json" }, //与开发者服务器连接成功后,执行的回调函数 success: function (res) { // 把data从Buffer转成string var str = res.data.toString('utf8'); //把JSON格式的string转成JSON对象,以便获取数据 var json_obj = JSON.parse(str); weatherInfo = new Object(); weatherInfo.hourly = new Object(); // 获取到温度 weatherInfo.hourly.Temperature = json_obj.result.hourly.temperature; // 获取到天气情况 晴/多云/阴天 weatherInfo.hourly.Skycon = json_obj.result.hourly.skycon; weatherInfo.hourly.minutely = json_obj.result.minutely.description; // 湿度 weatherInfo.hourly.Humidity = json_obj.result.hourly.humidity; weatherInfo.daily = new Object(); // 温馨提示语 weatherInfo.daily.description = json_obj.result.minutely.description.toString('utf8'); console.log('weatherInfo.daily.description >> ' + weatherInfo.daily.description) weatherInfo.daily.Skycon = json_obj.result.daily.skycon; console.log('weatherInfo >>> ') console.dir(weatherInfo); if (typeof (func) == "function") { func(); } console.log('getFeatureWeather request success 2019-12-4 11:28:59') }, fail: function () { console.log('getFeatureWeather request failed 2019-12-4 11:28:59') }, }); }, loadWeatherInfo: function () { if (weatherInfo == 0) { return; } this.setData({ lbl_out_temp: { value: "外温:" + weatherInfo.hourly.Temperature[0].value + "℃" } }); switch (weatherInfo.hourly.Skycon[0].value) { case "CLEAR_DAY": case "CLEAR_NIGHT": this.setData({ img_weather: { value: "black_clear.png" } }) this.setData({ lbl_weather: { value: "晴" } }) break; case "PARTLY_CLOUDY_DAY": case "PARTLY_CLOUDY_NIGHT": this.setData({ img_weather: { value: "black_cloudy.png" } }) this.setData({ lbl_weather: { value: "多云" } }) break; case "CLOUDY": this.setData({ img_weather: { value: "black_overcase.png" } }) this.setData({ lbl_weather: { value: "阴" } }) break; case "WIND": this.setData({ img_weather: { value: "black_windy.png" } }) this.setData({ lbl_weather: { value: "大风" } }) break; case "HAZE": this.setData({ img_weather: { value: "black_haze.png" } }) this.setData({ lbl_weather: { value: "雾霾" } }) break; case "RAIN": this.setData({ img_weather: { value: "black_rain.png" } }) this.setData({ lbl_weather: { value: "雨" } }) break; case "SNOW": this.setData({ img_weather: { value: "black_snow.png" } }) this.setData({ lbl_weather: { value: "雪" } }) break; } }, onBroadcast: function (event) { this.waitBackTime = 0; var str = currentCity.name; // 自定义提示语 var strtip = ''; switch (weatherInfo.hourly.Skycon[0].value) { case "CLEAR_DAY": case "CLEAR_NIGHT": str += "今天天气晴朗" strtip = '适合约小伙伴出门玩儿。'; break; case "PARTLY_CLOUDY_DAY": case "PARTLY_CLOUDY_NIGHT": str += "今天多云" strtip = '天凉室内可健身,户外运动需保暖。'; break; case "CLOUDY": str += "今天阴天" strtip = '应适当减少室外活动。'; break; case "WIND": str += "今天有风" strtip = '天气降温,请添衣保暖,多喝热水。'; break; case "HAZE": str += "今天有雾霾" strtip = '尽量减少外出,出门记得带口罩。'; break; case "RAIN": str += "今天下雨" strtip = '出门记得带好雨具,预防感冒。'; break; case "SNOW": str += "今天下雪" strtip = '出门记得带好雨具,预防感冒。'; break; } str += (",气温为" + weatherInfo.hourly.Temperature[0].value + "度,相对湿度为百分之" + parseInt(weatherInfo.hourly.Humidity[0].value * 100) + "。"); //TODO 根据湿度增加提示语 str += weatherInfo.daily.description; var that = this; var http = require('http'); http.request({ url: 'http://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=uGmHtBFMOkme2XeGWzKLREDv&client_secret=xG7I0fy4GQLPpLqanq7pZAGtNXGUW564', success: function (res) { var jnews = res.data.jsonParse(); var url = "https://tsn.baidu.com/text2audio?tex=" + str + "&lan=zh&cuid=44-b2-95-27-49-1f&vol=15&ctp=1&per=0&tok=" + jnews.access_token; http.request({ url: url, method: "get", success: function (res) { console.log('request success'); var file = pm.getFileSystemManager(); file.writeFile({ filePath: "forecast.mp3", data: res.data, success: function () { audio.setVolume(100), audio.stop(); audio.setSrc("/mnt/sd0/filesystem/forecast.mp3"); that.targetAnimatedImage = "animated_boardcast" audio.play(); that.stopWaitBack(); }, complete: function () { console.log("writeFile complete"); } }); }, }) } }) },
6.视频分享
RT-Thread 第4周柿饼派学习入门课程-决赛作品
7.工程源码
git clone https://gitee.com/fyywhy/introduction-to-persimmon.git
以上为这次作业的分享,经过4周柿饼的学习,对柿饼的认识要深入很多,柿饼基于RT-Thread实时操作系统。在RT-Thread上实现了各种外设驱动。让开发者在使用柿饼的时候,可以专注于业务层面的实现。这样无疑会大缩短开发时间,也提高了开发效率。不过目前的椒饼派IO还比较少,希望以后能丰富起来。可玩性就更强了。