code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
#! /bin/env python
from aostools import Make
# default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin
# defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin')
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/helloworld_demo/SConstruct
|
Python
|
apache-2.0
| 303
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include "aos/init.h"
#include "board.h"
#include <aos/errno.h>
#include <aos/kernel.h>
#include <k_api.h>
#include <stdio.h>
#include <stdlib.h>
int application_start(int argc, char *argv[])
{
int count = 0;
printf("nano entry here!\r\n");
while (1) {
printf("hello world! count %d \r\n", count++);
aos_msleep(10000);
};
}
|
YifuLiu/AliOS-Things
|
solutions/helloworld_demo/helloworld.c
|
C
|
apache-2.0
| 424
|
/* user space */
#ifndef RHINO_CONFIG_USER_SPACE
#define RHINO_CONFIG_USER_SPACE 0
#endif
|
YifuLiu/AliOS-Things
|
solutions/helloworld_demo/k_app_config.h
|
C
|
apache-2.0
| 106
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t* init_args);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void* arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/helloworld_demo/maintask.c
|
C
|
apache-2.0
| 1,192
|
var fanSwitch = 0;
var waterSwitch = 0;
var beepSwitch = 0;
var gpio = require('gpio');
var beep = gpio.open({
id: 'D4'
});
var relay1 = gpio.open({
id: 'D3'
});
var relay2 = gpio.open({
id: 'D2'
});
// GPIO will ouput high in default
// Turn off beep and relay immediately
beep.writeValue(beepSwitch);
relay1.writeValue(waterSwitch);
relay2.writeValue(fanSwitch);
console.log('turn off beep and relay');
sleepMs(100);
var iot = require('iot');
var network = require('network');
var net = network.openNetWorkClient();
var productKey = 'yourproductkey'; /* your productKey */
var deviceName = 'yourdevicename'; /* your deviceName */
var deviceSecret = 'yourdevicesecret'; /* your deviceSecret */
var device;
var mqtt_connected = false;
var modbus = require('./modbus.js');
var deviceAddr = 1;
var timeout = 300;
var modbus_device = modbus(
{ id: 'UART2' },
{ id: 'D13', polarity: 1 },
deviceAddr
);
var temperature = 25.0;
var pressure = 0.0;
var bmp280 = require('./bmp280.js');
bmp280.bmp280_init();
var adc = require('adc');
var pir = adc.open({
id: 'ADC0',
success: function() {
console.log('adc: open adc1 success')
},
fail: function() {
console.log('adc: open adc1 failed')
}
});
var pirStatus = 0;
var pirTempStatus = 0;
var pirCount = 0;
//----------------------- GPS Start--------------------------------
var GPS = require("./gps.js");
var gps = new GPS();
var uart1 = require('uart');
// gnss uart
var gnss = uart1.open({
id: 'UART1'
});
var geoLocation_data = {'lat':0, 'lon':0, 'alt':0}
gps.on("data", function (parsed) {
//console.log(parsed);
geoLocation_data['lat'] = gps.state["lat"];
geoLocation_data['lon'] = gps.state["lon"];
geoLocation_data['alt'] = gps.state["alt"];
console.log("geo data " + JSON.stringify(geoLocation_data, null, 4))
});
function ArrayToString(fileData) {
var dataString = "";
for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
}
return dataString;
}
var GGA;
gnss.on('data', function(data) {
var aaa = ArrayToString(data);
var bbb = aaa.split("$");
GGA = "$" + bbb[1];
});
// GPS data post
setInterval(function(){
var gga_default = "$GNGGA,033122.000,3111.28510,N,12136.26122,E,1,13,1.0,1.3,M,11.7,M,,*4B"
/* gga_default is temporary data for agriculture demo, we should use real 'GGA' data */
gps.update(gga_default);
//gps.update(GGA);
if(mqtt_connected) {
device.postProps(JSON.stringify({
GeoLocation: {
Longitude: geoLocation_data['lon'],
Latitude: geoLocation_data['lat'],
Altitude: geoLocation_data['alt'],
CoordinateSystem: 1
}
}));
}
}, 5000);
//----------------------- GPS End--------------------------------
setInterval(function(){
temperature = bmp280.bmp280TemperatureRead();
pressure = bmp280.bmp280PressureRead();
pressure = pressure / 100; // iot needs hPa
console.log('Temperature is ' + temperature + ' Pressure is ' + pressure);
if(mqtt_connected) {
device.postProps(JSON.stringify({
CurrentTemperature: temperature
}));
device.postProps(JSON.stringify({
Atmosphere: pressure
}));
}
}, 10000);
setInterval(function(){
var pinStatus = (pir.readValue() > 512) ? 1 : 0;
if(pirTempStatus == pinStatus) {
pirCount++;
if(pirCount > 4) {
pirCount = 0;
if(pirTempStatus != pirStatus) {
pirStatus = pirTempStatus;
if(mqtt_connected) {
device.postProps(JSON.stringify({
AlarmState: pirStatus
}));
}
console.log('Pir status is ' + pirStatus);
}
}
} else {
pirTempStatus = pinStatus;
pirCount = 0;
}
}, 50);
function createDevice() {
device = iot.device({
productKey: productKey,
deviceName: deviceName,
deviceSecret: deviceSecret
});
var humidity = 50;
device.on('connect', function () {
console.log('(re)connected');
mqtt_connected = true;
/* post props */
device.postProps(JSON.stringify({
Coil: fanSwitch, CurrentTemperature: temperature, WaterOutletSwitch: waterSwitch, Buzzer: beepSwitch,
CurrentHumidity:humidity, AlarmState: pirStatus, Atmosphere: pressure, SoilTemperature: 25.5,
SoilMoisture: 50.5
}));
/* 云端设置属性事件 */
device.onProps(function (res) {
console.log('cloud req msg_id is ' + res.msg_id);
console.log('cloud req params_len is ' + res.params_len);
console.log('cloud req params is ' + res.params);
var payload = JSON.parse(res.params);
if(payload.Coil !== undefined)
{
fanSwitch = parseInt(payload.Coil);
relay2.writeValue(fanSwitch);
device.postProps(JSON.stringify({
Coil: fanSwitch
}));
}
if(payload.WaterOutletSwitch !== undefined)
{
waterSwitch = parseInt(payload.WaterOutletSwitch);
relay1.writeValue(waterSwitch);
device.postProps(JSON.stringify({
WaterOutletSwitch: waterSwitch
}));
}
if(payload.Buzzer !== undefined)
{
beepSwitch = parseInt(payload.Buzzer);
beep.writeValue(beepSwitch);
device.postProps(JSON.stringify({
Buzzer: beepSwitch
}));
}
});
/* 云端下发服务事件 */
device.onService(function (res) {
console.log('received cloud msg_id is ' + res.msg_id);
console.log('received cloud service_id is ' + res.service_id);
console.log('received cloud params_len is ' + res.params_len);
console.log('received cloud params is ' + res.params);
});
});
/* 网络断开事件 */
device.on('disconnect', function () {
console.log('disconnect ');
mqtt_connected = false;
});
/* 关闭连接事件 */
device.on('end', function () {
console.log('iot client just closed');
mqtt_connected = false;
});
/* 发生错误事件 */
device.on('error', function (err) {
console.log('error ' + err);
});
}
var status = net.getStatus();
console.log('net status is: ' + status);
if (status == 'connect') {
createDevice();
} else {
net.on('connect', function () {
createDevice();
});
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/app.js
|
JavaScript
|
apache-2.0
| 6,792
|
var i2c = require('i2c');
var calibParamT1;
var calibParamT2;
var calibParamT3;
var calibParamP1;
var calibParamP2;
var calibParamP3;
var calibParamP4;
var calibParamP5;
var calibParamP6;
var calibParamP7;
var calibParamP8;
var calibParamP9;
var calibParamT_FINE;
const INVALID_TEMP = -273.15;
const INVALID_PRESS = 0;
var sensor = i2c.open({
id: 'bmp280',
success: function() {
console.log('bmp280 sensor open success')
},
fail: function() {
console.log('bmp280 sensor open failed')
}
});
function bmp280SoftReset()
{
var regaddr = 0xe0;
var regval = [0xb6];
sensor.writeMem(regaddr, regval);
console.log('bmp280 soft reset');
}
function bmp280PowerEnable()
{
var regval = sensor.readMem(0xf4, 1);
regval[0] |= 0x03;
sensor.writeMem(0xf4, regval);
console.log('bmp280 power up');
}
function bmp280PowerDisable()
{
var regval = sensor.readMem(0xf4, 1);
regval[0] &= 0xfc;
sensor.writeMem(0xf4, regval);
console.log('bmp280 power down');
}
function bmp280SetOdr()
{
var regval = sensor.readMem(0xf5, 1);
regval[0] &= 0x1f;
regval[0] |= 0x20;
sensor.writeMem(0xf5, regval);
console.log('bmp280 set odr');
}
function bmp280SetWorkMode()
{
var regval = sensor.readMem(0xf4, 1);
console.log('bmp280 old work mode ' + regval);
regval[0] &= 0x03;
regval[0] |= (0x03 << 5 | 0x03 << 2);
sensor.writeMem(0xf4, regval);
regval = sensor.readMem(0xf4, 1);
console.log('bmp280 new work mode ' + regval);
}
function bmp280ReadCalibParams()
{
var calibTable = sensor.readMem(0x88, 24);
console.log('bmp280 calib table ' + calibTable);
calibParamT1 = (calibTable[1] << 8) | calibTable[0];
calibParamT2 = (calibTable[3] << 8) | calibTable[2];
calibParamT3 = (calibTable[5] << 8) | calibTable[4];
calibParamP1 = (calibTable[7] << 8) | calibTable[6];
calibParamP2 = (calibTable[9] << 8) | calibTable[8];
calibParamP3 = (calibTable[11] << 8) | calibTable[10];
calibParamP4 = (calibTable[13] << 8) | calibTable[12];
calibParamP5 = (calibTable[15] << 8) | calibTable[14];
calibParamP6 = (calibTable[17] << 8) | calibTable[16];
calibParamP7 = (calibTable[19] << 8) | calibTable[18];
calibParamP8 = (calibTable[21] << 8) | calibTable[20];
calibParamP9 = (calibTable[23] << 8) | calibTable[22];
}
function bmp280RegRead(reg, len)
{
var regval = sensor.readMem(reg, len);
if(!regval) {
return;
}
return regval;
}
function bmp280TemperatureRead()
{
var temperature = INVALID_TEMP;
var regval = bmp280RegRead(0xfa, 3);
if (regval) {
var uncomp_temp = (regval[0] << 12) | (regval[1] << 4) | (regval[2] >> 4);
var ta = (((uncomp_temp >> 3) - (calibParamT1 << 1)) * calibParamT2) >> 11;
var tb = (((((uncomp_temp >> 4) - calibParamT1) * ((uncomp_temp >> 4) - calibParamT1)) >> 12) * calibParamT3) >> 14;
calibParamT_FINE = ta + tb;
temperature = ((ta + tb) * 5 + 128) >> 8;
temperature /= 100;
} else {
console.error('Failed to get temperature');
}
return temperature;
}
function bmp280PressureRead()
{
var pressure = INVALID_PRESS;
var regval;
// get t_fine value first
if (bmp280TemperatureRead() == INVALID_TEMP) {
console.error('Failed to get temperature');
return pressure;
}
regval = bmp280RegRead(0xf7, 3);
if (regval) {
var uncomp_press = (regval[0] << 12) | (regval[1] << 4) | (regval[2] >> 4);
var var1 = (calibParamT_FINE >> 1) - 64000;
var var2 = (((var1 >> 2) * (var1 >> 2)) >> 11) * calibParamP6;
var2 = var2 + ((var1 * calibParamP5) << 1);
var2 = (var2 >> 2) + (calibParamP4 << 16);
var1 = (((calibParamP3 * (((var1 >> 2) * (var1 >> 2)) >> 13)) >> 3) + ((calibParamP2 * var1) >> 1)) >> 18;
var1 = ((32768 + var1) * calibParamP1) >> 15;
pressure = ((1048576 - uncomp_press) - (var2 >> 12)) * 3152;
if (var1 != 0) {
if (pressure < 0x80000000) {
//pressure = (pressure << 1) / var1;
pressure = (pressure / var1) << 1;
} else {
pressure = (pressure / var1) << 1;
}
var1 = (calibParamP9 * (((pressure >> 3) * (pressure >> 3)) >> 13)) >> 12;
var2 = ((pressure >> 2) * calibParamP8) >> 13;
pressure = (pressure + ((var1 + var2 + calibParamP7) >> 4))
}
} else {
console.error('Failed to get pressure');
}
return pressure;
}
function bmp280_init()
{
var chipID = sensor.readMem(0xd0, 1);
console.log('bmp280 chip id is ' + chipID);
bmp280SoftReset();
bmp280SetOdr();
bmp280ReadCalibParams();
bmp280SetWorkMode();
bmp280PowerEnable();
}
// for test purpose only
function bmp280_test()
{
var cnt = 10;
var loop = 10;
bmp280_init();
var intervalHandled = setInterval(function(){
console.log('Temperature is ' + bmp280TemperatureRead());
console.log('Pressure is ' + bmp280PressureRead());
cnt--;
if(cnt <= 0){
//clearInterval(intervalHandled)
console.log('bmp280: sensor close ' + loop);
sensor.close();
loop--;
cnt = 1;
if (loop == 0) {
clearInterval(intervalHandled);
}
else {
sensor = i2c.open({
id: 'bmp280',
success: function() {
console.log('bmp280 sensor open success')
},
fail: function() {
console.log('bmp280 sensor open failed')
}
});
}
}
}, 2000);
}
module.exports = {
bmp280_init,
bmp280TemperatureRead,
bmp280PressureRead,
bmp280_test,
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/bmp280.js
|
JavaScript
|
apache-2.0
| 5,871
|
var gpio = require("gpio");
var dht11 = gpio.open({
di: 'dht11'
});
function usleep(us)
{
// TODO
}
function msleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
function gpioSet(level)
{
dht11.writeValue(level);
}
function gpioGet()
{
return dht11.readValue();
}
function reset()
{
gpioSet(0);
await msleep(20);
gpioSet(1);
await msleep(30);
}
function isOnline()
{
var retry = 0;
while (gpioGet() != 0 && retry < 100) {
retry++;
usleep(1);
}
if (retry >= 100) {
console.error("DHT11 pin high!");
return false;
} else {
retry = 0;
}
while (gpioGet() == 0 && retry < 100) {
retry++;
usleep(1);
}
if (retry >= 100) {
console.error("DHT11 pin low!");
return false;
}
return true;
}
function readBit()
{
var retry = 0;
while (gpioGet() != 0 && retry < 100) {
retry++;
usleep(1);
}
retry = 0;
while (gpioGet() == 0 && retry < 100) {
retry++;
usleep(1);
}
usleep(40);
if (gpioGet() != 0) {
return 1;
} else {
return 0;
}
}
function readByte()
{
var i, dat;
for (i = 0; i < 0; i++) {
dat = dat << 1;
dat = dat | readBit();
}
return dat;
}
function readData()
{
var i, humi, temp;
var buf = new Array();
reset();
if (isOnline()) {
for (i = 0; i < 5; i++) {
buf[i] = readByte();
}
if ((buf[0] + buf[1] + buf[2] + buf[3]) == buf[4]) {
humi = buf[0];
temp = buf[2];
}
} else {
console.error("DHT11 is not online!");
return;
}
return [temp, humi];
}
function init()
{
gpioSet(1);
reset();
}
function readTemp()
{
var temp = -273.15, data;
data = readData();
if (data) {
temp = data[0];
}
return temp;
}
function readHumidity()
{
var humi = 0, data;
data = readData();
if (data) {
humi = data[1]
}
return humi;
}
module.exports = {
init,
readTemp,
readHumidity
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/dht11.js
|
JavaScript
|
apache-2.0
| 2,158
|
/**
* @license GPS.js v0.6.0 26/01/2016
*
* Copyright (c) 2016, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
**/
(function (root) {
'use strict';
var D2R = Math.PI / 180;
var collectSats = {};
var lastSeenSat = {};
function updateState(state, data) {
// TODO: can we really use RMC time here or is it the time of fix?
if (data['type'] === 'RMC' || data['type'] === 'GGA' || data['type'] === 'GLL' || data['type'] === 'GNS') {
state['time'] = data['time'];
state['lat'] = data['lat'];
state['lon'] = data['lon'];
}
if (data['type'] === 'ZDA') {
state['time'] = data['time'];
}
if (data['type'] === 'GGA') {
state['alt'] = data['alt'];
}
if (data['type'] === 'RMC' /* || data['type'] === 'VTG'*/ ) {
// TODO: is rmc speed/track really interchangeable with vtg speed/track?
state['speed'] = data['speed'];
state['track'] = data['track'];
}
if (data['type'] === 'GSA') {
state['satsActive'] = data['satellites'];
state['fix'] = data['fix'];
state['hdop'] = data['hdop'];
state['pdop'] = data['pdop'];
state['vdop'] = data['vdop'];
}
if (data['type'] === 'GSV') {
var now = new Date().getTime();
var sats = data['satellites'];
for (var i = 0; i < sats.length; i++) {
var prn = sats[i].prn;
lastSeenSat[prn] = now;
collectSats[prn] = sats[i];
}
var ret = [];
for (var prn in collectSats) {
if (now - lastSeenSat[prn] < 3000) // Sats are visible for 3 seconds
ret.push(collectSats[prn])
}
state['satsVisible'] = ret;
}
}
/**
*
* @param {String} time
* @param {String=} date
* @returns {Date}
*/
function parseTime(time, date) {
if (time === '') {
return null;
}
var ret = new Date;
if (date) {
var year = date.slice(4);
var month = date.slice(2, 4) - 1;
var day = date.slice(0, 2);
if (year.length === 4) {
ret.setUTCFullYear(Number(year), Number(month), Number(day));
} else {
// If we need to parse older GPRMC data, we should hack something like
// year < 73 ? 2000+year : 1900+year
// Since GPS appeared in 1973
ret.setUTCFullYear(Number('20' + year), Number(month), Number(day));
}
}
ret.setUTCHours(Number(time.slice(0, 2)));
ret.setUTCMinutes(Number(time.slice(2, 4)));
ret.setUTCSeconds(Number(time.slice(4, 6)));
// Extract the milliseconds, since they can be not present, be 3 decimal place, or 2 decimal places, or other?
var msStr = time.slice(7);
var msExp = msStr.length;
var ms = 0;
if (msExp !== 0) {
ms = parseFloat(msStr) * Math.pow(10, 3 - msExp);
}
ret.setUTCMilliseconds(Number(ms));
return ret;
}
function parseCoord(coord, dir) {
// Latitude can go from 0 to 90; longitude can go from -180 to 180.
if (coord === '')
return null;
var n, sgn = 1;
switch (dir) {
case 'S':
sgn = -1;
case 'N':
n = 2;
break;
case 'W':
sgn = -1;
case 'E':
n = 3;
break;
}
/*
* Mathematically, but more expensive and not numerical stable:
*
* raw = 4807.038
* deg = Math.floor(raw / 100)
*
* dec = (raw - (100 * deg)) / 60
* res = deg + dec // 48.1173
*/
return sgn * (parseFloat(coord.slice(0, n)) + parseFloat(coord.slice(n)) / 60);
}
function parseNumber(num) {
if (num === '') {
return null;
}
return parseFloat(num);
}
function parseKnots(knots) {
if (knots === '')
return null;
return parseFloat(knots) * 1.852;
}
function parseGSAMode(mode) {
switch (mode) {
case 'M':
return 'manual';
case 'A':
return 'automatic';
case '':
return null;
}
throw new Error('INVALID GSA MODE: ' + mode);
}
function parseGGAFix(fix) {
if (fix === '')
return null;
switch (parseInt(fix, 10)) {
case 0:
return null;
case 1:
return 'fix'; // valid SPS fix
case 2:
return 'dgps-fix'; // valid DGPS fix
case 3:
return 'pps-fix'; // valid PPS fix
case 4:
return 'rtk'; // valid (real time kinematic) RTK fix
case 5:
return 'rtk-float'; // valid (real time kinematic) RTK float
case 6:
return 'estimated'; // dead reckoning
case 7:
return 'manual';
case 8:
return 'simulated';
}
throw new Error('INVALID GGA FIX: ' + fix);
}
function parseGSAFix(fix) {
switch (fix) {
case '1':
case '':
return null;
case '2':
return '2D';
case '3':
return '3D';
}
throw new Error('INVALID GSA FIX: ' + fix);
}
function parseRMC_GLLStatus(status) {
switch (status) {
case 'A':
return 'active';
case 'V':
return 'void';
case '':
return null;
}
throw new Error('INVALID RMC/GLL STATUS: ' + status);
}
function parseFAA(faa) {
// Only A and D will correspond to an Active and reliable Sentence
switch (faa) {
case '':
return null;
case 'A':
return 'autonomous';
case 'D':
return 'differential';
case 'E':
return 'estimated'; // dead reckoning
case 'M':
return 'manual input';
case 'S':
return 'simulated';
case 'N':
return 'not valid';
case 'P':
return 'precise';
case 'R':
return 'rtk'; // valid (real time kinematic) RTK fix
case 'F':
return 'rtk-float'; // valid (real time kinematic) RTK float
}
throw new Error('INVALID FAA MODE: ' + faa);
}
function parseRMCVariation(vari, dir) {
if (vari === '' || dir === '')
return null;
var q = (dir === 'W') ? -1.0 : 1.0;
return parseFloat(vari) * q;
}
function isValid(str, crc) {
var checksum = 0;
for (var i = 1; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c === 42) // Asterisk: *
break;
checksum ^= c;
}
return checksum === parseInt(crc, 16);
}
function parseDist(num, unit) {
if (unit === 'M' || unit === '') {
return parseNumber(num);
}
throw new Error('Unknown unit: ' + unit);
}
/**
*
* @constructor
*/
function GPS() {
if (!(this instanceof GPS)) {
return new GPS;
}
this['events'] = {};
this['state'] = {
'errors': 0,
'processed': 0
};
}
GPS.prototype['events'] = null;
GPS.prototype['state'] = null;
GPS['mod'] = {
// Global Positioning System Fix Data
'GGA': function (str, gga) {
if (gga.length !== 16 && gga.length !== 14) {
throw new Error("Invalid GGA length: " + str);
}
/*
11
1 2 3 4 5 6 7 8 9 10 | 12 13 14 15
| | | | | | | | | | | | | | |
$--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh
1) Time (UTC)
2) Latitude
3) N or S (North or South)
4) Longitude
5) E or W (East or West)
6) GPS Quality Indicator,
0 = Invalid, 1 = Valid SPS, 2 = Valid DGPS, 3 = Valid PPS
7) Number of satellites in view, 00 - 12
8) Horizontal Dilution of precision, lower is better
9) Antenna Altitude above/below mean-sea-level (geoid)
10) Units of antenna altitude, meters
11) Geoidal separation, the difference between the WGS-84 earth
ellipsoid and mean-sea-level (geoid), '-' means mean-sea-level below ellipsoid
12) Units of geoidal separation, meters
13) Age of differential GPS data, time in seconds since last SC104
type 1 or 9 update, null field when DGPS is not used
14) Differential reference station ID, 0000-1023
15) Checksum
*/
return {
'time': parseTime(gga[1]),
'lat': parseCoord(gga[2], gga[3]),
'lon': parseCoord(gga[4], gga[5]),
'alt': parseDist(gga[9], gga[10]),
'quality': parseGGAFix(gga[6]),
'satellites': parseNumber(gga[7]),
'hdop': parseNumber(gga[8]), // dilution
'geoidal': parseDist(gga[11], gga[12]), // aboveGeoid
'age': gga[13] === undefined ? null : parseNumber(gga[13]), // dgps time since update
'stationID': gga[14] === undefined ? null : parseNumber(gga[14]) // dgpsReference??
};
},
// GPS DOP and active satellites
'GSA': function (str, gsa) {
if (gsa.length !== 19 && gsa.length !== 20) {
throw new Error('Invalid GSA length: ' + str);
}
/*
eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C
eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35
1 = Mode:
M=Manual, forced to operate in 2D or 3D
A=Automatic, 3D/2D
2 = Mode:
1=Fix not available
2=2D
3=3D
3-14 = PRNs of Satellite Vehicles (SVs) used in position fix (null for unused fields)
15 = PDOP
16 = HDOP
17 = VDOP
(18) = systemID NMEA 4.10
18 = Checksum
*/
var sats = [];
for (var i = 3; i < 15; i++) {
if (gsa[i] !== '') {
sats.push(parseInt(gsa[i], 10));
}
}
return {
'mode': parseGSAMode(gsa[1]),
'fix': parseGSAFix(gsa[2]),
'satellites': sats,
'pdop': parseNumber(gsa[15]),
'hdop': parseNumber(gsa[16]),
'vdop': parseNumber(gsa[17]),
'systemId': gsa.length > 19 ? parseNumber(gsa[18]) : null
};
},
// Recommended Minimum data for gps
'RMC': function (str, rmc) {
if (rmc.length !== 13 && rmc.length !== 14 && rmc.length !== 15) {
throw new Error('Invalid RMC length: ' + str);
}
/*
$GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh
RMC = Recommended Minimum Specific GPS/TRANSIT Data
1 = UTC of position fix
2 = Data status (A-ok, V-invalid)
3 = Latitude of fix
4 = N or S
5 = Longitude of fix
6 = E or W
7 = Speed over ground in knots
8 = Track made good in degrees True
9 = UT date
10 = Magnetic variation degrees (Easterly var. subtracts from true course)
11 = E or W
(12) = NMEA 2.3 introduced FAA mode indicator (A=Autonomous, D=Differential, E=Estimated, N=Data not valid)
(13) = NMEA 4.10 introduced nav status
12 = Checksum
*/
return {
'time': parseTime(rmc[1], rmc[9]),
'status': parseRMC_GLLStatus(rmc[2]),
'lat': parseCoord(rmc[3], rmc[4]),
'lon': parseCoord(rmc[5], rmc[6]),
'speed': parseKnots(rmc[7]),
'track': parseNumber(rmc[8]), // heading
'variation': parseRMCVariation(rmc[10], rmc[11]),
'faa': rmc.length > 13 ? parseFAA(rmc[12]) : null,
'navStatus': rmc.length > 14 ? rmc[13] : null
};
},
// Track info
'VTG': function (str, vtg) {
if (vtg.length !== 10 && vtg.length !== 11) {
throw new Error('Invalid VTG length: ' + str);
}
/*
------------------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10
| | | | | | | | | |
$--VTG,x.x,T,x.x,M,x.x,N,x.x,K,m,*hh<CR><LF>
------------------------------------------------------------------------------
1 = Track made good (degrees true)
2 = Fixed text 'T' indicates that track made good is relative to true north
3 = optional: Track made good (degrees magnetic)
4 = optional: M: track made good is relative to magnetic north
5 = Speed over ground in knots
6 = Fixed text 'N' indicates that speed over ground in in knots
7 = Speed over ground in kilometers/hour
8 = Fixed text 'K' indicates that speed over ground is in kilometers/hour
(9) = FAA mode indicator (NMEA 2.3 and later)
9/10 = Checksum
*/
if (vtg[2] === '' && vtg[8] === '' && vtg[6] === '') {
return {
'track': null,
'trackMagetic': null,
'speed': null,
'faa': null
};
}
if (vtg[2] !== 'T') {
throw new Error('Invalid VTG track mode: ' + str);
}
if (vtg[8] !== 'K' || vtg[6] !== 'N') {
throw new Error('Invalid VTG speed tag: ' + str);
}
return {
'track': parseNumber(vtg[1]), // heading
'trackMagnetic': vtg[3] === '' ? null : parseNumber(vtg[3]), // heading uncorrected to magnetic north
'speed': parseKnots(vtg[5]),
'faa': vtg.length === 11 ? parseFAA(vtg[9]) : null
};
},
// satellites in view
'GSV': function (str, gsv) {
if (gsv.length % 4 % 3 === 0) {
throw new Error('Invalid GSV length: ' + str);
}
/*
$GPGSV,1,1,13,02,02,213,,03,-3,000,,11,00,121,,14,13,172,05*67
1 = Total number of messages of this type in this cycle
2 = Message number
3 = Total number of SVs in view
repeat [
4 = SV PRN number
5 = Elevation in degrees, 90 maximum
6 = Azimuth, degrees from true north, 000 to 359
7 = SNR (signal to noise ratio), 00-99 dB (null when not tracking, higher is better)
]
N+1 = signalID NMEA 4.10
N+2 = Checksum
*/
var sats = [];
for (var i = 4; i < gsv.length - 3; i += 4) {
var prn = parseNumber(gsv[i]);
var snr = parseNumber(gsv[i + 3]);
/*
Plot satellites in Radar chart with north on top
by linear map elevation from 0° to 90° into r to 0
centerX + cos(azimuth - 90) * (1 - elevation / 90) * radius
centerY + sin(azimuth - 90) * (1 - elevation / 90) * radius
*/
sats.push({
'prn': prn,
'elevation': parseNumber(gsv[i + 1]),
'azimuth': parseNumber(gsv[i + 2]),
'snr': snr,
'status': prn !== null ? (snr !== null ? 'tracking' : 'in view') : null
});
}
return {
'msgNumber': parseNumber(gsv[2]),
'msgsTotal': parseNumber(gsv[1]),
//'satsInView' : parseNumber(gsv[3]), // Can be obtained by satellites.length
'satellites': sats,
'signalId': gsv.length % 4 === 2 ? parseNumber(gsv[gsv.length - 2]) : null // NMEA 4.10 addition
};
},
// Geographic Position - Latitude/Longitude
'GLL': function (str, gll) {
if (gll.length !== 9 && gll.length !== 8) {
throw new Error('Invalid GLL length: ' + str);
}
/*
------------------------------------------------------------------------------
1 2 3 4 5 6 7 8
| | | | | | | |
$--GLL,llll.ll,a,yyyyy.yy,a,hhmmss.ss,a,m,*hh<CR><LF>
------------------------------------------------------------------------------
1. Latitude
2. N or S (North or South)
3. Longitude
4. E or W (East or West)
5. Universal Time Coordinated (UTC)
6. Status A - Data Valid, V - Data Invalid
7. FAA mode indicator (NMEA 2.3 and later)
8. Checksum
*/
return {
'time': parseTime(gll[5]),
'status': parseRMC_GLLStatus(gll[6]),
'lat': parseCoord(gll[1], gll[2]),
'lon': parseCoord(gll[3], gll[4]),
'faa': gll.length === 9 ? parseFAA(gll[7]) : null
};
},
// UTC Date / Time and Local Time Zone Offset
'ZDA': function (str, zda) {
/*
1 = hhmmss.ss = UTC
2 = xx = Day, 01 to 31
3 = xx = Month, 01 to 12
4 = xxxx = Year
5 = xx = Local zone description, 00 to +/- 13 hours
6 = xx = Local zone minutes description (same sign as hours)
*/
// TODO: incorporate local zone information
return {
'time': parseTime(zda[1], zda[2] + zda[3] + zda[4])
//'delta': time === null ? null : (Date.now() - time) / 1000
};
},
'GST': function (str, gst) {
if (gst.length !== 10) {
throw new Error('Invalid GST length: ' + str);
}
/*
1 = Time (UTC)
2 = RMS value of the pseudorange residuals; includes carrier phase residuals during periods of RTK (float) and RTK (fixed) processing
3 = Error ellipse semi-major axis 1 sigma error, in meters
4 = Error ellipse semi-minor axis 1 sigma error, in meters
5 = Error ellipse orientation, degrees from true north
6 = Latitude 1 sigma error, in meters
7 = Longitude 1 sigma error, in meters
8 = Height 1 sigma error, in meters
9 = Checksum
*/
return {
'time': parseTime(gst[1]),
'rms': parseNumber(gst[2]),
'ellipseMajor': parseNumber(gst[3]),
'ellipseMinor': parseNumber(gst[4]),
'ellipseOrientation': parseNumber(gst[5]),
'latitudeError': parseNumber(gst[6]),
'longitudeError': parseNumber(gst[7]),
'heightError': parseNumber(gst[8])
};
},
// add HDT
'HDT': function (str, hdt) {
if (hdt.length !== 4) {
throw new Error('Invalid HDT length: ' + str);
}
/*
------------------------------------------------------------------------------
1 2 3
| | |
$--HDT,hhh.hhh,T*XX<CR><LF>
------------------------------------------------------------------------------
1. Heading in degrees
2. T: indicates heading relative to True North
3. Checksum
*/
return {
'heading': parseFloat(hdt[1]),
'trueNorth': hdt[2] === 'T'
};
},
'GRS': function (str, grs) {
if (grs.length !== 18) {
throw new Error('Invalid GRS length: ' + str);
}
var res = [];
for (var i = 3; i <= 14; i++) {
var tmp = parseNumber(grs[i]);
if (tmp !== null)
res.push(tmp);
}
return {
'time': parseTime(grs[1]),
'mode': parseNumber(grs[2]),
'res': res
};
},
'GBS': function (str, gbs) {
if (gbs.length !== 10 && gbs.length !== 12) {
throw new Error('Invalid GBS length: ' + str);
}
/*
0 1 2 3 4 5 6 7 8
| | | | | | | | |
$--GBS,hhmmss.ss,x.x,x.x,x.x,x.x,x.x,x.x,x.x*hh<CR><LF>
1. UTC time of the GGA or GNS fix associated with this sentence
2. Expected error in latitude (meters)
3. Expected error in longitude (meters)
4. Expected error in altitude (meters)
5. PRN (id) of most likely failed satellite
6. Probability of missed detection for most likely failed satellite
7. Estimate of bias in meters on most likely failed satellite
8. Standard deviation of bias estimate
--
9. systemID (NMEA 4.10)
10. signalID (NMEA 4.10)
*/
return {
'time': parseTime(gbs[1]),
'errLat': parseNumber(gbs[2]),
'errLon': parseNumber(gbs[3]),
'errAlt': parseNumber(gbs[4]),
'failedSat': parseNumber(gbs[5]),
'probFailedSat': parseNumber(gbs[6]),
'biasFailedSat': parseNumber(gbs[7]),
'stdFailedSat': parseNumber(gbs[8]),
'systemId': gbs.length === 12 ? parseNumber(gbs[9]) : null,
'signalId': gbs.length === 12 ? parseNumber(gbs[10]) : null
};
},
'GNS': function (str, gns) {
if (gns.length !== 14 && gns.length !== 15) {
throw new Error('Invalid GNS length: ' + str);
}
return {
'time': parseTime(gns[1]),
'lat': parseCoord(gns[2], gns[3]),
'lon': parseCoord(gns[4], gns[5]),
'mode': gns[6],
'satsUsed': parseNumber(gns[7]),
'hdop': parseNumber(gns[8]),
'alt': parseNumber(gns[9]),
'sep': parseNumber(gns[10]),
'diffAge': parseNumber(gns[11]),
'diffStation': parseNumber(gns[12]),
'navStatus': gns.length === 15 ? gns[13] : null // NMEA 4.10
};
}
};
GPS['Parse'] = function (line) {
if (typeof line !== 'string')
return false;
var nmea = line.split(',');
var last = nmea.pop();
// HDT is 2 items length
if (nmea.length < 2 || line.charAt(0) !== '$' || last.indexOf('*') === -1) {
return false;
}
last = last.split('*');
nmea.push(last[0]);
nmea.push(last[1]);
// Remove $ character and first two chars from the beginning
nmea[0] = nmea[0].slice(3);
if (GPS['mod'][nmea[0]] !== undefined) {
// set raw data here as well?
var data = this['mod'][nmea[0]](line, nmea);
data['raw'] = line;
data['valid'] = isValid(line, nmea[nmea.length - 1]);
data['type'] = nmea[0];
return data;
}
return false;
};
// Heading (N=0, E=90, S=189, W=270) from point 1 to point 2
GPS['Heading'] = function (lat1, lon1, lat2, lon2) {
var dlon = (lon2 - lon1) * D2R;
lat1 = lat1 * D2R;
lat2 = lat2 * D2R;
var sdlon = Math.sin(dlon);
var cdlon = Math.cos(dlon);
var slat1 = Math.sin(lat1);
var clat1 = Math.cos(lat1);
var slat2 = Math.sin(lat2);
var clat2 = Math.cos(lat2);
var y = sdlon * clat2;
var x = clat1 * slat2 - slat1 * clat2 * cdlon;
var head = Math.atan2(y, x) * 180 / Math.PI;
return (head + 360) % 360;
};
GPS['Distance'] = function (lat1, lon1, lat2, lon2) {
// Haversine Formula
// R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159
// Because Earth is no exact sphere, rounding errors may be up to 0.5%.
// var RADIUS = 6371; // Earth radius average
// var RADIUS = 6378.137; // Earth radius at equator
var RADIUS = 6372.8; // Earth radius in km
var hLat = (lat2 - lat1) * D2R * 0.5; // Half of lat difference
var hLon = (lon2 - lon1) * D2R * 0.5; // Half of lon difference
lat1 = lat1 * D2R;
lat2 = lat2 * D2R;
var shLat = Math.sin(hLat);
var shLon = Math.sin(hLon);
var clat1 = Math.cos(lat1);
var clat2 = Math.cos(lat2);
var tmp = shLat * shLat + clat1 * clat2 * shLon * shLon;
//return RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
return RADIUS * 2 * Math.asin(Math.sqrt(tmp));
};
GPS['TotalDistance'] = function (path) {
if (path.length < 2)
return 0;
var len = 0;
for (var i = 0; i < path.length - 1; i++) {
var c = path[i];
var n = path[i + 1];
len += GPS['Distance'](c['lat'], c['lon'], n['lat'], n['lon']);
}
return len;
};
GPS.prototype['update'] = function (line) {
var parsed = GPS['Parse'](line);
this['state']['processed']++;
if (parsed === false) {
this['state']['errors']++;
return false;
}
updateState(this['state'], parsed);
this['emit']('data', parsed);
this['emit'](parsed.type, parsed);
return true;
};
GPS.prototype['partial'] = "";
GPS.prototype['updatePartial'] = function (chunk) {
this['partial'] += chunk;
while (true) {
var pos = this['partial'].indexOf("\r\n");
if (pos === -1)
break;
var line = this['partial'].slice(0, pos);
if (line.charAt(0) === '$') {
this['update'](line);
}
this['partial'] = this['partial'].slice(pos + 2);
}
};
GPS.prototype['on'] = function (ev, cb) {
if (this['events'][ev] === undefined) {
this['events'][ev] = cb;
return this;
}
return null;
};
GPS.prototype['off'] = function (ev) {
if (this['events'][ev] !== undefined) {
this['events'][ev] = undefined;
}
return this;
};
GPS.prototype['emit'] = function (ev, data) {
if (this['events'][ev] !== undefined) {
this['events'][ev].call(this, data);
}
};
if (typeof exports === 'object') {
Object.defineProperty(exports, "__esModule", {
'value': true
});
GPS['default'] = GPS;
GPS['GPS'] = GPS;
module['exports'] = GPS;
} else {
root['GPS'] = GPS;
}
})(this);
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/gps.js
|
JavaScript
|
apache-2.0
| 24,532
|
/* Please insert below lines to app.json file if you want to enable lm75:
"I2C0": {
"type": "I2C",
"port": 0,
"addrWidth": 7,
"freq": 400000,
"mode": "master",
"devAddr": 72
},
*/
var i2c = require('i2c');
var lm75 =
function lm75Init()
{
lm75 = i2c.open({
id: 'I2C0'
});
}
function lm75tmpGet()
{
var sig = 1;
var temp;
var regval = lm75.readMem(0x00, 2);
var tempAll = (regval[0] << 8) + regval[1];
if (regval[0] & 0x80 != 0) {
tempAll = ~(tempAll) + 1;
sig = -1;
}
tempAll = tempAll >> 5;
temp = tempAll * 0.125 * sig;
return temp;
}
module.exports = {
lm75Init,
lm75tmpGet
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/lm75.js
|
JavaScript
|
apache-2.0
| 724
|
function Modbus(uartPort, dirPort) {
var rtn = {}
var lastTid = 1
rtn.readTimeout = 500;
rtn.readTimeouthandler;
rtn.packetBufferLength = 100
rtn.packets = []
rtn.stream = Serial(uartPort, dirPort)
rtn.protocal = 'rtu'
rtn.read = function (unitId, address, timeout, callback) {
var parsedAddress = parseAddress(address)
var funcCode = parsedAddress.fcRead
var length = parsedAddress.length
address = parsedAddress.address
rtn.readTimeout = timeout
rtn.readTimeouthandler = setTimeout(function() {
rtn.packets[tid].promiseReject('timeout')
}, rtn.readTimeout)
var tid = getTid()
var buff = makeDataPacket(tid, 0, unitId, funcCode, address, null, length)
if (rtn.protocal == 'rtu') { buff = buff.rtu }
var packet = {
onResponce: callback,
tx: {
funcCode: funcCode,
tid: tid,
address: address,
hex: buff.toString('hex')
},
promiseResolve: null,
promiseReject: null,
rx: null
}
rtn.packets[tid] = packet
rtn.stream.send(buff)
console.log('read send ' + buff.toString('hex'))
return new Promise(function (resolve, reject) {
rtn.packets[tid].promiseResolve = resolve
rtn.packets[tid].promiseReject = reject
})
}
rtn.write = function (unitId, address, value, timeout, callback) {
var parsedAddress = parseAddress(address)
var funcCode = parsedAddress.fcWrite
var length = parsedAddress.length
address = parsedAddress.address
var tid = getTid()
rtn.readTimeout = timeout
rtn.readTimeouthandler = setTimeout(function() {
rtn.packets[tid].promiseReject('timeout')
}, rtn.readTimeout)
if (funcCode == 5 && value == true) { value = 65280 } // To force a coil on you send FF00 not 0001
var buff = makeDataPacket(tid, 0, unitId, funcCode, address, value, length)
if (rtn.protocal == 'rtu') { buff = buff.rtu }
// console.log('buff ' + buff)
var packet = {
onResponce: callback,
tx: {
funcCode: funcCode,
tid: tid,
address: address,
hex: buff.toString('hex')
},
rx: null
}
rtn.packets[tid] = packet
rtn.stream.send(buff)
console.log('write send ' + buff.toString('hex'))
return new Promise(function (resolve, reject) {
rtn.packets[tid].promiseResolve = resolve
rtn.packets[tid].promiseReject = reject
})
}
var getTid = function () {
if (lastTid > rtn.packetBufferLength) { lastTid = 0 }
lastTid++
if (rtn.protocal == 'rtu') { lastTid = 0 }
return lastTid
}
rtn.stream.onData = function (buf) {
console.log('onData: ' + buf.toString('hex'))
var modbusRes
if (rtn.protocal == "rtu") { modbusRes = parseResponseRtu(buf) }
var value = modbusRes.value
var tid = modbusRes.tid
if (rtn.protocal == "rtu") { tid = 0 }
var err = null
if (modbusRes.exceptionCode) { err = 'Exception Code: 02 - Illegal Data Address' }
rtn.packets[tid].rx = modbusRes
rtn.packets[tid].rx.hex = buf.toString('hex')
if (typeof (rtn.packets[tid].onResponce) == "function") {
rtn.packets[tid].onResponce(err, value)
}
if (err) {
rtn.packets[tid].promiseReject(err)
}
else {
// console.log('raw data:', value)
rtn.packets[tid].promiseResolve(value)
clearTimeout(rtn.readTimeouthandler)
}
}
return rtn
}
function parseResponseRtu(buffer) {
var res = {}
res.tid = 1
var buf = new Buffer(buffer)
res.unitId = buf.readInt8(0) //Unit Id - Byte 6
res.funcCode = buf.readInt8(1) //Function Code - Byte 7
res.byteCount = Math.abs(buf.readInt8(2)) //Byte Count - Byte 8
if (buf.length > 3) {
// res.value = buf.readIntBE(3, buf.length - 5) //Data - Bytes 9+
// var arr = Array.prototype.slice.call(new Uint8Array(buf))
// res.value = new Buffer(arr.slice(3, buf.length - 5))
var dataBuffer = buf.subarray(3, buf.length - 2)
res.value = Array.prototype.slice.call(new Uint8Array(buf))
}
return res
}
function crc16modbus(buf, previous) {
var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
}
function makeDataPacket(transId, protoId, unitId, funcCode, address, data, length) {
if (typeof (data) == "boolean" && data) { data = 1 }
if (typeof (data) == "boolean" && !data) { data = 0 }
if (address == 0) { address = 65535 }
else { address = address - 1 }
var dataBytes = 0
if (funcCode == 15) { dataBytes = length }
if (funcCode == 16) { dataBytes = length * 2 }
var bufferLength = 12
if (funcCode == 15 || funcCode == 16) { bufferLength = 13 + dataBytes }
var byteCount = bufferLength - 6
var buf = new Buffer(bufferLength)
buf.writeUInt16BE(transId, 0)
buf.writeUInt16BE(protoId, 2)
buf.writeUInt16BE(byteCount, 4)
buf.writeUInt8(unitId, 6)
buf.writeUInt8(funcCode, 7)
buf.writeUInt16BE(address, 8)
if (funcCode == 1 || funcCode == 2 || funcCode == 3 || funcCode == 4) {
buf.writeUInt16BE(length, 10)
}
if (funcCode == 5 || funcCode == 6) {
buf.writeInt16BE(data, 10)
}
if (funcCode == 15 || funcCode == 16) {
buf.writeInt16BE(length, 10)
buf.writeUInt8(dataBytes, 12)
buf.writeInt32BE(data, 13)
}
var makeCrc = crc16modbus
var bufRtu = buf.slice(6, bufferLength)
var crc = makeCrc(bufRtu)
var arr = Array.prototype.slice.call(new Uint8Array(bufRtu))
arr.push(0);
arr.push(0);
var buffRtu = new Buffer(arr);
buffRtu.writeUInt16LE(crc, buffRtu.length - 2)
//console.log('buffRtu:', buffRtu);
return { rtu: Array.prototype.slice.call(new Uint8Array(buffRtu)) }
}
function parseAddress(address) {
var rtn = {}
address = address.toLowerCase()
// 提取地址
// Data Type Short Hand Size Accessibility
// Descrite Input i 1 Bit Read Only
// Coil c 1 Bit Read / Write
// Input Register ir 16 Bits Read Only
// Holding Register hr 16 Bits Read / Write
var isRegister = address.replace('r', '').length !== address.length;
if (isRegister) {
rtn.address = address.substr(2)
rtn.type = address.substr(0, 2)
}
if (!isRegister) {
rtn.address = address.substr(1)
rtn.type = address.substr(0, 1)
}
var isRange = rtn.address.replace('-', '').length !== rtn.address.length
if (isRange) {
var range = rtn.address.split('-')
rtn.length = range[0] - range[1]
if (rtn.length < 0) { rtn.address = range[0] }
if (rtn.length > 0) { rtn.address = range[1] }
rtn.length = Math.abs(rtn.length) + 1
}
if (!isRange) {
rtn.length = 1
}
rtn.address = parseInt(rtn.address)
// 获取类型
// FC1 - Read Coil
// FC2 - Read Input
// FC3 - Read Holding Registers
// FC4 - Read Input Registers
// FC5 - Write Single Coil
// FC6 - Write Single Register
// FC15 - Write Multiple Coils
// FC16 - Write Multiple Registers
if (rtn.type == 'c') {
rtn.fcRead = 1
rtn.fcWrite = 5
}
if (rtn.type == 'i') {
rtn.fcRead = 2
}
if (rtn.type == 'hr' && !isRange) {
rtn.fcRead = 3
rtn.fcWrite = 6
}
if (rtn.type == 'hr' && isRange) {
rtn.fcRead = 3
rtn.fcWrite = 16
}
if (rtn.type == 'ir') {
rtn.fcRead = 4
}
return rtn
}
function Serial(uartPort, dirPort) {
var rtn = {}
var Uart = require('uart')
rtn.port = Uart.open(uartPort)
if (dirPort) {
var events = require('events');
var event = new events();
var Gpio = require('gpio')
var option = {};
option.id = dirPort.id;
rtn.io = Gpio.open(option);
}
rtn.send = function (data) {
rtn.io.writeValue(dirPort.polarity === 0 ? 0 : 1);
rtn.port.write(data)
event.emit('send')
}
rtn.onData = function () { }
rtn.port.on('data', function (data) {
console.log("rtn onData");
rtn.onData(data);
})
event.on('send', function () {
rtn.io.writeValue(dirPort.polarity === 0 ? 1 : 0);
})
return rtn
}
module.exports = Modbus;
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/agriculture_demo/modbus.js
|
JavaScript
|
apache-2.0
| 11,179
|
import * as adc from 'adc'
var vol = adc.open({
id: 'battery',
success: function () {
console.log('adc: open adc success')
},
fail: function () {
console.log('adc: open adc failed')
}
});
var value = vol.readValue()
console.log('adc value is ' + value)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/adc.js
|
JavaScript
|
apache-2.0
| 296
|
import * as dac from 'dac'
// led灯
var vol = dac.open({
id: 'voltage',
success: function () {
console.log('open dac success')
},
fail: function () {
console.log('open dac failed')
}
});
vol.writeValue(65536 / 2)
var value = vol.readValue();
console.log('voltage value is ' + value)
vol.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/dac.js
|
JavaScript
|
apache-2.0
| 340
|
import * as DS18B20 from 'ds18b20'
/*
Please add this section into app.json when run this script as app.js.
This configuration is designed for haas100 edu k1.
{
"version": "1.0.0",
"io": {
"DS18B20": {
"type": "GPIO",
"port": 4,
"dir": "output",
"pull": "pullup"
}
},
"debugLevel": "DEBUG"
}
*/
console.log('testing DS18B20...');
DS18B20.init("DS18B20");
var temperature;
var count = 10;
while(count-- > 0)
{
temperature = DS18B20.getTemperature();
{
console.log("Temperature is: " , temperature);
}
}
DS18B20.deinit();
console.log("test DS18B20 success!");
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/ds18b20.js
|
JavaScript
|
apache-2.0
| 670
|
import * as fs from 'fs'
var path = '/workspace/dev_amp/test.data';
//var path = '/tmp/test.data';
var content = 'this is amp fs test file';
console.log('testing fs write...');
// write file
fs.writeSync(path, content);
console.log('testing fs read...');
// read file
var data = fs.readSync(path);
console.log('fs read: ' + data);
console.log('testing fs delete...');
fs.unlinkSync(path);
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/fs.js
|
JavaScript
|
apache-2.0
| 393
|
import * as i2c from 'i2c'
var memaddr = 0x18
var msgbuf = [0x10, 0xee]
var sensor = i2c.open({
id: 'I2C0',
success: function () {
console.log('open i2c success')
},
fail: function () {
console.log('open i2c failed')
}
});
sensor.write(msgbuf)
var value = sensor.read(2)
console.log('sensor read ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.writeMem(memaddr, msgbuf)
var vol = sensor.readMem(memaddr, 2)
console.log('sensor read mem vol is ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/i2c.js
|
JavaScript
|
apache-2.0
| 593
|
import * as kv from 'kv'
console.log('testing kv...');
var key = 'key-test';
var value = 'this is amp kv test file';
// kv set
kv.setStorageSync(key, value);
// kv get
var val = kv.getStorageSync(key);
console.log('kv read: ' + val);
// kv remove
kv.removeStorageSync(key);
console.log('testing kv end');
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/kv.js
|
JavaScript
|
apache-2.0
| 310
|
import * as lcd from 'lcd'
var msgbuf = 'this is amp lcd test'
lcd.open();
//var value = lcd.show(0, 0, 320, 240, buf);
var value = lcd.fill(0, 0, 320, 240, 0xffffffff);
console.log('lcd fill value is ' + value)
lcd.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/lcd.js
|
JavaScript
|
apache-2.0
| 231
|
// {
// "version": "1.0.0",
// "io": {
// "oled_dc": {
// "type": "GPIO",
// "port": 28,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_res": {
// "type": "GPIO",
// "port": 30,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_spi": {
// "type": "SPI",
// "port": 1,
// "mode": "mode3",
// "freq": 26000000
// }
// },
// "debugLevel": "DEBUG"
// }
import * as spi from 'spi'
import * as gpio from 'gpio'
import SH1106 from './sh1106.js'
var oled_spi = spi.open({ id: "oled_spi" });
var oled_dc = gpio.open({ id: "oled_dc" });
var oled_res = gpio.open({ id: "oled_res" });
var dispaly = new SH1106(132, 64, oled_spi, oled_dc, oled_res, undefined)
dispaly.open()
var HAAS_XBM_width = 23
var HAAS_XBM_height = 9
dispaly.fill(0)
var HAAS_XBM = [0xff, 0xff, 0xfe, 0x80, 0x00, 0x02, 0xa4, 0xc6, 0x7a, 0xa5, 0x29, 0x42, 0xbd, 0xef, 0x7a, 0xa5, 0x29, 0x0a, 0xa5, 0x29, 0x7a, 0x80, 0x00, 0x02, 0xff, 0xff, 0xfe]
dispaly.draw_XBM(40, 20, HAAS_XBM_width, HAAS_XBM_height, HAAS_XBM)
dispaly.show()
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/oled.js
|
JavaScript
|
apache-2.0
| 1,217
|
/*
* PWM's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"pwm0": {
"type": "PWM",
"port": 0
},
"timer1": {
"type":"TIMER",
"port": 0
}
},
"debugLevel": "DEBUG"
}
*/
import * as pwm from 'pwm'
import * as timer from 'timer'
console.log('pwm: pwm test open ')
var pwm1 = pwm.open({
id: 'pwm0',
success: function() {
console.log('pwm: open pwm success')
},
fail: function() {
console.log('pwm: open pwm failed')
}
});
var timer1 = timer.open({
id: 'timer1'
});
var freq = pwm1.get().freq
var duty = pwm1.get().duty
console.log('pwm: pwm default config freq is ' + freq + ' duty is ' + duty)
console.log('pwm: pwm test start ')
duty = 0;
var cnt = 10;
var loop = 10;
timer1.setInterval(function(){
if (duty >= 100) {
duty = 0;
}
duty = duty + 10;
pwm1.set({
freq: 200, /* Configure 200 ~ 900 to make the buzzer work */
duty: duty
})
freq = pwm1.get().freq
duty = pwm1.get().duty
console.log('pwm: pwm timer config freq is ' + freq + ' duty is ' + duty)
console.log('pwm: pwm test count ' + cnt)
cnt = cnt - 1;
if (cnt == 0) {
console.log('pwm: pwm test finish loop ' + loop)
loop--;
if (loop == 0)
{
pwm1.close();
timer1.clearInterval();
}
// else {
// pwm1 = pwm.open({
// id: 'pwm1',
// success: function() {
// console.log('pwm: open pwm success')
// },
// fail: function() {
// console.log('pwm: open pwm failed')
// }
// });
// }
cnt = 10;
}
}, 1000000)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/pwm.js
|
JavaScript
|
apache-2.0
| 1,706
|
import * as rtc from 'rtc'
rtc.start();
var current_time = rtc.getTime();
console.log('rtc1: current time is ' + current_time);
var my_date = new Date();
my_date.setFullYear(2008,7,9);
console.log('rtc1: time.getYear() ' + my_date.getYear());
console.log('rtc1: time.getMonth() ' + my_date.getMonth());
console.log('rtc1: time.getDate() ' + my_date.getDate());
console.log('rtc1: time.getHours() ' + my_date.getHours());
console.log('rtc1: time.getMinutes() ' + my_date.getMinutes());
console.log('rtc1: time.getSeconds() ' + my_date.getSeconds());
rtc.setTime(my_date);
console.log('Date is ' + my_date.toUTCString());
current_time = rtc.getTime();
console.log('rtc2: current time is ' + current_time);
rtc.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/rtc.js
|
JavaScript
|
apache-2.0
| 725
|
import * as uart from 'uart'
/* Uart's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"serial": {
"type": "UART",
"port": 2,
"dataWidth":8,
"baudRate":115200,
"stopBits":0,
"flowControl":"disable",
"parity":"none"
}
},
"debugLevel": "DEBUG"
}
*/
var msgbuf = 'this is amp uart test'
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
console.log('uart open')
var serial = uart.open({
id: 'serial',
//mode: 'poll', //just for read mode
success: function() {
console.log('open uart success')
},
fail: function() {
console.log('open uart failed')
}
});
console.log('uart write')
serial.write(msgbuf);
sleepMs(1000);
console.log('uart read')
var rCnt = 0;
var rtrn = 0;
var value = ''
//just for read mode
// while(1)
// {
// rtrn = serial.read()
// if(0 != rtrn)
// {
// value += ab2str(rtrn);
// rCnt++;
// }
// if(rCnt > 10)
// {
// break;
// }
// }
// console.log('sensor value is ' + value)
serial.on('data', function(data, len) {
console.log('uart receive data len is : ' + len + ' data is: ' + ab2str(data));
})
//serial.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/uart.js
|
JavaScript
|
apache-2.0
| 1,266
|
#waring {
font-color: #ffffff;
font-size: 16px;
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/uipages/page/waring.css
|
CSS
|
apache-2.0
| 55
|
var ui = require('ui');
if (!(ui && ui.redirectTo)) {
throw new Error("ui: [failed] require(\'ui\')");
}
Page({
onShow: function() {
console.log('enter page onShow');
},
onExit: function() {
console.log('enter page onExit');
},
onUpdate: function() {
console.log('enter page onUpdate');
}
});
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/uipages/page/waring.js
|
JavaScript
|
apache-2.0
| 327
|
import * as wdg from 'wdg'
console.log("hello world\n")
wdg.start(2000);
wdg.feed();
wdg.stop();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas-edu-k1/wdg.js
|
JavaScript
|
apache-2.0
| 100
|
import * as adc from 'adc'
var vol = adc.open({
id: 'battery',
success: function () {
console.log('adc: open adc success')
},
fail: function () {
console.log('adc: open adc failed')
}
});
var value = vol.readValue()
console.log('adc value is ' + value)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/adc.js
|
JavaScript
|
apache-2.0
| 296
|
import * as dac from 'dac'
// led灯
var vol = dac.open({
id: 'voltage',
success: function () {
console.log('open dac success')
},
fail: function () {
console.log('open dac failed')
}
});
vol.writeValue(65536 / 2)
var value = vol.readValue();
console.log('voltage value is ' + value)
vol.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/dac.js
|
JavaScript
|
apache-2.0
| 340
|
import * as DS18B20 from 'ds18b20'
/*
Please add this section into app.json when run this script as app.js.
This configuration is designed for haas100 edu k1.
{
"version": "1.0.0",
"io": {
"DS18B20": {
"type": "GPIO",
"port": 4,
"dir": "output",
"pull": "pullup"
}
},
"debugLevel": "DEBUG"
}
*/
console.log('testing DS18B20...');
DS18B20.init("DS18B20");
var temperature;
var count = 10;
while(count-- > 0)
{
temperature = DS18B20.getTemperature();
{
console.log("Temperature is: " , temperature);
}
}
DS18B20.deinit();
console.log("test DS18B20 success!");
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/ds18b20.js
|
JavaScript
|
apache-2.0
| 670
|
import * as fs from 'fs'
var path = '/workspace/dev_amp/test.data';
//var path = '/tmp/test.data';
var content = 'this is amp fs test file';
console.log('testing fs write...');
// write file
fs.writeSync(path, content);
console.log('testing fs read...');
// read file
var data = fs.readSync(path);
console.log('fs read: ' + data);
console.log('testing fs delete...');
fs.unlinkSync(path);
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/fs.js
|
JavaScript
|
apache-2.0
| 393
|
import * as i2c from 'i2c'
var memaddr = 0x18
var msgbuf = [0x10, 0xee]
var sensor = i2c.open({
id: 'I2C0',
success: function () {
console.log('open i2c success')
},
fail: function () {
console.log('open i2c failed')
}
});
sensor.write(msgbuf)
var value = sensor.read(2)
console.log('sensor read ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.writeMem(memaddr, msgbuf)
var vol = sensor.readMem(memaddr, 2)
console.log('sensor read mem vol is ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/i2c.js
|
JavaScript
|
apache-2.0
| 593
|
import * as kv from 'kv'
console.log('testing kv...');
var key = 'key-test';
var value = 'this is amp kv test file';
// kv set
kv.setStorageSync(key, value);
// kv get
var val = kv.getStorageSync(key);
console.log('kv read: ' + val);
// kv remove
kv.removeStorageSync(key);
console.log('testing kv end');
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/kv.js
|
JavaScript
|
apache-2.0
| 310
|
import * as lcd from 'lcd'
var msgbuf = 'this is amp lcd test'
lcd.open();
//var value = lcd.show(0, 0, 320, 240, buf);
var value = lcd.fill(0, 0, 320, 240, 0xffffffff);
console.log('lcd fill value is ' + value)
lcd.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/lcd.js
|
JavaScript
|
apache-2.0
| 231
|
// {
// "version": "1.0.0",
// "io": {
// "oled_dc": {
// "type": "GPIO",
// "port": 28,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_res": {
// "type": "GPIO",
// "port": 30,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_spi": {
// "type": "SPI",
// "port": 1,
// "mode": "mode3",
// "freq": 26000000
// }
// },
// "debugLevel": "DEBUG"
// }
import * as spi from 'spi'
import * as gpio from 'gpio'
import SH1106 from './sh1106.js'
var oled_dc = gpio.open({
id: "oled_dc",
success: function () {
console.log('gpio: open oled_dc success')
},
fail: function () {
console.log('gpio: open oled_dc failed')
}
});
var oled_res = gpio.open({
id: "oled_res",
success: function () {
console.log('gpio: open oled_res success')
},
fail: function () {
console.log('gpio: open oled_res failed')
}
});
var oled_spi = spi.open({
id: "oled_spi",
success: function () {
console.log('gpio: open oled_spi success')
},
fail: function () {
console.log('gpio: open oled_spi failed')
}
});
console.log("look here!!!!")
let dispaly = new SH1106(132, 64, oled_spi, oled_dc, oled_res, undefined)
dispaly.open()
while (1) {
dispaly.fill(1)
dispaly.show()
dispaly.fill(0)
dispaly.show()
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/oled.js
|
JavaScript
|
apache-2.0
| 1,525
|
/*
* PWM's options are configured in app.json.
* HaaS100
{
"version": "0.0.1",
"io": {
"pwm1": {
"type": "PWM",
"port": 1
},
"timer1": {
"type":"TIMER",
"port": 0
}
},
"debugLevel": "DEBUG"
}
*/
/*
* PWM's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"pwm1": {
"type": "PWM",
"port": 1
},
"timer1": {
"type":"TIMER",
"port": 1
}
},
"debugLevel": "DEBUG"
}
*/
import * as pwm from 'pwm'
import * as timer from 'timer'
console.log('pwm: pwm test open ')
var pwm1 = pwm.open({
id: 'pwm1',
success: function() {
console.log('pwm: open pwm success')
},
fail: function() {
console.log('pwm: open pwm failed')
}
});
var timer1 = timer.open({
id: 'timer1'
});
var freq = pwm1.get().freq
var duty = pwm1.get().duty
console.log('pwm: pwm default config freq is ' + freq + ' duty is ' + duty)
console.log('pwm: pwm test start ')
duty = 0;
var cnt = 10;
var loop = 10;
timer1.setInterval(function(){
if (duty >= 100) {
duty = 0;
}
duty = duty + 10;
pwm1.set({
freq: 100000,
duty: duty
})
freq = pwm1.get().freq
duty = pwm1.get().duty
console.log('pwm: pwm timer config freq is ' + freq + ' duty is ' + duty)
console.log('pwm: pwm test count ' + cnt)
cnt = cnt - 1;
if (cnt == 0) {
console.log('pwm: pwm test finish loop ' + loop)
loop--;
if (loop == 0)
{
pwm1.close();
timer1.clearInterval();
}
// else {
// pwm1 = pwm.open({
// id: 'pwm1',
// success: function() {
// console.log('pwm: open pwm success')
// },
// fail: function() {
// console.log('pwm: open pwm failed')
// }
// });
// }
cnt = 10;
}
}, 1000000)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/pwm.js
|
JavaScript
|
apache-2.0
| 1,925
|
import * as rtc from 'rtc'
rtc.start();
var current_time = rtc.getTime();
console.log('rtc1: current time is ' + current_time);
var my_date = new Date();
my_date.setFullYear(2008,7,9);
console.log('rtc1: time.getYear() ' + my_date.getYear());
console.log('rtc1: time.getMonth() ' + my_date.getMonth());
console.log('rtc1: time.getDate() ' + my_date.getDate());
console.log('rtc1: time.getHours() ' + my_date.getHours());
console.log('rtc1: time.getMinutes() ' + my_date.getMinutes());
console.log('rtc1: time.getSeconds() ' + my_date.getSeconds());
rtc.setTime(my_date);
console.log('Date is ' + my_date.toUTCString());
current_time = rtc.getTime();
console.log('rtc2: current time is ' + current_time);
rtc.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/rtc.js
|
JavaScript
|
apache-2.0
| 725
|
import * as uart from 'uart'
/* Uart's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"serial": {
"type": "UART",
"port": 2,
"dataWidth":8,
"baudRate":115200,
"stopBits":0,
"flowControl":"disable",
"parity":"none"
}
},
"debugLevel": "DEBUG"
}
*/
var msgbuf = 'this is amp uart test'
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
console.log('uart open')
var serial = uart.open({
id: 'serial',
//mode: 'poll', //just for read mode
success: function() {
console.log('open uart success')
},
fail: function() {
console.log('open uart failed')
}
});
console.log('uart write')
serial.write(msgbuf);
sleepMs(1000);
console.log('uart read')
var rCnt = 0;
var rtrn = 0;
var value = ''
//just for read mode
// while(1)
// {
// rtrn = serial.read()
// if(0 != rtrn)
// {
// value += ab2str(rtrn);
// rCnt++;
// }
// if(rCnt > 10)
// {
// break;
// }
// }
// console.log('sensor value is ' + value)
serial.on('data', function(data, len) {
console.log('uart receive data len is : ' + len + ' data is: ' + ab2str(data));
})
//serial.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/uart.js
|
JavaScript
|
apache-2.0
| 1,266
|
import * as wdg from 'wdg'
console.log("hello world\n")
wdg.start(2000);
wdg.feed();
wdg.stop();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas100/wdg.js
|
JavaScript
|
apache-2.0
| 100
|
import * as adc from 'adc'
var vol = adc.open({
id: 'battery',
success: function () {
console.log('adc: open adc success')
},
fail: function () {
console.log('adc: open adc failed')
}
});
var value = vol.readValue()
console.log('adc value is ' + value)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/adc.js
|
JavaScript
|
apache-2.0
| 296
|
import * as dac from 'dac'
// led灯
var vol = dac.open({
id: 'voltage',
success: function () {
console.log('open dac success')
},
fail: function () {
console.log('open dac failed')
}
});
vol.writeValue(65536 / 2)
var value = vol.readValue();
console.log('voltage value is ' + value)
vol.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/dac.js
|
JavaScript
|
apache-2.0
| 340
|
import * as DS18B20 from 'ds18b20'
/*
Please add this section into app.json when run this script as app.js.
This configuration is designed for haas100 edu k1.
{
"version": "1.0.0",
"io": {
"DS18B20": {
"type": "GPIO",
"port": 4,
"dir": "output",
"pull": "pullup"
}
},
"debugLevel": "DEBUG"
}
*/
console.log('testing DS18B20...');
DS18B20.init("DS18B20");
var temperature;
var count = 10;
while(count-- > 0)
{
temperature = DS18B20.getTemperature();
{
console.log("Temperature is: " , temperature);
}
}
DS18B20.deinit();
console.log("test DS18B20 success!");
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/ds18b20.js
|
JavaScript
|
apache-2.0
| 670
|
import * as fs from 'fs'
var path = '/workspace/dev_amp/test.data';
//var path = '/tmp/test.data';
var content = 'this is amp fs test file';
console.log('testing fs write...');
// write file
fs.writeSync(path, content);
console.log('testing fs read...');
// read file
var data = fs.readSync(path);
console.log('fs read: ' + data);
console.log('testing fs delete...');
fs.unlinkSync(path);
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/fs.js
|
JavaScript
|
apache-2.0
| 393
|
import * as i2c from 'i2c'
var memaddr = 0x18
var msgbuf = [0x10, 0xee]
var sensor = i2c.open({
id: 'I2C0',
success: function () {
console.log('open i2c success')
},
fail: function () {
console.log('open i2c failed')
}
});
sensor.write(msgbuf)
var value = sensor.read(2)
console.log('sensor read ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.writeMem(memaddr, msgbuf)
var vol = sensor.readMem(memaddr, 2)
console.log('sensor read mem vol is ' + '0x' + value[0].toString(16) + ' 0x' + value[1].toString(16))
sensor.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/i2c.js
|
JavaScript
|
apache-2.0
| 593
|
import * as kv from 'kv'
console.log('testing kv...');
var key = 'key-test';
var value = 'this is amp kv test file';
// kv set
kv.setStorageSync(key, value);
// kv get
var val = kv.getStorageSync(key);
console.log('kv read: ' + val);
// kv remove
kv.removeStorageSync(key);
console.log('testing kv end');
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/kv.js
|
JavaScript
|
apache-2.0
| 310
|
import * as lcd from 'lcd'
var msgbuf = 'this is amp lcd test'
lcd.open();
//var value = lcd.show(0, 0, 320, 240, buf);
var value = lcd.fill(0, 0, 320, 240, 0xffffffff);
console.log('lcd fill value is ' + value)
lcd.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/lcd.js
|
JavaScript
|
apache-2.0
| 231
|
// {
// "version": "1.0.0",
// "io": {
// "oled_dc": {
// "type": "GPIO",
// "port": 28,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_res": {
// "type": "GPIO",
// "port": 30,
// "dir": "output",
// "pull": "pulldown"
// },
// "oled_spi": {
// "type": "SPI",
// "port": 1,
// "mode": "mode3",
// "freq": 26000000
// }
// },
// "debugLevel": "DEBUG"
// }
import * as spi from 'spi'
import * as gpio from 'gpio'
import SH1106 from './sh1106.js'
var oled_dc = gpio.open({
id: "oled_dc",
success: function () {
console.log('gpio: open oled_dc success')
},
fail: function () {
console.log('gpio: open oled_dc failed')
}
});
var oled_res = gpio.open({
id: "oled_res",
success: function () {
console.log('gpio: open oled_res success')
},
fail: function () {
console.log('gpio: open oled_res failed')
}
});
var oled_spi = spi.open({
id: "oled_spi",
success: function () {
console.log('gpio: open oled_spi success')
},
fail: function () {
console.log('gpio: open oled_spi failed')
}
});
console.log("look here!!!!")
let dispaly = new SH1106(132, 64, oled_spi, oled_dc, oled_res, undefined)
dispaly.open()
while (1) {
dispaly.fill(1)
dispaly.show()
dispaly.fill(0)
dispaly.show()
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/oled.js
|
JavaScript
|
apache-2.0
| 1,525
|
/*
* PWM's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"pwm1": {
"type": "PWM",
"port": 1
},
"timer1": {
"type":"TIMER",
"port": 1
}
},
"debugLevel": "DEBUG"
}
*/
import * as pwm from 'pwm'
import * as timer from 'TIMER'
console.log('pwm: pwm test open ')
var pwm1 = pwm.open({
id: 'pwm1',
success: function() {
console.log('pwm: open pwm success')
},
fail: function() {
console.log('pwm: open pwm failed')
}
});
var timer1 = timer.open({
id: 'timer1'
});
var freq = pwm1.get().freq
var duty = pwm1.get().duty
console.log('pwm: pwm default config freq is ' + freq + ' duty is ' + duty)
console.log('pwm: pwm test start ')
duty = 0;
var cnt = 10;
var loop = 10;
timer1.setInterval(function(){
if (duty >= 100) {
duty = 0;
}
duty = duty + 20;
pwm1.set({
freq: 100,
duty: duty
})
console.log('pwm: pwm test count ' + cnt)
cnt = cnt - 1;
if (cnt == 0) {
pwm1.close();
console.log('pwm: pwm test finish loop ' + loop)
loop--;
if (loop == 0) {
timer1.clearInterval();
}
else {
pwm1 = pwm.open({
id: 'pwm1',
success: function() {
console.log('pwm: open pwm success')
},
fail: function() {
console.log('pwm: open pwm failed')
}
});
}
cnt = 10;
}
}, 1000)
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/pwm.js
|
JavaScript
|
apache-2.0
| 1,453
|
import * as rtc from 'rtc'
rtc.start();
var current_time = rtc.getTime();
console.log('rtc1: current time is ' + current_time);
var my_date = new Date();
my_date.setFullYear(2008,7,9);
console.log('rtc1: time.getYear() ' + my_date.getYear());
console.log('rtc1: time.getMonth() ' + my_date.getMonth());
console.log('rtc1: time.getDate() ' + my_date.getDate());
console.log('rtc1: time.getHours() ' + my_date.getHours());
console.log('rtc1: time.getMinutes() ' + my_date.getMinutes());
console.log('rtc1: time.getSeconds() ' + my_date.getSeconds());
rtc.setTime(my_date);
console.log('Date is ' + my_date.toUTCString());
current_time = rtc.getTime();
console.log('rtc2: current time is ' + current_time);
rtc.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/rtc.js
|
JavaScript
|
apache-2.0
| 725
|
import * as uart from 'uart'
/* Uart's options are configured in app.json.
{
"version": "0.0.1",
"io": {
"serial": {
"type": "UART",
"port": 2,
"dataWidth":8,
"baudRate":115200,
"stopBits":0,
"flowControl":"disable",
"parity":"none"
}
},
"debugLevel": "DEBUG"
}
*/
var msgbuf = 'this is amp uart test'
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
console.log('uart open')
var serial = uart.open({
id: 'serial',
//mode: 'poll', //just for read mode
success: function() {
console.log('open uart success')
},
fail: function() {
console.log('open uart failed')
}
});
console.log('uart write')
serial.write(msgbuf);
sleepMs(1000);
console.log('uart read')
var rCnt = 0;
var rtrn = 0;
var value = ''
//just for read mode
// while(1)
// {
// rtrn = serial.read()
// if(0 != rtrn)
// {
// value += ab2str(rtrn);
// rCnt++;
// }
// if(rCnt > 10)
// {
// break;
// }
// }
// console.log('sensor value is ' + value)
serial.on('data', function(data, len) {
console.log('uart receive data len is : ' + len + ' data is: ' + ab2str(data));
})
//serial.close();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/uart.js
|
JavaScript
|
apache-2.0
| 1,266
|
import * as wdg from 'wdg'
console.log("hello world\n")
wdg.start(2000);
wdg.feed();
wdg.stop();
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/board/haas600/wdg.js
|
JavaScript
|
apache-2.0
| 100
|
import * as netmgr from 'netmgr';
import * as iot from 'iot';
import * as ulog from 'ulog';
var productKey = '*****'; /* 输入你的product key*/
var deviceName = '*****'; /* 输入你的device name */
var deviceSecret = '*****'; /* 输入你的deviceSecret */
var device;
/* set different log level */
/*设置本地日志输出等级为debug*/
ulog.stdloglevel('debug');
/*设置上报到云端的等级为debug*/
ulog.cloudloglevel('debug');
ulog.info('hello HaaS amp ulog!');
var network = netmgr.openNetMgrClient({
name: '/dev/wifi0'
});
network.on('error', function () {
ulog.error('netowrk error ...');
});
network.on('connect', function () {
ulog.info('net connect success');
createDevice();
});
var status;
status = network.getState();
if (status == 'connect') {
/*network is connect */
log.info('network is connected try to connect to aliyun iot platform');
createDevice();
} else {
network.connect({
ssid: '*****', //请替换为自己的热点ssid
password: '****' //请替换为自己热点的密码
});
}
function createDevice() {
device = iot.device({
productKey: productKey,
deviceName: deviceName,
deviceSecret: deviceSecret,
region: 'cn-shanghai',
});
device.on('connect', function () {
ulog.info('iot connect successed start to pop different log level output');
var log_count = 0;
setInterval(function(){
log_count++;
/*输出调试日志*/
ulog.debug('ulog test demo debug log output count ' + log_count);
if (log_count % 2 == 0) {
/*输出信息级别日志*/
ulog.info('ulog test demo info log output count ' + log_count/2);
}
if (log_count % 3 == 0) {
/*输出告警级别日志*/
ulog.warn('ulog test demo warn log output count ' + log_count/3);
}
if (log_count % 4 == 0) {
/*输出错误级别日志*/
ulog.error('ulog test demo error log output count ' + log_count/4);
}
if (log_count % 5 == 0) {
/*输出致命级别日志*/
ulog.fatal('ulog test demo fatal log output count ' + log_count/5);
}
}, 2000);
});
}
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/common/ulog_demo.js
|
JavaScript
|
apache-2.0
| 2,319
|
import * as netmgr from 'netmgr';
import * as oss from 'oss';
console.log('hello amp!');
var network = netmgr.openNetMgrClient({
name: '/dev/wifi0'
});
var status;
status = network.getState();
console.log('status is ' + status);
network.connect({
ssid: 'own_ssid', //请替换为自己的热点ssid
password: 'own_password' //请替换为自己热点的密码
});
network.on('error', function () {
console.log('error ...');
});
var oss_key = '' // 请替换为自己的OSS KEY
var oss_secret = '' // 请替换为自己的OSS secret
var endpoint = '' //请替换为自己 oss endpoint
var bucket_name = '' //请替换为自己 oss bucketname
// 'oss_filename_path' 替换为oss上存放的文件名及路径,比如 test/test.jpg
// 'your_local_file_name' 替换为设备本地路径及文件名,比如 /data/test.jpg
network.on('connect', function () {
console.log('net connect success');
var url = oss.uploadFile(oss_key, oss_secret, endpoint, bucket_name, 'oss_filename_path', 'your_local_file_name');
console.log('upload url: ' + url)
console.log('download begin');
oss.downloadFile(oss_key, oss_secret, endpoint, bucket_name, 'oss_filename_path', 'your_local_file_name');
console.log('oss download success ')
});
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/network/oss.js
|
JavaScript
|
apache-2.0
| 1,266
|
import * as netmgr from 'netmgr';
console.log('hello amp!');
var network = netmgr.openNetMgrClient({
name: '/dev/wifi0'
});
var status;
status = network.getState();
console.log('status is ' + status);
network.connect({
ssid: 'own_ssid', //请替换为自己的热点ssid
password: 'own_password' //请替换为自己热点的密码
});
network.on('error', function () {
console.log('error ...');
});
network.on('connect', function () {
console.log('net connect success');
});
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/network/wifi.js
|
JavaScript
|
apache-2.0
| 504
|
var appota = require('appota');
var iot = require('iot');
/* device info */
var productKey = ''; /* your productKey */
var deviceName = ''; /* your deviceName */
var deviceSecret = ''; /* your deviceSecret */
var module_name = 'default';
var default_ver = '1.0.0';
var ota;
var status;
/* download info */
var info = {
url: '',
store_path: '/data/jsamp/pack.bin',
install_path: '/data/jsamp/',
length: 0,
hashType: '',
hash: ''
}
var device = iot.device({
productKey: productKey,
deviceName: deviceName,
deviceSecret: deviceSecret
});
device.on('connect', function(iot_res) {
console.log('device connected');
var iotDeviceHandle = device.getDeviceHandle();
ota = appota.open(iotDeviceHandle);
console.log('report default module ver');
ota.report({
device_handle: iotDeviceHandle,
product_key: productKey,
device_name: deviceName,
module_name: module_name,
version: default_ver
});
ota.on('new', function(res) {
console.log('length is ' + res.length);
console.log('module_name is ' + res.module_name);
console.log('version is ' + res.version);
console.log('url is ' + res.url);
console.log('hash is ' + res.hash);
console.log('hash_type is ' + res.hash_type);
info.url = res.url;
info.length = res.length;
info.module_name = res.module_name;
info.version = res.version;
info.hash = res.hash;
info.hashType = res.hash_type;
ota.download({
url: info.url,
store_path: info.store_path
}, function(res) {
if (res >= 0) {
console.log('download success');
console.log('verify start');
console.log(info.hashType);
ota.verify({
length: info.length,
hash_type: info.hashType,
hash: info.hash,
store_path: info.store_path
}, function(res) {
if (res >= 0) {
console.log('verify success');
console.log('upgrade start');
ota.upgrade({
length: info.length,
store_path: info.store_path,
install_path: info.install_path
}, function(res) {
if (res >= 0) {
console.log('upgrade success')
} else {
console.log('upgrade failed')
}
})
} else {
console.log('verify failed');
}
})
} else {
console.log('download failed');
}
});
});
})
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/ota_demo/ota_4g.js
|
JavaScript
|
apache-2.0
| 2,258
|
import * as netmgr from 'netmgr';
import * as iot from 'iot';
import * as appota from 'appota'
//此脚本包含了wifi连网功能,仅适合haas100、haaseduk1
var productKey = ''; /* your productKey */
var deviceName = ''; /* your deviceName */
var deviceSecret = ''; /* your deviceSecret */
var device;
var module_name = 'default';
var default_ver = '0.0.1';
var ota;
var status;
/* download info */
var info = {
url: '',
store_path: '/data/jsamp/pack.bin',
install_path: '/data/jsamp/',
length: 0,
hashType: '',
hash: ''
}
function createDevice() {
device = iot.device({
productKey: productKey,
deviceName: deviceName,
deviceSecret: deviceSecret,
region: 'cn-shanghai',
});
device.on('connect', function () {
console.log('(re)connected');
var iotDeviceHandle = device.getDeviceHandle();
console.log('get device handle module');
ota = appota.open(iotDeviceHandle);
console.log('report default module ver');
ota.report({
device_handle: iotDeviceHandle,
product_key: productKey,
device_name: deviceName,
module_name: module_name,
version: default_ver
});
ota.on('new', function(res) {
console.log('length is ' + res.length);
console.log('module_name is ' + res.module_name);
console.log('version is ' + res.version);
console.log('url is ' + res.url);
console.log('hash is ' + res.hash);
console.log('hash_type is ' + res.hash_type);
info.url = res.url;
info.length = res.length;
info.module_name = res.module_name;
info.version = res.version;
info.hash = res.hash;
info.hashType = res.hash_type;
ota.download({
url: info.url,
store_path: info.store_path
}, function(res) {
if (res >= 0) {
console.log('download success');
console.log('verify start');
console.log(info.hashType);
ota.verify({
length: info.length,
hash_type: info.hashType,
hash: info.hash,
store_path: info.store_path
}, function(res) {
if (res >= 0) {
console.log('verify success');
console.log('upgrade start');
ota.upgrade({
length: info.length,
store_path: info.store_path,
install_path: info.install_path
}, function(res) {
if (res >= 0) {
console.log('upgrade success')
} else {
console.log('upgrade failed')
}
})
} else {
console.log('verify failed');
}
})
} else {
console.log('download failed');
}
});
});
});
}
var network = netmgr.openNetMgrClient({
name: '/dev/wifi0'
});
var status;
status = network.getState();
console.log('status is ' + status);
network.connect({
ssid: '', //请替换为自己的热点ssid
password: '' //请替换为自己热点的密码
});
network.on('error', function () {
console.log('error ...');
});
network.on('connect', function () {
createDevice();
});
|
YifuLiu/AliOS-Things
|
solutions/javascript_demo/ota_demo/ota_wifi.js
|
JavaScript
|
apache-2.0
| 2,901
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
MK_GENERATED_IMGS_PATH:=generated
PRODUCT_BIN:=product
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo ucloud ai demo build Done
@echo [INFO] Create bin files
# $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -i $(MK_GENERATED_IMGS_PATH)/data -l -p
# $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -e $(MK_GENERATED_IMGS_PATH) -x
.PHONY:flash
flash:
$(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -w prim
.PHONY:flashall
flashall:
$(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -a
sdk:
$(CPRE) haas sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
$(CPRE) find . -name "*.[od]" -delete
$(CPRE) rm yoc_sdk yoc.* generated out -rf
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/Makefile
|
Makefile
|
apache-2.0
| 882
|
#! /bin/env python
from aostools import Make
# defconfig = Make(elf='yoc.elf', objcopy='generated/data/prim', objdump='yoc.asm')
defconfig = Make(elf='aos.elf', objcopy='binary/kws_demo@haas100.bin')
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/SConstruct
|
Python
|
apache-2.0
| 253
|
#!/usr/bin/env python3
import os
import sys
import getpass
import shutil
#!/usr/bin/env python3
import os
import sys
import getpass
import shutil
comp_path = sys.path[0]
print("comp_path:")
print(comp_path)
# original folder
src_mp3_path = comp_path + "/resources/mp3"
# new folder
data_path = comp_path + "/../../hardware/chip/haas1000/prebuild/data/data"
mp3_dst_path = data_path + "/mp3"
# delete prebuild/data resources
if os.path.exists(mp3_dst_path):
print ('Delete /data/mp3 firstly')
shutil.rmtree(mp3_dst_path)
# copy resources
shutil.copytree(src_mp3_path, mp3_dst_path)
# result
print("run external script success")
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/cp_resources.py
|
Python
|
apache-2.0
| 644
|
#include "kws.h"
#include "ulog/ulog.h"
#include "aiagent_service.h"
#include "aiagent_common.h"
#if (BOARD_HAAS100 == 1)
#include "led.h"
#endif
#include "uvoice_init.h"
#include "uvoice_types.h"
#include "uvoice_event.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#define TAG "kws"
static os_task_t play_task;
static uvoice_player_t *uvocplayer;
static char text_source[256];
static int source_sample_rate;
static int source_channels;
static int get_format_from_name(char *name, media_format_t *format)
{
if (!name || !format) {
LOGE(TAG, "arg null !\n");
return -1;
}
if (strstr(name, ".mp3") || strstr(name, ".MP3"))
*format = MEDIA_FMT_MP3;
else if (strstr(name, ".wav") || strstr(name, ".WAV"))
*format = MEDIA_FMT_WAV;
else if (strstr(name, ".aac") || strstr(name, ".AAC"))
*format = MEDIA_FMT_AAC;
else if (strstr(name, ".m4a") || strstr(name, ".M4A"))
*format = MEDIA_FMT_M4A;
else if (strstr(name, ".pcm") || strstr(name, ".PCM"))
*format = MEDIA_FMT_PCM;
else if (strstr(name, ".spx") || strstr(name, ".SPX"))
*format = MEDIA_FMT_SPX;
else if (strstr(name, ".ogg") || strstr(name, ".OGG"))
*format = MEDIA_FMT_OGG;
else if (strstr(name, ".amrwb") || strstr(name, ".AMRWB"))
*format = MEDIA_FMT_AMRWB;
else if (strstr(name, ".amr") || strstr(name, ".AMR"))
*format = MEDIA_FMT_AMR;
else if (strstr(name, ".opus") || strstr(name, ".OPUS"))
*format = MEDIA_FMT_OPS;
else if (strstr(name, ".flac") || strstr(name, ".FLAC"))
*format = MEDIA_FMT_FLAC;
return 0;
}
static void *play_music(void *arg)
{
media_format_t format = MEDIA_FMT_UNKNOWN;
get_format_from_name(text_source, &format);
if (uvocplayer->set_source(text_source)) {
LOGE(TAG, "set source failed !\n");
return NULL;
}
if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX)
uvocplayer->set_pcminfo(source_sample_rate, source_channels, 16, 1280);
if (uvocplayer->start()) {
LOGE(TAG, "start failed !\n");
uvocplayer->clr_source();
}
return NULL;
}
static int32_t play_local_mp3(void)
{
int32_t random;
random = rand() % 240;
LOG("random: %d\n", random);
memset(text_source, 0, sizeof(text_source));
if (random < 100) {
strcpy(text_source, "fs:/data/mp3/haas_intro.mp3");
} else if (random > 100 && random < 150) {
strcpy(text_source, "fs:/data/mp3/haasxiaozhushou.mp3");
} else if (random > 150 && random < 200) {
strcpy(text_source, "fs:/data/mp3/zhurenwozai.mp3");
} else {
strcpy(text_source, "fs:/data/mp3/eiwozai.mp3");
}
os_task_create(&play_task,
"play music task", play_music,
NULL, 8192, 0);
return 0;
}
static int32_t kws_callback(ai_result_t *result)
{
int32_t kws_ret = (int32_t)*result;
player_state_t player_state = -1;
if (kws_ret) {
led_switch(1, LED_ON);
aos_msleep(200);
led_switch(2, LED_ON);
aos_msleep(200);
led_switch(3, LED_ON);
aos_msleep(200);
led_switch(4, LED_ON);
aos_msleep(200);
led_switch(5, LED_ON);
aos_msleep(200);
led_switch(6, LED_ON);
/*play local tts*/
play_local_mp3();
uvocplayer->wait_complete();
led_switch(1, LED_OFF);
led_switch(2, LED_OFF);
led_switch(3, LED_OFF);
led_switch(4, LED_OFF);
led_switch(5, LED_OFF);
led_switch(6, LED_OFF);
}
return 0;
}
int32_t kws_init(void)
{
int32_t ret;
ai_config_t config;
ret = aiagent_service_init("kws", AI_MODEL_KWS);
if (ret < 0) {
LOGE(TAG, "aiagent_service_init failed");
return -1;
}
config.channel = 2;
aiagent_service_config(&config);
/*Init sound driver*/
audio_install_codec_driver();
/*Init uvoice to play mp3*/
uvoice_init();
/*create uvoice player*/
uvocplayer = uvoice_player_create();
if (!uvocplayer) {
LOGE(TAG, "create media player failed !\n");
return;
}
uvocplayer->eq_enable(0);
/*set play volume*/
uvocplayer->set_volume(10);
return aiagent_service_model_infer(NULL, NULL, kws_callback);
}
int32_t kws_uninit(void)
{
aiagent_service_uninit();
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/kws.c
|
C
|
apache-2.0
| 4,412
|
#ifndef __KWS_H__
#define __KWS_H__
#include <stdint.h>
#include <stdio.h>
extern int audio_install_codec_driver();
int32_t kws_init(void);
int32_t kws_uninit(void);
#endif
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/kws.h
|
C
|
apache-2.0
| 177
|
/*
* Copyright (c) 2014-2016 Alibaba Group. All rights reserved.
* License-Identifier: Apache-2.0
*
* 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.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "aos/kernel.h"
#include "ulog/ulog.h"
#include "kws.h"
int application_start(int argc, char **argv)
{
aos_set_log_level(AOS_LL_DEBUG);
kws_init();
while (1) {
aos_msleep(1000);
};
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/main.c
|
C
|
apache-2.0
| 980
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_network_init(void);
extern void board_kinit_init(kinit_t *init_args);
extern void board_flash_init(void);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
board_flash_init();
/*FOR STM32F429 delete hal_i2c_pre_init \I2C1_init\CAN_init here*/
}
void aos_maintask(void *arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/kws_demo/maintask.c
|
C
|
apache-2.0
| 1,362
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) -j4
@echo AOS SDK Done
sdk:
$(CPRE) aos sdk
.PHONY:clean
clean:
$(CPRE) scons -c
ifeq ($(OS), Windows_NT)
$(CPRE) if exist aos_sdk rmdir /s /q aos_sdk
$(CPRE) if exist binary rmdir /s /q binary
$(CPRE) if exist out rmdir /s /q out
$(CPRE) if exist aos.elf del /f /q aos.elf
$(CPRE) if exist aos.map del /f /q aos.map
else
$(CPRE) rm -rf aos_sdk binary out aos.elf aos.map
endif
|
YifuLiu/AliOS-Things
|
solutions/linkkit_genie_demo/Makefile
|
Makefile
|
apache-2.0
| 557
|
#! /bin/env python
from aostools import Make
# default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin
# defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin')
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/linkkit_genie_demo/SConstruct
|
Python
|
apache-2.0
| 303
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include "aos/init.h"
#include "board.h"
#include <aos/errno.h>
#include <aos/kernel.h>
#include <k_api.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "netmgr.h"
#include "linkkit/wifi_provision_api.h"
#include "linkkit/infra/infra_types.h"
#include "linkkit/infra/infra_defs.h"
#include "linkkit/infra/infra_compat.h"
#include "linkkit/dev_model_api.h"
#include "linkkit/infra/infra_config.h"
#include "linkkit/wrappers/wrappers.h"
#include "cJSON.h"
#include "aos/gpioc.h"
/**
* These PRODUCT_KEY|PRODUCT_SECRET|DEVICE_NAME|DEVICE_SECRET are listed for demo only
*
* When you created your own devices on iot.console.com, you SHOULD replace them with what you got from console
*
*/
#define PRODUCT_KEY "xx"
#define PRODUCT_SECRET "xx"
#define DEVICE_NAME "xx"
#define DEVICE_SECRET "xx"
// kv keys of Wi-Fi SSID/Password
#define WIFI_SSID_KV_KEY "wifi_ssid"
#define WIFI_PASSWORD_KV_KEY "wifi_password"
#define EXAMPLE_TRACE(...) \
do { \
HAL_Printf("\033[1;32;40m%s.%d: ", __func__, __LINE__); \
HAL_Printf(__VA_ARGS__); \
HAL_Printf("\033[0m\r\n"); \
} while (0)
#define EXAMPLE_MASTER_DEVID (0)
#define EXAMPLE_YIELD_TIMEOUT_MS (200)
// HaaS200's GPIO named with PA_28 is connected to the Red LED
#define LED_PIN 28
typedef struct {
int master_devid;
int cloud_connected;
int master_initialized;
} user_example_ctx_t;
static user_example_ctx_t g_user_example_ctx;
static aos_gpioc_ref_t gpioc;
static led_state = 0;
// control LED's on/off
int led_ctrl(unsigned int on)
{
// output 0 to turn on the LED, while output 1 to turn off the LED
return aos_gpioc_set_value(&gpioc, LED_PIN, on ? 0 : 1);
}
// initialize the GPIO, which is connected with LED
int led_init(void)
{
int ret = -1;
unsigned int mode;
memset(&gpioc, 0, sizeof(gpioc));
// get GPIO controller's reference
ret = aos_gpioc_get(&gpioc, 0);
if (ret) {
EXAMPLE_TRACE("GPIO_HAL", "get gpioc failed, gpioc_index = %d, ret = %d;\n", LED_PIN, ret);
return ret;
}
// set LED_PIN into output mode
mode = AOS_GPIO_DIR_OUTPUT;
mode |= AOS_GPIO_OUTPUT_CFG_PP;
mode |= AOS_GPIO_OUTPUT_INIT_HIGH;
ret = aos_gpioc_set_mode(&gpioc, LED_PIN, mode);
if (ret) {
EXAMPLE_TRACE("GPIO_HAL", "%s: set gpio mode failed, %d\n", __func__, ret);
aos_gpioc_put(&gpioc);
return ret;
}
EXAMPLE_TRACE("GPIO_HAL", "%s: set gpio mode succeed\n", __func__);
return ret;
}
/** cloud connected event callback */
static int user_connected_event_handler(void)
{
EXAMPLE_TRACE("Cloud Connected");
g_user_example_ctx.cloud_connected = 1;
return 0;
}
/** cloud disconnected event callback */
static int user_disconnected_event_handler(void)
{
EXAMPLE_TRACE("Cloud Disconnected");
g_user_example_ctx.cloud_connected = 0;
return 0;
}
/* device initialized event callback */
static int user_initialized(const int devid)
{
EXAMPLE_TRACE("Device Initialized");
g_user_example_ctx.master_initialized = 1;
return 0;
}
/** recv property post response message from cloud **/
static int user_report_reply_event_handler(const int devid, const int msgid, const int code, const char *reply,
const int reply_len)
{
EXAMPLE_TRACE("Message Post Reply Received, Message ID: %d, Code: %d, Reply: %.*s", msgid, code,
reply_len,
(reply == NULL) ? ("NULL") : (reply));
return 0;
}
/** recv event post response message from cloud **/
static int user_trigger_event_reply_event_handler(const int devid, const int msgid, const int code, const char *eventid,
const int eventid_len, const char *message, const int message_len)
{
EXAMPLE_TRACE("Trigger Event Reply Received, Message ID: %d, Code: %d, EventID: %.*s, Message: %.*s",
msgid, code,
eventid_len,
eventid, message_len, message);
return 0;
}
/** recv property set command from cloud **/
static int user_property_set_event_handler(const int devid, const char *request, const int request_len)
{
int res = 0;
cJSON *root = NULL, *power_state = NULL;
EXAMPLE_TRACE("Property Set Received, Request: %s", request);
/* parse json string */
root = cJSON_Parse(request);
if (root == NULL || !cJSON_IsObject(root)) {
EXAMPLE_TRACE("JSON Parse Error");
return -1;
}
/* check whether powerstate control command exist or not */
power_state = cJSON_GetObjectItem(root, "powerstate");
if (power_state == NULL)
goto out;
EXAMPLE_TRACE("powerstate = %d", power_state->valueint);
if (power_state->valueint)
led_state = 1;
else
led_state = 0;
// turn on/off the LED according to the command from cloud
EXAMPLE_TRACE("turn %s the LED", led_state ? "on" : "off");
led_ctrl(led_state);
// post device's property back to the cloud
user_post_property();
out:
cJSON_Delete(root);
return 0;
}
/** recv service request from cloud **/
static int user_service_request_event_handler(const int devid, const char *serviceid, const int serviceid_len,
const char *request, const int request_len,
char **response, int *response_len)
{
int add_result = 0;
int ret = -1;
cJSON *root = NULL, *item_number_a = NULL, *item_number_b = NULL;
const char *response_fmt = "{\"Result\": %d}";
EXAMPLE_TRACE("Service Request Received, Service ID: %.*s, Payload: %s", serviceid_len, serviceid, request);
/* Parse Root */
root = cJSON_Parse(request);
if (root == NULL || !cJSON_IsObject(root)) {
EXAMPLE_TRACE("JSON Parse Error");
return -1;
}
do {
if (strlen("Operation_Service") == serviceid_len && memcmp("Operation_Service", serviceid, serviceid_len) == 0) {
/* Parse NumberA */
item_number_a = cJSON_GetObjectItem(root, "NumberA");
if (item_number_a == NULL || !cJSON_IsNumber(item_number_a))
break;
EXAMPLE_TRACE("NumberA = %d", item_number_a->valueint);
/* Parse NumberB */
item_number_b = cJSON_GetObjectItem(root, "NumberB");
if (item_number_b == NULL || !cJSON_IsNumber(item_number_b))
break;
EXAMPLE_TRACE("NumberB = %d", item_number_b->valueint);
add_result = item_number_a->valueint + item_number_b->valueint;
ret = 0;
/* Send Service Response To Cloud */
}
} while (0);
*response_len = strlen(response_fmt) + 10 + 1;
*response = (char *)HAL_Malloc(*response_len);
if (*response != NULL) {
memset(*response, 0, *response_len);
HAL_Snprintf(*response, *response_len, response_fmt, add_result);
*response_len = strlen(*response);
}
cJSON_Delete(root);
return ret;
}
static int user_timestamp_reply_event_handler(const char *timestamp)
{
EXAMPLE_TRACE("Current Timestamp: %s", timestamp);
return 0;
}
/** fota event handler **/
static int user_fota_event_handler(int type, const char *version)
{
char buffer[128] = {0};
int buffer_length = 128;
/* 0 - new firmware exist, query the new firmware */
if (type == 0) {
EXAMPLE_TRACE("New Firmware Version: %s", version);
IOT_Linkkit_Query(EXAMPLE_MASTER_DEVID, ITM_MSG_QUERY_FOTA_DATA, (unsigned char *)buffer, buffer_length);
}
return 0;
}
/* cota event handler */
static int user_cota_event_handler(int type, const char *config_id, int config_size, const char *get_type,
const char *sign, const char *sign_method, const char *url)
{
char buffer[128] = {0};
int buffer_length = 128;
/* type = 0, new config exist, query the new config */
if (type == 0) {
EXAMPLE_TRACE("New Config ID: %s", config_id);
EXAMPLE_TRACE("New Config Size: %d", config_size);
EXAMPLE_TRACE("New Config Type: %s", get_type);
EXAMPLE_TRACE("New Config Sign: %s", sign);
EXAMPLE_TRACE("New Config Sign Method: %s", sign_method);
EXAMPLE_TRACE("New Config URL: %s", url);
IOT_Linkkit_Query(EXAMPLE_MASTER_DEVID, ITM_MSG_QUERY_COTA_DATA, (unsigned char *)buffer, buffer_length);
}
return 0;
}
// report device's property to the cloud
void user_post_property(void)
{
int res = 0;
char property_payload[30] = {0};
HAL_Snprintf(property_payload, sizeof(property_payload), "{\"powerstate\": %d}", led_state);
res = IOT_Linkkit_Report(EXAMPLE_MASTER_DEVID, ITM_MSG_POST_PROPERTY,
(unsigned char *)property_payload, strlen(property_payload));
EXAMPLE_TRACE("Post Property Message ID: %d", res);
}
void user_deviceinfo_update(void)
{
int res = 0;
char *device_info_update = "[{\"attrKey\":\"abc\",\"attrValue\":\"hello,world\"}]";
res = IOT_Linkkit_Report(EXAMPLE_MASTER_DEVID, ITM_MSG_DEVICEINFO_UPDATE,
(unsigned char *)device_info_update, strlen(device_info_update));
EXAMPLE_TRACE("Device Info Update Message ID: %d", res);
}
void user_deviceinfo_delete(void)
{
int res = 0;
char *device_info_delete = "[{\"attrKey\":\"abc\"}]";
res = IOT_Linkkit_Report(EXAMPLE_MASTER_DEVID, ITM_MSG_DEVICEINFO_DELETE,
(unsigned char *)device_info_delete, strlen(device_info_delete));
EXAMPLE_TRACE("Device Info Delete Message ID: %d", res);
}
static int user_cloud_error_handler(const int code, const char *data, const char *detail)
{
EXAMPLE_TRACE("code =%d ,data=%s, detail=%s", code, data, detail);
return 0;
}
// make sure device's signature is correct
static void set_iot_device_info(void)
{
char _device_secret[IOTX_DEVICE_SECRET_LEN + 1] = {0};
HAL_GetDeviceSecret(_device_secret);
// if device secret does not exist, store pk/ps/dn/ds into kv system
if (!strlen(_device_secret)) {
HAL_SetProductKey(PRODUCT_KEY);
HAL_SetProductSecret(PRODUCT_SECRET);
HAL_SetDeviceName(DEVICE_NAME);
HAL_SetDeviceSecret(DEVICE_SECRET);
}
return;
}
int linkkit_main(void)
{
int res = 0;
int cnt = 0;
int auto_quit = 0;
iotx_linkkit_dev_meta_info_t master_meta_info;
int domain_type = 0, dynamic_register = 0, post_reply_need = 0, fota_timeout = 30;
memset(&g_user_example_ctx, 0, sizeof(user_example_ctx_t));
memset(&master_meta_info, 0, sizeof(iotx_linkkit_dev_meta_info_t));
HAL_GetProductKey(master_meta_info.product_key);
HAL_GetDeviceName(master_meta_info.device_name);
HAL_GetProductSecret(master_meta_info.product_secret);
HAL_GetDeviceSecret(master_meta_info.device_secret);
IOT_SetLogLevel(IOT_LOG_DEBUG);
/* Register Callback */
IOT_RegisterCallback(ITE_CONNECT_SUCC, user_connected_event_handler);
IOT_RegisterCallback(ITE_DISCONNECTED, user_disconnected_event_handler);
IOT_RegisterCallback(ITE_SERVICE_REQUEST, user_service_request_event_handler);
IOT_RegisterCallback(ITE_PROPERTY_SET, user_property_set_event_handler);
IOT_RegisterCallback(ITE_REPORT_REPLY, user_report_reply_event_handler);
IOT_RegisterCallback(ITE_TRIGGER_EVENT_REPLY, user_trigger_event_reply_event_handler);
IOT_RegisterCallback(ITE_TIMESTAMP_REPLY, user_timestamp_reply_event_handler);
IOT_RegisterCallback(ITE_INITIALIZE_COMPLETED, user_initialized);
IOT_RegisterCallback(ITE_FOTA, user_fota_event_handler);
IOT_RegisterCallback(ITE_COTA, user_cota_event_handler);
IOT_RegisterCallback(ITE_CLOUD_ERROR, user_cloud_error_handler);
domain_type = IOTX_CLOUD_REGION_SHANGHAI;
IOT_Ioctl(IOTX_IOCTL_SET_DOMAIN, (void *)&domain_type);
/* Choose Login Method */
dynamic_register = 0;
IOT_Ioctl(IOTX_IOCTL_SET_DYNAMIC_REGISTER, (void *)&dynamic_register);
/* post reply doesn't need */
post_reply_need = 1;
IOT_Ioctl(IOTX_IOCTL_RECV_EVENT_REPLY, (void *)&post_reply_need);
IOT_Ioctl(IOTX_IOCTL_FOTA_TIMEOUT_MS, (void *)&fota_timeout);
#if defined(USE_ITLS)
{
char url[128] = {0};
int port = 1883;
snprintf(url, 128, "%s.itls.cn-shanghai.aliyuncs.com", master_meta_info.product_key);
IOT_Ioctl(IOTX_IOCTL_SET_MQTT_DOMAIN, (void *)url);
IOT_Ioctl(IOTX_IOCTL_SET_CUSTOMIZE_INFO, (void *)"authtype=id2");
IOT_Ioctl(IOTX_IOCTL_SET_MQTT_PORT, &port);
}
#endif
/* Create Master Device Resources */
do {
g_user_example_ctx.master_devid = IOT_Linkkit_Open(IOTX_LINKKIT_DEV_TYPE_MASTER, &master_meta_info);
if (g_user_example_ctx.master_devid >= 0) {
break;
}
EXAMPLE_TRACE("IOT_Linkkit_Open failed! retry after %d ms\n", 2000);
HAL_SleepMs(2000);
} while (1);
/* Start Connect Aliyun Server */
do {
res = IOT_Linkkit_Connect(g_user_example_ctx.master_devid);
if (res >= 0) {
break;
}
EXAMPLE_TRACE("IOT_Linkkit_Connect failed! retry after %d ms\n", 5000);
HAL_SleepMs(5000);
} while (1);
while (1) {
IOT_Linkkit_Yield(EXAMPLE_YIELD_TIMEOUT_MS);
/* Post Proprety Example */
if ((cnt % 20) == 0) {
user_post_property();
}
cnt++;
if (auto_quit == 1 && cnt > 3600) {
break;
}
}
IOT_Linkkit_Close(g_user_example_ctx.master_devid);
IOT_DumpMemoryStats(IOT_LOG_DEBUG);
return 0;
}
int application_start(int argc, char *argv[])
{
int len = 0;
int ret = 0;
int count = 0;
char ssid[32 + 1] = {0};
char password[64 + 1] = {0};
EXAMPLE_TRACE("nano entry here!\r\n");
/* LED GPIO initialization */
ret = led_init();
if (ret) {
EXAMPLE_TRACE("led init done, ret:%d\r\n", ret);
}
set_iot_device_info();
/*
check whether SSID/Password are configured or not
*/
len = sizeof(ssid);
ret = aos_kv_get(WIFI_SSID_KV_KEY, ssid, &len);
if (ret) {
EXAMPLE_TRACE("aos_kv_get %s ret:%d\r\n", WIFI_SSID_KV_KEY, ret);
goto zero_config;
}
len = sizeof(password);
ret = aos_kv_get(WIFI_PASSWORD_KV_KEY, password, &len);
if (ret) {
EXAMPLE_TRACE("aos_kv_get %s ret:%d\r\n", WIFI_PASSWORD_KV_KEY, ret);
goto zero_config;
}
/*
connect to Wi-Fi
*/
netmgr_comp_enable(ssid, password, 0);
goto linkkit_start;
zero_config:
awss_config_press();
awss_start();
linkkit_start:
linkkit_main();
while (1) {
EXAMPLE_TRACE("hello genie intelligent light! count %d \r\n", count++);
aos_msleep(10000);
};
}
|
YifuLiu/AliOS-Things
|
solutions/linkkit_genie_demo/genie_demo.c
|
C
|
apache-2.0
| 14,946
|
/* user space */
#ifndef RHINO_CONFIG_USER_SPACE
#define RHINO_CONFIG_USER_SPACE 0
#endif
|
YifuLiu/AliOS-Things
|
solutions/linkkit_genie_demo/k_app_config.h
|
C
|
apache-2.0
| 106
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t *init_args);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void *arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/linkkit_genie_demo/maintask.c
|
C
|
apache-2.0
| 1,192
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo AOS SDK Done
sdk:
$(CPRE) aos sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
ifeq ($(OS), Windows_NT)
$(CPRE) if exist aos_sdk rmdir /s /q aos_sdk
$(CPRE) if exist binary rmdir /s /q binary
$(CPRE) if exist out rmdir /s /q out
$(CPRE) if exist aos.elf del /f /q aos.elf
$(CPRE) if exist aos.map del /f /q aos.map
else
$(CPRE) rm -rf aos_sdk binary out aos.elf aos.map
endif
|
YifuLiu/AliOS-Things
|
solutions/linksdk_demo/Makefile
|
Makefile
|
apache-2.0
| 599
|
#! /bin/env python
from aostools import Make
# default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin
# defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin')
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/linksdk_demo/SConstruct
|
Python
|
apache-2.0
| 303
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
* If board have no component for example board_xx_init, it indicates that this
* app does not support this board.
* Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t *init_args);
/*
* For user config
* kinit.argc = 0;
* kinit.argv = NULL;
* kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/*
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void *arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#if !defined(AOS_BINS) && !defined(AOS_SEPARATE_APP)
application_start(kinit.argc, kinit.argv);
#else
#include "dm_app.h"
printf("%s-%s\r\n", __DATE__, __TIME__);
dm_app_load("/data/app/separate_app");
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_demo/maintask.c
|
C
|
apache-2.0
| 1,324
|
/*
* 这个例程演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程
*
* + 一个线程用于保活长连接
* + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调
*
* 接着演示了在MQTT连接上进行属性上报, 事件上报, 以及处理收到的属性设置, 服务调用, 取消这些代码段落的注释即可观察运行效果
*
* 需要用户关注或修改的部分, 已经用 TODO 在注释中标明
*
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <aos/kernel.h>
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_dm_api.h"
/* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
/* 位于external/ali_ca_cert.c中的服务器证书 */
extern const char *ali_ca_cert;
static uint8_t g_mqtt_process_thread_running = 0;
static uint8_t g_mqtt_recv_thread_running = 0;
/* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
*
* 例如: [1577589489.033][LK-0317] mqtt_basic_demo&a13FN5TplKq
*
* 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h
*
*/
/* 日志回调函数, SDK的日志会从这里输出 */
int32_t demo_state_logcb(int32_t code, char *message)
{
printf("%s", message);
return 0;
}
/* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
{
switch (event->type) {
/* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
case AIOT_MQTTEVT_CONNECT: {
printf("AIOT_MQTTEVT_CONNECT\n");
}
break;
/* SDK因为网络状况被动断连后, 自动发起重连已成功 */
case AIOT_MQTTEVT_RECONNECT: {
printf("AIOT_MQTTEVT_RECONNECT\n");
}
break;
/* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
case AIOT_MQTTEVT_DISCONNECT: {
char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
("heartbeat disconnect");
printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause);
}
break;
default: {
}
}
}
/* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
void *demo_mqtt_process_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (g_mqtt_process_thread_running) {
res = aiot_mqtt_process(args);
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
return NULL;
}
/* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
void *demo_mqtt_recv_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (g_mqtt_recv_thread_running) {
res = aiot_mqtt_recv(args);
if (res < STATE_SUCCESS) {
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
}
return NULL;
}
/* 用户数据接收处理回调函数 */
static void demo_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
printf("demo_dm_recv_handler, type = %d\r\n", recv->type);
switch (recv->type) {
/* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */
case AIOT_DMRECV_GENERIC_REPLY: {
printf("msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n",
recv->data.generic_reply.msg_id,
recv->data.generic_reply.code,
recv->data.generic_reply.data_len,
recv->data.generic_reply.data,
recv->data.generic_reply.message_len,
recv->data.generic_reply.message);
}
break;
/* 属性设置 */
case AIOT_DMRECV_PROPERTY_SET: {
printf("msg_id = %ld, params = %.*s\r\n",
(unsigned long)recv->data.property_set.msg_id,
recv->data.property_set.params_len,
recv->data.property_set.params);
/* TODO: 以下代码演示如何对来自云平台的属性设置指令进行应答, 用户可取消注释查看演示效果 */
/*
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_PROPERTY_SET_REPLY;
msg.data.property_set_reply.msg_id = recv->data.property_set.msg_id;
msg.data.property_set_reply.code = 200;
msg.data.property_set_reply.data = "{}";
int32_t res = aiot_dm_send(dm_handle, &msg);
if (res < 0) {
printf("aiot_dm_send failed\r\n");
}
}
*/
}
break;
/* 异步服务调用 */
case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: {
printf("msg_id = %ld, service_id = %s, params = %.*s\r\n",
(unsigned long)recv->data.async_service_invoke.msg_id,
recv->data.async_service_invoke.service_id,
recv->data.async_service_invoke.params_len,
recv->data.async_service_invoke.params);
/* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答, 用户可取消注释查看演示效果
*
* 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到
*/
/*
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY;
msg.data.async_service_reply.msg_id = recv->data.async_service_invoke.msg_id;
msg.data.async_service_reply.code = 200;
msg.data.async_service_reply.service_id = "ToggleLightSwitch";
msg.data.async_service_reply.data = "{\"dataA\": 20}";
int32_t res = aiot_dm_send(dm_handle, &msg);
if (res < 0) {
printf("aiot_dm_send failed\r\n");
}
}
*/
}
break;
/* 同步服务调用 */
case AIOT_DMRECV_SYNC_SERVICE_INVOKE: {
printf("msg_id = %ld, rrpc_id = %s, service_id = %s, params = %.*s\r\n",
(unsigned long)recv->data.sync_service_invoke.msg_id,
recv->data.sync_service_invoke.rrpc_id,
recv->data.sync_service_invoke.service_id,
recv->data.sync_service_invoke.params_len,
recv->data.sync_service_invoke.params);
/* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答, 用户可取消注释查看演示效果
*
* 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id和rrpc_id字符串, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到
*/
/*
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY;
msg.data.sync_service_reply.rrpc_id = recv->data.sync_service_invoke.rrpc_id;
msg.data.sync_service_reply.msg_id = recv->data.sync_service_invoke.msg_id;
msg.data.sync_service_reply.code = 200;
msg.data.sync_service_reply.service_id = "SetLightSwitchTimer";
msg.data.sync_service_reply.data = "{}";
int32_t res = aiot_dm_send(dm_handle, &msg);
if (res < 0) {
printf("aiot_dm_send failed\r\n");
}
}
*/
}
break;
/* 下行二进制数据 */
case AIOT_DMRECV_RAW_DATA: {
printf("raw data len = %d\r\n", recv->data.raw_data.data_len);
/* TODO: 以下代码演示如何发送二进制格式数据, 若使用需要有相应的数据透传脚本部署在云端 */
/*
{
aiot_dm_msg_t msg;
uint8_t raw_data[] = {0x01, 0x02};
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_RAW_DATA;
msg.data.raw_data.data = raw_data;
msg.data.raw_data.data_len = sizeof(raw_data);
aiot_dm_send(dm_handle, &msg);
}
*/
}
break;
/* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */
case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE: {
printf("raw sync service rrpc_id = %s, data_len = %d\r\n",
recv->data.raw_service_invoke.rrpc_id,
recv->data.raw_service_invoke.data_len);
}
break;
default:
break;
}
}
/* 属性上报函数演示 */
int32_t demo_send_property_post(void *dm_handle, char *params)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_PROPERTY_POST;
msg.data.property_post.params = params;
return aiot_dm_send(dm_handle, &msg);
}
/* 事件上报函数演示 */
int32_t demo_send_event_post(void *dm_handle, char *event_id, char *params)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_EVENT_POST;
msg.data.event_post.event_id = event_id;
msg.data.event_post.params = params;
return aiot_dm_send(dm_handle, &msg);
}
/* 演示了获取属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */
int32_t demo_send_get_desred_requset(void *dm_handle)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_GET_DESIRED;
msg.data.get_desired.params = "[\"LightSwitch\"]";
return aiot_dm_send(dm_handle, &msg);
}
/* 演示了删除属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */
int32_t demo_send_delete_desred_requset(void *dm_handle)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_DELETE_DESIRED;
msg.data.get_desired.params = "{\"LightSwitch\":{}}";
return aiot_dm_send(dm_handle, &msg);
}
int demo_main(int argc, char *argv[])
{
int32_t res = STATE_SUCCESS;
void *dm_handle = NULL;
void *mqtt_handle = NULL;
char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
/* TODO: 替换为自己设备的三元组 */
char *product_key = "";
char *device_name = "";
char *device_secret = "";
/* 配置SDK的底层依赖 */
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
/* 配置SDK的日志输出 */
aiot_state_set_logcb(demo_state_logcb);
/* 创建SDK的安全凭据, 用于建立TLS连接 */
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
/* 创建1个MQTT客户端实例并内部初始化默认参数 */
mqtt_handle = aiot_mqtt_init();
if (mqtt_handle == NULL) {
printf("aiot_mqtt_init failed\n");
return -1;
}
snprintf(host, 100, "%s.%s", product_key, url);
/* 配置MQTT服务器地址 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
/* 配置MQTT服务器端口 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
/* 配置设备productKey */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
/* 配置设备deviceName */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
/* 配置设备deviceSecret */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
/* 配置网络连接的安全凭据, 上面已经创建好了 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
/* 配置MQTT事件回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
/* 创建DATA-MODEL实例 */
dm_handle = aiot_dm_init();
if (dm_handle == NULL) {
printf("aiot_dm_init failed");
return -1;
}
/* 配置MQTT实例句柄 */
aiot_dm_setopt(dm_handle, AIOT_DMOPT_MQTT_HANDLE, mqtt_handle);
/* 配置消息接收处理回调函数 */
aiot_dm_setopt(dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)demo_dm_recv_handler);
/* 与服务器建立MQTT连接 */
res = aiot_mqtt_connect(mqtt_handle);
if (res < STATE_SUCCESS) {
/* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
aiot_mqtt_deinit(&mqtt_handle);
printf("aiot_mqtt_connect failed: -0x%04X\n", -res);
return -1;
}
/* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
g_mqtt_process_thread_running = 1;
res = aos_task_new("demo_mqtt_process", demo_mqtt_process_thread, mqtt_handle, 4096);
// res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle);
if (res != 0) {
printf("create demo_mqtt_process_thread failed: %d\n", res);
return -1;
}
/* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
g_mqtt_recv_thread_running = 1;
res = aos_task_new("demo_mqtt_process", demo_mqtt_recv_thread, mqtt_handle, 4096);
// res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle);
if (res != 0) {
printf("create demo_mqtt_recv_thread failed: %d\n", res);
return -1;
}
/* 主循环进入休眠 */
while (1) {
/* TODO: 以下代码演示了简单的属性上报和事件上报, 用户可取消注释观察演示效果 */
demo_send_property_post(dm_handle, "{\"LightSwitch\": 0}");
demo_send_event_post(dm_handle, "Error", "{\"ErrorCode\": 0}");
aos_msleep(10000);
}
/* 断开MQTT连接, 一般不会运行到这里 */
res = aiot_mqtt_disconnect(mqtt_handle);
if (res < STATE_SUCCESS) {
aiot_mqtt_deinit(&mqtt_handle);
printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
return -1;
}
/* 销毁DATA-MODEL实例, 一般不会运行到这里 */
res = aiot_dm_deinit(&dm_handle);
if (res < STATE_SUCCESS) {
printf("aiot_dm_deinit failed: -0x%04X\n", -res);
return -1;
}
/* 销毁MQTT实例, 一般不会运行到这里 */
res = aiot_mqtt_deinit(&mqtt_handle);
if (res < STATE_SUCCESS) {
printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
return -1;
}
g_mqtt_process_thread_running = 0;
g_mqtt_recv_thread_running = 0;
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_demo/separate_app/data_model_basic_demo.c
|
C
|
apache-2.0
| 16,372
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
/**
* @file main.c
*
* This file includes the entry code of link sdk related demo
*
*/
#include <string.h>
#include <stdio.h>
#include <aos/kernel.h>
#include "netmgr.h"
#include <uservice/uservice.h>
#include <uservice/eventid.h>
extern int demo_main(int argc, char *argv[]);
static int _ip_got_finished = 0;
static void entry_func(void *data)
{
demo_main(0 , NULL);
}
static void wifi_event_cb(uint32_t event_id, const void *param, void *context)
{
aos_task_t task;
aos_status_t ret;
if (event_id != EVENT_NETMGR_DHCP_SUCCESS)
return;
if (_ip_got_finished != 0)
return;
_ip_got_finished = 1;
ret = aos_task_create(&task, "linksdk_demo", entry_func,
NULL, NULL, 6048, AOS_DEFAULT_APP_PRI, AOS_TASK_AUTORUN);
if (ret < 0) {
printf("create linksdk demo task failed, ret = %ld \r\n", ret);
}
}
int application_start(int argc, char *argv[])
{
aos_set_log_level(AOS_LL_DEBUG);
event_service_init(NULL);
netmgr_service_init(NULL);
netmgr_set_auto_reconnect(NULL, true);
netmgr_wifi_set_auto_save_ap(true);
event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL);
while (1) {
aos_msleep(1000);
};
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_demo/separate_app/main.c
|
C
|
apache-2.0
| 1,321
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo AOS SDK Done
sdk:
$(CPRE) aos sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
$(CPRE) find . -name "*.[od]" -delete
$(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin generated out
|
YifuLiu/AliOS-Things
|
solutions/linksdk_gateway_demo/Makefile
|
Makefile
|
apache-2.0
| 397
|
#! /bin/env python
from aostools import Make
# default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin
# defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin')
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/linksdk_gateway_demo/SConstruct
|
Python
|
apache-2.0
| 303
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
/**
* @file main.c
*
* This file includes the entry code of link sdk related demo
*
*/
#include <string.h>
#include <stdio.h>
#include <aos/kernel.h>
#include "ulog/ulog.h"
#include "netmgr.h"
#include <uservice/uservice.h>
#include <uservice/eventid.h>
extern int demo_main(int argc, char *argv[]);
static int _ip_got_finished = 0;
static void entry_func(void *data)
{
demo_main(0 , NULL);
}
static void wifi_event_cb(uint32_t event_id, const void *param, void *context)
{
aos_task_t task;
aos_status_t ret;
if (event_id != EVENT_NETMGR_DHCP_SUCCESS)
return;
if (_ip_got_finished != 0)
return;
_ip_got_finished = 1;
ret = aos_task_create(&task, "linksdk_gateway_demo", entry_func,
NULL, NULL, 6048, AOS_DEFAULT_APP_PRI, AOS_TASK_AUTORUN);
if (ret < 0) {
printf("create linksdk gateway demo task failed, ret = %ld \r\n", ret);
}
}
int application_start(int argc, char *argv[])
{
aos_set_log_level(AOS_LL_DEBUG);
event_service_init(NULL);
netmgr_service_init(NULL);
netmgr_set_auto_reconnect(NULL, true);
netmgr_wifi_set_auto_save_ap(true);
event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL);
while (1)
aos_msleep(1000);
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_gateway_demo/main.c
|
C
|
apache-2.0
| 1,351
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t *init_args);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void *arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifdef CONFIG_COM_DRV
//_os_driver_entry();
#endif
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_gateway_demo/maintask.c
|
C
|
apache-2.0
| 1,248
|
/*
* 这个例程演示了用SDK代理子设备,之后创建2个线程
*
* + 一个线程用于保活长连接
* + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调
*
* 接着演示了在MQTT连接上进行属性上报, 事件上报, 以及处理收到的属性设置, 服务调用, 取消这些代码段落的注释即可观察运行效果
*
* 需要用户关注或修改的部分, 已经用 TODO 在注释中标明
*
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <aos/kernel.h>
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_subdev_api.h"
/* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
/* 位于external/ali_ca_cert.c中的服务器证书 */
extern const char *ali_ca_cert;
static uint8_t g_mqtt_process_thread_running = 0;
static uint8_t g_mqtt_recv_thread_running = 0;
aiot_subdev_dev_t g_subdev[] = {
{
"a13FN5TplKq",
"subdev_basic_demo_01",
"768XBgQwgOakz3K4uhOiLeeh9xjJQx6h",
"y7GSILD480lBSsP8"
},
{
"a13FN5TplKq",
"subdev_basic_demo_02",
"iwTZrbjbgNVChfuJkihjE5asekoyKoYv",
"y7GSILD480lBSsP8"
},
{
"a13FN5TplKq",
"subdev_basic_demo_03",
"fdutq35iKMYdcWWBuIINY26hsNhgFXWE",
"y7GSILD480lBSsP8"
},
{
"a13FN5TplKq",
"subdev_basic_demo_04",
"HCKv50YqgwdKhy5cE0Vz4aydmK2ojPvr",
"y7GSILD480lBSsP8"
}
};
/* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
*
* 例如: [1577589489.033][LK-0317] subdev_basic_demo&a13FN5TplKq
*
* 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h
*
*/
/* 日志回调函数, SDK的日志会从这里输出 */
static int32_t demo_state_logcb(int32_t code, char *message)
{
printf("%s", message);
return 0;
}
/* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
{
switch (event->type) {
/* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
case AIOT_MQTTEVT_CONNECT: {
printf("AIOT_MQTTEVT_CONNECT\n");
/* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */
}
break;
/* SDK因为网络状况被动断连后, 自动发起重连已成功 */
case AIOT_MQTTEVT_RECONNECT: {
printf("AIOT_MQTTEVT_RECONNECT\n");
/* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */
}
break;
/* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
case AIOT_MQTTEVT_DISCONNECT: {
char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
("heartbeat disconnect");
printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause);
/* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */
}
break;
default: {
}
}
}
/* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */
void demo_mqtt_default_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
{
switch (packet->type) {
case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
printf("heartbeat response\n");
/* TODO: 处理服务器对心跳的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_SUB_ACK: {
printf("suback, res: -0x%04X, packet id: %d, max qos: %d\n",
-packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
/* TODO: 处理服务器对订阅请求的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_PUB: {
printf("pub, qos: %d, topic: %.*s\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
printf("pub, payload: %.*s\n", packet->data.pub.payload_len, packet->data.pub.payload);
/* TODO: 处理服务器下发的业务报文 */
}
break;
case AIOT_MQTTRECV_PUB_ACK: {
printf("puback, packet id: %d\n", packet->data.pub_ack.packet_id);
/* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
}
break;
default: {
}
}
}
/* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
void *demo_mqtt_process_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (g_mqtt_process_thread_running) {
res = aiot_mqtt_process(args);
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
return NULL;
}
/* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
void *demo_mqtt_recv_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (g_mqtt_recv_thread_running) {
res = aiot_mqtt_recv(args);
if (res < STATE_SUCCESS) {
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
}
return NULL;
}
int32_t demo_mqtt_start(void **handle)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
/* TODO: 替换为自己设备的三元组 */
char *product_key = "a1tmc66UyDK";
char *device_name = "subdev_basic_demo";
char *device_secret = "awAlkVEzZm40nk4EbMfcUVRwDnnClVVu";
/* 创建SDK的安全凭据, 用于建立TLS连接 */
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
/* 创建1个MQTT客户端实例并内部初始化默认参数 */
mqtt_handle = aiot_mqtt_init();
if (mqtt_handle == NULL) {
printf("aiot_mqtt_init failed\n");
return -1;
}
/* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */
/*
{
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE;
}
*/
snprintf(host, 100, "%s.%s", product_key, url);
/* 配置MQTT服务器地址 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
/* 配置MQTT服务器端口 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
/* 配置设备productKey */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
/* 配置设备deviceName */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
/* 配置设备deviceSecret */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
/* 配置网络连接的安全凭据, 上面已经创建好了 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
/* 配置MQTT默认消息接收回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
/* 配置MQTT事件回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
/* 与服务器建立MQTT连接 */
res = aiot_mqtt_connect(mqtt_handle);
if (res < STATE_SUCCESS) {
/* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
aiot_mqtt_deinit(&mqtt_handle);
printf("aiot_mqtt_connect failed: -0x%04X\n", -res);
return -1;
}
/* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
g_mqtt_process_thread_running = 1;
res = aos_task_new("demo_mqtt_process", demo_mqtt_process_thread, mqtt_handle, 4096);
// res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle);
if (res != 0) {
printf("create demo_mqtt_process_thread failed: %d\n", res);
aiot_mqtt_deinit(&mqtt_handle);
return -1;
}
/* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
g_mqtt_recv_thread_running = 1;
res = aos_task_new("demo_mqtt_process", demo_mqtt_recv_thread, mqtt_handle, 4096);
// res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle);
if (res != 0) {
printf("create demo_mqtt_recv_thread failed: %d\n", res);
g_mqtt_process_thread_running = 0;
aiot_mqtt_deinit(&mqtt_handle);
return -1;
}
*handle = mqtt_handle;
return 0;
}
int32_t demo_mqtt_stop(void **handle)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
mqtt_handle = *handle;
g_mqtt_process_thread_running = 0;
g_mqtt_recv_thread_running = 0;
/* 断开MQTT连接 */
res = aiot_mqtt_disconnect(mqtt_handle);
if (res < STATE_SUCCESS) {
aiot_mqtt_deinit(&mqtt_handle);
printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
return -1;
}
/* 销毁MQTT实例 */
res = aiot_mqtt_deinit(&mqtt_handle);
if (res < STATE_SUCCESS) {
printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
return -1;
}
return 0;
}
void demo_subdev_recv_handler(void *handle, const aiot_subdev_recv_t *packet, void *user_data)
{
switch (packet->type) {
case AIOT_SUBDEVRECV_TOPO_ADD_REPLY:
case AIOT_SUBDEVRECV_TOPO_DELETE_REPLY:
case AIOT_SUBDEVRECV_TOPO_GET_REPLY:
case AIOT_SUBDEVRECV_BATCH_LOGIN_REPLY:
case AIOT_SUBDEVRECV_BATCH_LOGOUT_REPLY:
case AIOT_SUBDEVRECV_SUB_REGISTER_REPLY:
case AIOT_SUBDEVRECV_PRODUCT_REGISTER_REPLY: {
printf("msgid : %d\n", packet->data.generic_reply.msg_id);
printf("code : %d\n", packet->data.generic_reply.code);
printf("product key : %s\n", packet->data.generic_reply.product_key);
printf("device name : %s\n", packet->data.generic_reply.device_name);
printf("message : %s\n", (packet->data.generic_reply.message == NULL) ? ("NULL") : (packet->data.generic_reply.message));
printf("data : %s\n", packet->data.generic_reply.data);
}
break;
case AIOT_SUBDEVRECV_TOPO_CHANGE_NOTIFY: {
printf("msgid : %d\n", packet->data.generic_notify.msg_id);
printf("product key : %s\n", packet->data.generic_notify.product_key);
printf("device name : %s\n", packet->data.generic_notify.device_name);
printf("params : %s\n", packet->data.generic_notify.params);
}
break;
default: {
}
}
}
int demo_main(int argc, char *argv[])
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL, *subdev_handle = NULL;
/* 配置SDK的底层依赖 */
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
/* 配置SDK的日志输出 */
aiot_state_set_logcb(demo_state_logcb);
res = demo_mqtt_start(&mqtt_handle);
if (res < 0) {
printf("demo_mqtt_start failed\n");
return -1;
}
subdev_handle = aiot_subdev_init();
if (subdev_handle == NULL) {
printf("aiot_subdev_init failed\n");
demo_mqtt_stop(&mqtt_handle);
return -1;
}
aiot_subdev_setopt(subdev_handle, AIOT_SUBDEVOPT_MQTT_HANDLE, mqtt_handle);
aiot_subdev_setopt(subdev_handle, AIOT_SUBDEVOPT_RECV_HANDLER, demo_subdev_recv_handler);
res = aiot_subdev_send_topo_add(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
if (res < STATE_SUCCESS) {
printf("aiot_subdev_send_topo_add failed, res: -0x%04X\n", -res);
aiot_subdev_deinit(&subdev_handle);
demo_mqtt_stop(&mqtt_handle);
return -1;
}
aos_msleep(1000);
// aiot_subdev_send_topo_delete(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
// if (res < STATE_SUCCESS) {
// printf("aiot_subdev_send_topo_delete failed, res: -0x%04X\n", -res);
// aiot_subdev_deinit(&subdev_handle);
// demo_mqtt_stop(&mqtt_handle);
// return -1;
// }
// aos_msleep(1000);
// aiot_subdev_send_topo_get(subdev_handle);
// if (res < STATE_SUCCESS) {
// printf("aiot_subdev_send_topo_get failed, res: -0x%04X\n", -res);
// aiot_subdev_deinit(&subdev_handle);
// demo_mqtt_stop(&mqtt_handle);
// return -1;
// }
// aos_msleep(1000);
// aiot_subdev_send_sub_register(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
// if (res < STATE_SUCCESS) {
// printf("aiot_subdev_send_sub_register failed, res: -0x%04X\n", -res);
// aiot_subdev_deinit(&subdev_handle);
// demo_mqtt_stop(&mqtt_handle);
// return -1;
// }
// aos_msleep(1000);
// aiot_subdev_send_product_register(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
// if (res < STATE_SUCCESS) {
// printf("aiot_subdev_send_product_register failed, res: -0x%04X\n", -res);
// aiot_subdev_deinit(&subdev_handle);
// demo_mqtt_stop(&mqtt_handle);
// return -1;
// }
// aos_msleep(1000);
aiot_subdev_send_batch_login(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
if (res < STATE_SUCCESS) {
printf("aiot_subdev_send_batch_login failed, res: -0x%04X\n", -res);
aiot_subdev_deinit(&subdev_handle);
demo_mqtt_stop(&mqtt_handle);
return -1;
}
aos_msleep(1000);
// aiot_subdev_send_batch_logout(subdev_handle, g_subdev, sizeof(g_subdev) / sizeof(aiot_subdev_dev_t));
// if (res < STATE_SUCCESS) {
// printf("aiot_subdev_send_batch_logout failed, res: -0x%04X\n", -res);
// aiot_subdev_deinit(&subdev_handle);
// demo_mqtt_stop(&mqtt_handle);
// return -1;
// }
while (1)
aos_msleep(1000);
res = aiot_subdev_deinit(&subdev_handle);
if (res < STATE_SUCCESS)
printf("aiot_subdev_deinit failed: -0x%04X\n", res);
res = demo_mqtt_stop(&mqtt_handle);
if (res < 0) {
printf("demo_start_stop failed\n");
return -1;
}
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/linksdk_gateway_demo/subdev_basic_demo.c
|
C
|
apache-2.0
| 15,751
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo AOS SDK Done
sdk:
$(CPRE) aos sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
$(CPRE) find . -name "*.[od]" -delete
$(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin generated out
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/Makefile
|
Makefile
|
apache-2.0
| 397
|
#! /bin/env python
from aostools import Make
# defconfig = Make(elf='yoc.elf', objcopy='generated/data/prim', objdump='yoc.asm')
defconfig = Make(elf='aos.elf', objcopy='binary/helloworld_demo@haas100.bin')
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/SConstruct
|
Python
|
apache-2.0
| 260
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <string.h>
#include "board.h"
#include "radio.h"
#include "aos/hal/gpio.h"
#include "aos/hal/spi.h"
#include "sx126x-board.h"
#include "aos/hal/timer.h"
#include "ulog/ulog.h"
#define TRANS_MODE_TX (0xEF)
#define TRANS_MODE_RX (0xFE)
// set transmission mode here, TRANS_MODE_TX or TRANS_MODE_RX
#define TRANSMIT_MODE TRANS_MODE_TX
#define RF_FREQUENCY 470000000 // 779000000 Hz
#define TX_OUTPUT_POWER 14 // dBm
#define LORA_BANDWIDTH 2 // [0: 125 kHz, 1: 250 kHz, 2: 500 kHz]
#define LORA_SPREADING_FACTOR 7 // [SF7..SF12]
#define LORA_CODINGRATE 1 // [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
#define LORA_PREAMBLE_LENGTH 8 // Same for Tx and Rx
#define LORA_SYMBOL_TIMEOUT 0 // Symbols
#define LORA_FIX_LENGTH_PAYLOAD_ON false
#define LORA_IQ_INVERSION_ON false
#define BUFFER_SIZE 64 // Define the payload size here
uint8_t g_buffer[BUFFER_SIZE] = {0};
static RadioEvents_t g_RadioCallback;
void OnTxDone( ) {
LOG("[lora demo][%s] << %s \n", __func__, g_buffer);
memset(g_buffer, 0, BUFFER_SIZE);
sleep(5);
}
void OnRxDone( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr ) {
LOG("[lora demo][%s] >> %s \n", __func__, payload);
Radio.Sleep();
Radio.Rx( 1000 );
}
/**
* Main application entry point.
*/
int application_start(int argc, char *argv[]) {
bool isMaster = true;
uint8_t i;
// set log level
aos_set_log_level(AOS_LL_DEBUG);
// Radio initialization
g_RadioCallback.TxDone = OnTxDone;
g_RadioCallback.RxDone = OnRxDone;
Radio.Init( &g_RadioCallback );
LOG("[lora demo] ++init radio done++");
Radio.SetChannel( RF_FREQUENCY );
#if defined(TRANSMIT_MODE) && (TRANSMIT_MODE == TRANS_MODE_TX)
Radio.SetTxConfig( MODEM_LORA, TX_OUTPUT_POWER, 0, LORA_BANDWIDTH,
LORA_SPREADING_FACTOR, LORA_CODINGRATE,
LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON,
true, 0, 0, LORA_IQ_INVERSION_ON, 3000 );
LOG("[lora demo] ++set TX config done++");
#elif defined(TRANSMIT_MODE) && (TRANSMIT_MODE == TRANS_MODE_RX)
Radio.SetRxConfig( MODEM_LORA, LORA_BANDWIDTH, LORA_SPREADING_FACTOR,
LORA_CODINGRATE, 0, LORA_PREAMBLE_LENGTH,
LORA_SYMBOL_TIMEOUT, LORA_FIX_LENGTH_PAYLOAD_ON,
0, true, 0, 0, LORA_IQ_INVERSION_ON, true );
LOG("[lora demo] ++set RX config done++");
#else
#error "PLEASE SET VALID TRANSMIT MODE FIRST!!"
#endif
Radio.SetMaxPayloadLength( MODEM_LORA, BUFFER_SIZE );
LOG("[lora demo] ++lora init done++\n");
#if defined(TRANSMIT_MODE) && (TRANSMIT_MODE == TRANS_MODE_RX)
Radio.Rx( 1000 );
#endif
while( 1 )
{
#if defined(TRANSMIT_MODE) && (TRANSMIT_MODE == TRANS_MODE_TX)
if(strlen(g_buffer) == 0) {
snprintf(g_buffer, BUFFER_SIZE, "Hello from HaaS@%llu...", aos_now_ms());
Radio.Send( g_buffer, strlen(g_buffer)+1);
}
#endif
if( Radio.IrqProcess != NULL )
{
Radio.IrqProcess( );
}
// sleep for other system task, such as CLI task.
aos_msleep(100);
}
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/demo.c
|
C
|
apache-2.0
| 3,592
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t* init_args);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void* arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/maintask.c
|
C
|
apache-2.0
| 1,192
|
/*!
* \file radio.c
*
* \brief Radio driver API definition
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#include <math.h>
#include <string.h>
//#include "utilities.h"
//#include "timer.h"
//#include "delay.h"
#include "radio.h"
#include "sx126x.h"
#include "sx126x-board.h"
#include "board.h"
#include "ulog/ulog.h"
/*!
* \brief Initializes the radio
*
* \param [IN] events Structure containing the driver callback functions
*/
void RadioInit( RadioEvents_t *events );
/*!
* Return current radio status
*
* \param status Radio status.[RF_IDLE, RF_RX_RUNNING, RF_TX_RUNNING]
*/
RadioState_t RadioGetStatus( void );
/*!
* \brief Configures the radio with the given modem
*
* \param [IN] modem Modem to be used [0: FSK, 1: LoRa]
*/
void RadioSetModem( RadioModems_t modem );
/*!
* \brief Sets the channel frequency
*
* \param [IN] freq Channel RF frequency
*/
void RadioSetChannel( uint32_t freq );
/*!
* \brief Checks if the channel is free for the given time
*
* \remark The FSK modem is always used for this task as we can select the Rx bandwidth at will.
*
* \param [IN] freq Channel RF frequency in Hertz
* \param [IN] rxBandwidth Rx bandwidth in Hertz
* \param [IN] rssiThresh RSSI threshold in dBm
* \param [IN] maxCarrierSenseTime Max time in milliseconds while the RSSI is measured
*
* \retval isFree [true: Channel is free, false: Channel is not free]
*/
bool RadioIsChannelFree( uint32_t freq, uint32_t rxBandwidth, int16_t rssiThresh, uint32_t maxCarrierSenseTime );
/*!
* \brief Generates a 32 bits random value based on the RSSI readings
*
* \remark This function sets the radio in LoRa modem mode and disables
* all interrupts.
* After calling this function either Radio.SetRxConfig or
* Radio.SetTxConfig functions must be called.
*
* \retval randomValue 32 bits random value
*/
uint32_t RadioRandom( void );
/*!
* \brief Sets the reception parameters
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] bandwidth Sets the bandwidth
* FSK : >= 2600 and <= 250000 Hz
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] bandwidthAfc Sets the AFC Bandwidth (FSK only)
* FSK : >= 2600 and <= 250000 Hz
* LoRa: N/A ( set to 0 )
* \param [IN] preambleLen Sets the Preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] symbTimeout Sets the RxSingle timeout value
* FSK : timeout in number of bytes
* LoRa: timeout in symbols
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] payloadLen Sets payload length when fixed length is used
* \param [IN] crcOn Enables/Disables the CRC [0: OFF, 1: ON]
* \param [IN] FreqHopOn Enables disables the intra-packet frequency hopping
* FSK : N/A ( set to 0 )
* LoRa: [0: OFF, 1: ON]
* \param [IN] HopPeriod Number of symbols between each hop
* FSK : N/A ( set to 0 )
* LoRa: Number of symbols
* \param [IN] iqInverted Inverts IQ signals (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [0: not inverted, 1: inverted]
* \param [IN] rxContinuous Sets the reception in continuous mode
* [false: single mode, true: continuous mode]
*/
void RadioSetRxConfig( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint32_t bandwidthAfc, uint16_t preambleLen,
uint16_t symbTimeout, bool fixLen,
uint8_t payloadLen,
bool crcOn, bool FreqHopOn, uint8_t HopPeriod,
bool iqInverted, bool rxContinuous );
/*!
* \brief Sets the transmission parameters
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] power Sets the output power [dBm]
* \param [IN] fdev Sets the frequency deviation (FSK only)
* FSK : [Hz]
* LoRa: 0
* \param [IN] bandwidth Sets the bandwidth (LoRa only)
* FSK : 0
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] preambleLen Sets the preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] crcOn Enables disables the CRC [0: OFF, 1: ON]
* \param [IN] FreqHopOn Enables disables the intra-packet frequency hopping
* FSK : N/A ( set to 0 )
* LoRa: [0: OFF, 1: ON]
* \param [IN] HopPeriod Number of symbols between each hop
* FSK : N/A ( set to 0 )
* LoRa: Number of symbols
* \param [IN] iqInverted Inverts IQ signals (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [0: not inverted, 1: inverted]
* \param [IN] timeout Transmission timeout [ms]
*/
void RadioSetTxConfig( RadioModems_t modem, int8_t power, uint32_t fdev,
uint32_t bandwidth, uint32_t datarate,
uint8_t coderate, uint16_t preambleLen,
bool fixLen, bool crcOn, bool FreqHopOn,
uint8_t HopPeriod, bool iqInverted, uint32_t timeout );
/*!
* \brief Checks if the given RF frequency is supported by the hardware
*
* \param [IN] frequency RF frequency to be checked
* \retval isSupported [true: supported, false: unsupported]
*/
bool RadioCheckRfFrequency( uint32_t frequency );
/*!
* \brief Computes the packet time on air in ms for the given payload
*
* \Remark Can only be called once SetRxConfig or SetTxConfig have been called
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] bandwidth Sets the bandwidth
* FSK : >= 2600 and <= 250000 Hz
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] preambleLen Sets the Preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] payloadLen Sets payload length when fixed length is used
* \param [IN] crcOn Enables/Disables the CRC [0: OFF, 1: ON]
*
* \retval airTime Computed airTime (ms) for the given packet payload length
*/
uint32_t RadioTimeOnAir( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint16_t preambleLen, bool fixLen, uint8_t payloadLen,
bool crcOn );
/*!
* \brief Sends the buffer of size. Prepares the packet to be sent and sets
* the radio in transmission
*
* \param [IN]: buffer Buffer pointer
* \param [IN]: size Buffer size
*/
void RadioSend( uint8_t *buffer, uint8_t size );
/*!
* \brief Sets the radio in sleep mode
*/
void RadioSleep( void );
/*!
* \brief Sets the radio in standby mode
*/
void RadioStandby( void );
/*!
* \brief Sets the radio in reception mode for the given time
* \param [IN] timeout Reception timeout [ms]
* [0: continuous, others timeout]
*/
void RadioRx( uint32_t timeout );
/*!
* \brief Start a Channel Activity Detection
*/
void RadioStartCad( void );
/*!
* \brief Sets the radio in continuous wave transmission mode
*
* \param [IN]: freq Channel RF frequency
* \param [IN]: power Sets the output power [dBm]
* \param [IN]: time Transmission mode timeout [s]
*/
void RadioSetTxContinuousWave( uint32_t freq, int8_t power, uint16_t time );
/*!
* \brief Reads the current RSSI value
*
* \retval rssiValue Current RSSI value in [dBm]
*/
int16_t RadioRssi( RadioModems_t modem );
/*!
* \brief Writes the radio register at the specified address
*
* \param [IN]: addr Register address
* \param [IN]: data New register value
*/
void RadioWrite( uint32_t addr, uint8_t data );
/*!
* \brief Reads the radio register at the specified address
*
* \param [IN]: addr Register address
* \retval data Register value
*/
uint8_t RadioRead( uint32_t addr );
/*!
* \brief Writes multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [IN] buffer Buffer containing the new register's values
* \param [IN] size Number of registers to be written
*/
void RadioWriteBuffer( uint32_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Reads multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [OUT] buffer Buffer where to copy the registers data
* \param [IN] size Number of registers to be read
*/
void RadioReadBuffer( uint32_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Sets the maximum payload length.
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] max Maximum payload length in bytes
*/
void RadioSetMaxPayloadLength( RadioModems_t modem, uint8_t max );
/*!
* \brief Sets the network to public or private. Updates the sync byte.
*
* \remark Applies to LoRa modem only
*
* \param [IN] enable if true, it enables a public network
*/
void RadioSetPublicNetwork( bool enable );
/*!
* \brief Gets the time required for the board plus radio to get out of sleep.[ms]
*
* \retval time Radio plus board wakeup time in ms.
*/
uint32_t RadioGetWakeupTime( void );
/*!
* \brief Process radio irq
*/
void RadioIrqProcess( void );
/*!
* \brief Sets the radio in reception mode with Max LNA gain for the given time
* \param [IN] timeout Reception timeout [ms]
* [0: continuous, others timeout]
*/
void RadioRxBoosted( uint32_t timeout );
/*!
* \brief Sets the Rx duty cycle management parameters
*
* \param [in] rxTime Structure describing reception timeout value
* \param [in] sleepTime Structure describing sleep timeout value
*/
void RadioSetRxDutyCycle( uint32_t rxTime, uint32_t sleepTime );
/*!
* Radio driver structure initialization
*/
const struct Radio_s Radio =
{
RadioInit,
RadioGetStatus,
RadioSetModem,
RadioSetChannel,
RadioIsChannelFree,
RadioRandom,
RadioSetRxConfig,
RadioSetTxConfig,
RadioCheckRfFrequency,
RadioTimeOnAir,
RadioSend,
RadioSleep,
RadioStandby,
RadioRx,
RadioStartCad,
RadioSetTxContinuousWave,
RadioRssi,
RadioWrite,
RadioRead,
RadioWriteBuffer,
RadioReadBuffer,
RadioSetMaxPayloadLength,
RadioSetPublicNetwork,
RadioGetWakeupTime,
RadioIrqProcess,
// Available on SX126x only
RadioRxBoosted,
RadioSetRxDutyCycle
};
/*
* Local types definition
*/
/*!
* FSK bandwidth definition
*/
typedef struct
{
uint32_t bandwidth;
uint8_t RegValue;
}FskBandwidth_t;
/*!
* Precomputed FSK bandwidth registers values
*/
const FskBandwidth_t FskBandwidths[] =
{
{ 4800 , 0x1F },
{ 5800 , 0x17 },
{ 7300 , 0x0F },
{ 9700 , 0x1E },
{ 11700 , 0x16 },
{ 14600 , 0x0E },
{ 19500 , 0x1D },
{ 23400 , 0x15 },
{ 29300 , 0x0D },
{ 39000 , 0x1C },
{ 46900 , 0x14 },
{ 58600 , 0x0C },
{ 78200 , 0x1B },
{ 93800 , 0x13 },
{ 117300, 0x0B },
{ 156200, 0x1A },
{ 187200, 0x12 },
{ 234300, 0x0A },
{ 312000, 0x19 },
{ 373600, 0x11 },
{ 467000, 0x09 },
{ 500000, 0x00 }, // Invalid Bandwidth
};
const RadioLoRaBandwidths_t Bandwidths[] = { LORA_BW_125, LORA_BW_250, LORA_BW_500 };
uint8_t MaxPayloadLength = 0xFF;
uint32_t TxTimeout = 0;
uint32_t RxTimeout = 0;
bool RxContinuous = false;
PacketStatus_t RadioPktStatus;
uint8_t RadioRxPayload[255];
bool IrqFired = false;
/*
* SX126x DIO IRQ callback functions prototype
*/
/*!
* \brief DIO 0 IRQ callback
*/
void RadioOnDioIrq( void* context );
/*!
* \brief Tx timeout timer callback
*/
void RadioOnTxTimeoutIrq( void* context );
/*!
* \brief Rx timeout timer callback
*/
void RadioOnRxTimeoutIrq( void* context );
/*
* Private global variables
*/
/*!
* Holds the current network type for the radio
*/
typedef struct
{
bool Previous;
bool Current;
}RadioPublicNetwork_t;
static RadioPublicNetwork_t RadioPublicNetwork = { false };
/*!
* Radio callbacks variable
*/
static RadioEvents_t* RadioEvents;
/*
* Public global variables
*/
/*!
* Radio hardware and global parameters
*/
SX126x_t SX126x;
/*!
* Tx and Rx timers
TimerEvent_t TxTimeoutTimer; // TODO
TimerEvent_t RxTimeoutTimer;
*/
/*!
* Returns the known FSK bandwidth registers value
*
* \param [IN] bandwidth Bandwidth value in Hz
* \retval regValue Bandwidth register value.
*/
static uint8_t RadioGetFskBandwidthRegValue( uint32_t bandwidth )
{
uint8_t i;
if( bandwidth == 0 )
{
return( 0x1F );
}
for( i = 0; i < ( sizeof( FskBandwidths ) / sizeof( FskBandwidth_t ) ) - 1; i++ )
{
if( ( bandwidth >= FskBandwidths[i].bandwidth ) && ( bandwidth < FskBandwidths[i + 1].bandwidth ) )
{
return FskBandwidths[i+1].RegValue;
}
}
// ERROR: Value not found
while( 1 );
}
void RadioInit( RadioEvents_t *events )
{
RadioEvents = events;
SX126xInit( RadioOnDioIrq );
SX126xSetStandby( STDBY_RC );
SX126xSetRegulatorMode( USE_DCDC );
SX126xSetBufferBaseAddress( 0x00, 0x00 );
SX126xSetTxParams( 0, RADIO_RAMP_200_US );
//SX126xSetDioIrqParams( IRQ_RADIO_ALL, IRQ_RADIO_ALL, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
IrqFired = false;
}
RadioState_t RadioGetStatus( void )
{
switch( SX126xGetOperatingMode( ) )
{
case MODE_TX:
return RF_TX_RUNNING;
case MODE_RX:
return RF_RX_RUNNING;
case MODE_CAD:
return RF_CAD;
default:
return RF_IDLE;
}
}
void RadioSetModem( RadioModems_t modem )
{
switch( modem )
{
default:
case MODEM_FSK:
SX126xSetPacketType( PACKET_TYPE_GFSK );
// When switching to GFSK mode the LoRa SyncWord register value is reset
// Thus, we also reset the RadioPublicNetwork variable
RadioPublicNetwork.Current = false;
break;
case MODEM_LORA:
SX126xSetPacketType( PACKET_TYPE_LORA );
// Public/Private network register is reset when switching modems
if( RadioPublicNetwork.Current != RadioPublicNetwork.Previous )
{
RadioPublicNetwork.Current = RadioPublicNetwork.Previous;
RadioSetPublicNetwork( RadioPublicNetwork.Current );
}
break;
}
}
void RadioSetChannel( uint32_t freq )
{
SX126xSetRfFrequency( freq );
}
bool RadioIsChannelFree( uint32_t freq, uint32_t rxBandwidth, int16_t rssiThresh, uint32_t maxCarrierSenseTime )
{
bool status = true;
int16_t rssi = 0;
uint32_t carrierSenseTime = 0;
RadioSetModem( MODEM_FSK );
RadioSetChannel( freq );
// Set Rx bandwidth. Other parameters are not used.
RadioSetRxConfig( MODEM_FSK, rxBandwidth, 600, 0, rxBandwidth, 3, 0, false,
0, false, 0, 0, false, true );
RadioRx( 0 );
usleep( 1000 );
#if 0
carrierSenseTime = TimerGetCurrentTime( );
// Perform carrier sense for maxCarrierSenseTime
while( TimerGetElapsedTime( carrierSenseTime ) < maxCarrierSenseTime )
{
rssi = RadioRssi( MODEM_FSK );
if( rssi > rssiThresh )
{
status = false;
break;
}
}
#endif
RadioSleep( );
return status;
}
uint32_t RadioRandom( void )
{
uint32_t rnd = 0;
/*
* Radio setup for random number generation
*/
// Set LoRa modem ON
RadioSetModem( MODEM_LORA );
// Disable LoRa modem interrupts
SX126xSetDioIrqParams( IRQ_RADIO_NONE, IRQ_RADIO_NONE, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
rnd = SX126xGetRandom( );
return rnd;
}
void RadioSetRxConfig( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint32_t bandwidthAfc, uint16_t preambleLen,
uint16_t symbTimeout, bool fixLen,
uint8_t payloadLen,
bool crcOn, bool freqHopOn, uint8_t hopPeriod,
bool iqInverted, bool rxContinuous )
{
RxContinuous = rxContinuous;
if( rxContinuous == true )
{
symbTimeout = 0;
}
if( fixLen == true )
{
MaxPayloadLength = payloadLen;
}
else
{
MaxPayloadLength = 0xFF;
}
switch( modem )
{
case MODEM_FSK:
SX126xSetStopRxTimerOnPreambleDetect( false );
SX126x.ModulationParams.PacketType = PACKET_TYPE_GFSK;
SX126x.ModulationParams.Params.Gfsk.BitRate = datarate;
SX126x.ModulationParams.Params.Gfsk.ModulationShaping = MOD_SHAPING_G_BT_1;
SX126x.ModulationParams.Params.Gfsk.Bandwidth = RadioGetFskBandwidthRegValue( bandwidth << 1 ); // SX126x badwidth is double sided
SX126x.PacketParams.PacketType = PACKET_TYPE_GFSK;
SX126x.PacketParams.Params.Gfsk.PreambleLength = ( preambleLen << 3 ); // convert byte into bit
SX126x.PacketParams.Params.Gfsk.PreambleMinDetect = RADIO_PREAMBLE_DETECTOR_08_BITS;
SX126x.PacketParams.Params.Gfsk.SyncWordLength = 3 << 3; // convert byte into bit
SX126x.PacketParams.Params.Gfsk.AddrComp = RADIO_ADDRESSCOMP_FILT_OFF;
SX126x.PacketParams.Params.Gfsk.HeaderType = ( fixLen == true ) ? RADIO_PACKET_FIXED_LENGTH : RADIO_PACKET_VARIABLE_LENGTH;
SX126x.PacketParams.Params.Gfsk.PayloadLength = MaxPayloadLength;
if( crcOn == true )
{
SX126x.PacketParams.Params.Gfsk.CrcLength = RADIO_CRC_2_BYTES_CCIT;
}
else
{
SX126x.PacketParams.Params.Gfsk.CrcLength = RADIO_CRC_OFF;
}
SX126x.PacketParams.Params.Gfsk.DcFree = RADIO_DC_FREEWHITENING;
RadioStandby( );
RadioSetModem( ( SX126x.ModulationParams.PacketType == PACKET_TYPE_GFSK ) ? MODEM_FSK : MODEM_LORA );
SX126xSetModulationParams( &SX126x.ModulationParams );
SX126xSetPacketParams( &SX126x.PacketParams );
SX126xSetSyncWord( ( uint8_t[] ){ 0xC1, 0x94, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00 } );
SX126xSetWhiteningSeed( 0x01FF );
RxTimeout = ( uint32_t )( symbTimeout * ( ( 1.0 / ( double )datarate ) * 8.0 ) * 1000 );
break;
case MODEM_LORA:
SX126xSetStopRxTimerOnPreambleDetect( false );
SX126x.ModulationParams.PacketType = PACKET_TYPE_LORA;
SX126x.ModulationParams.Params.LoRa.SpreadingFactor = ( RadioLoRaSpreadingFactors_t )datarate;
SX126x.ModulationParams.Params.LoRa.Bandwidth = Bandwidths[bandwidth];
SX126x.ModulationParams.Params.LoRa.CodingRate = ( RadioLoRaCodingRates_t )coderate;
if( ( ( bandwidth == 0 ) && ( ( datarate == 11 ) || ( datarate == 12 ) ) ) ||
( ( bandwidth == 1 ) && ( datarate == 12 ) ) )
{
SX126x.ModulationParams.Params.LoRa.LowDatarateOptimize = 0x01;
}
else
{
SX126x.ModulationParams.Params.LoRa.LowDatarateOptimize = 0x00;
}
SX126x.PacketParams.PacketType = PACKET_TYPE_LORA;
if( ( SX126x.ModulationParams.Params.LoRa.SpreadingFactor == LORA_SF5 ) ||
( SX126x.ModulationParams.Params.LoRa.SpreadingFactor == LORA_SF6 ) )
{
if( preambleLen < 12 )
{
SX126x.PacketParams.Params.LoRa.PreambleLength = 12;
}
else
{
SX126x.PacketParams.Params.LoRa.PreambleLength = preambleLen;
}
}
else
{
SX126x.PacketParams.Params.LoRa.PreambleLength = preambleLen;
}
SX126x.PacketParams.Params.LoRa.HeaderType = ( RadioLoRaPacketLengthsMode_t )fixLen;
SX126x.PacketParams.Params.LoRa.PayloadLength = MaxPayloadLength;
SX126x.PacketParams.Params.LoRa.CrcMode = ( RadioLoRaCrcModes_t )crcOn;
SX126x.PacketParams.Params.LoRa.InvertIQ = ( RadioLoRaIQModes_t )iqInverted;
RadioStandby( );
RadioSetModem( ( SX126x.ModulationParams.PacketType == PACKET_TYPE_GFSK ) ? MODEM_FSK : MODEM_LORA );
SX126xSetModulationParams( &SX126x.ModulationParams );
SX126xSetPacketParams( &SX126x.PacketParams );
SX126xSetLoRaSymbNumTimeout( symbTimeout );
// WORKAROUND - Optimizing the Inverted IQ Operation, see DS_SX1261-2_V1.2 datasheet chapter 15.4
if( SX126x.PacketParams.Params.LoRa.InvertIQ == LORA_IQ_INVERTED )
{
// RegIqPolaritySetup = @address 0x0736
SX126xWriteRegister( 0x0736, SX126xReadRegister( 0x0736 ) & ~( 1 << 2 ) );
}
else
{
// RegIqPolaritySetup @address 0x0736
SX126xWriteRegister( 0x0736, SX126xReadRegister( 0x0736 ) | ( 1 << 2 ) );
}
// WORKAROUND END
// Timeout Max, Timeout handled directly in SetRx function
RxTimeout = 0xFFFF;
break;
}
}
void RadioSetTxConfig( RadioModems_t modem, int8_t power, uint32_t fdev,
uint32_t bandwidth, uint32_t datarate,
uint8_t coderate, uint16_t preambleLen,
bool fixLen, bool crcOn, bool freqHopOn,
uint8_t hopPeriod, bool iqInverted, uint32_t timeout )
{
switch( modem )
{
case MODEM_FSK:
SX126x.ModulationParams.PacketType = PACKET_TYPE_GFSK;
SX126x.ModulationParams.Params.Gfsk.BitRate = datarate;
SX126x.ModulationParams.Params.Gfsk.ModulationShaping = MOD_SHAPING_G_BT_1;
SX126x.ModulationParams.Params.Gfsk.Bandwidth = RadioGetFskBandwidthRegValue( bandwidth << 1 ); // SX126x badwidth is double sided
SX126x.ModulationParams.Params.Gfsk.Fdev = fdev;
SX126x.PacketParams.PacketType = PACKET_TYPE_GFSK;
SX126x.PacketParams.Params.Gfsk.PreambleLength = ( preambleLen << 3 ); // convert byte into bit
SX126x.PacketParams.Params.Gfsk.PreambleMinDetect = RADIO_PREAMBLE_DETECTOR_08_BITS;
SX126x.PacketParams.Params.Gfsk.SyncWordLength = 3 << 3 ; // convert byte into bit
SX126x.PacketParams.Params.Gfsk.AddrComp = RADIO_ADDRESSCOMP_FILT_OFF;
SX126x.PacketParams.Params.Gfsk.HeaderType = ( fixLen == true ) ? RADIO_PACKET_FIXED_LENGTH : RADIO_PACKET_VARIABLE_LENGTH;
if( crcOn == true )
{
SX126x.PacketParams.Params.Gfsk.CrcLength = RADIO_CRC_2_BYTES_CCIT;
}
else
{
SX126x.PacketParams.Params.Gfsk.CrcLength = RADIO_CRC_OFF;
}
SX126x.PacketParams.Params.Gfsk.DcFree = RADIO_DC_FREEWHITENING;
RadioStandby( );
RadioSetModem( ( SX126x.ModulationParams.PacketType == PACKET_TYPE_GFSK ) ? MODEM_FSK : MODEM_LORA );
SX126xSetModulationParams( &SX126x.ModulationParams );
SX126xSetPacketParams( &SX126x.PacketParams );
SX126xSetSyncWord( ( uint8_t[] ){ 0xC1, 0x94, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00 } );
SX126xSetWhiteningSeed( 0x01FF );
break;
case MODEM_LORA:
SX126x.ModulationParams.PacketType = PACKET_TYPE_LORA;
SX126x.ModulationParams.Params.LoRa.SpreadingFactor = ( RadioLoRaSpreadingFactors_t ) datarate;
SX126x.ModulationParams.Params.LoRa.Bandwidth = Bandwidths[bandwidth];
SX126x.ModulationParams.Params.LoRa.CodingRate= ( RadioLoRaCodingRates_t )coderate;
if( ( ( bandwidth == 0 ) && ( ( datarate == 11 ) || ( datarate == 12 ) ) ) ||
( ( bandwidth == 1 ) && ( datarate == 12 ) ) )
{
SX126x.ModulationParams.Params.LoRa.LowDatarateOptimize = 0x01;
}
else
{
SX126x.ModulationParams.Params.LoRa.LowDatarateOptimize = 0x00;
}
SX126x.PacketParams.PacketType = PACKET_TYPE_LORA;
if( ( SX126x.ModulationParams.Params.LoRa.SpreadingFactor == LORA_SF5 ) ||
( SX126x.ModulationParams.Params.LoRa.SpreadingFactor == LORA_SF6 ) )
{
if( preambleLen < 12 )
{
SX126x.PacketParams.Params.LoRa.PreambleLength = 12;
}
else
{
SX126x.PacketParams.Params.LoRa.PreambleLength = preambleLen;
}
}
else
{
SX126x.PacketParams.Params.LoRa.PreambleLength = preambleLen;
}
SX126x.PacketParams.Params.LoRa.HeaderType = ( RadioLoRaPacketLengthsMode_t )fixLen;
SX126x.PacketParams.Params.LoRa.PayloadLength = MaxPayloadLength;
SX126x.PacketParams.Params.LoRa.CrcMode = ( RadioLoRaCrcModes_t )crcOn;
SX126x.PacketParams.Params.LoRa.InvertIQ = ( RadioLoRaIQModes_t )iqInverted;
RadioStandby( );
RadioSetModem( ( SX126x.ModulationParams.PacketType == PACKET_TYPE_GFSK ) ? MODEM_FSK : MODEM_LORA );
SX126xSetModulationParams( &SX126x.ModulationParams );
SX126xSetPacketParams( &SX126x.PacketParams );
break;
}
// WORKAROUND - Modulation Quality with 500 kHz LoRa Bandwidth, see DS_SX1261-2_V1.2 datasheet chapter 15.1
if( ( modem == MODEM_LORA ) && ( SX126x.ModulationParams.Params.LoRa.Bandwidth == LORA_BW_500 ) )
{
// RegTxModulation = @address 0x0889
SX126xWriteRegister( 0x0889, SX126xReadRegister( 0x0889 ) & ~( 1 << 2 ) );
}
else
{
// RegTxModulation = @address 0x0889
SX126xWriteRegister( 0x0889, SX126xReadRegister( 0x0889 ) | ( 1 << 2 ) );
}
// WORKAROUND END
SX126xSetRfTxPower( power );
TxTimeout = timeout;
}
bool RadioCheckRfFrequency( uint32_t frequency )
{
return true;
}
static uint32_t RadioGetLoRaBandwidthInHz( RadioLoRaBandwidths_t bw )
{
uint32_t bandwidthInHz = 0;
switch( bw )
{
case LORA_BW_007:
bandwidthInHz = 7812UL;
break;
case LORA_BW_010:
bandwidthInHz = 10417UL;
break;
case LORA_BW_015:
bandwidthInHz = 15625UL;
break;
case LORA_BW_020:
bandwidthInHz = 20833UL;
break;
case LORA_BW_031:
bandwidthInHz = 31250UL;
break;
case LORA_BW_041:
bandwidthInHz = 41667UL;
break;
case LORA_BW_062:
bandwidthInHz = 62500UL;
break;
case LORA_BW_125:
bandwidthInHz = 125000UL;
break;
case LORA_BW_250:
bandwidthInHz = 250000UL;
break;
case LORA_BW_500:
bandwidthInHz = 500000UL;
break;
}
return bandwidthInHz;
}
static uint32_t RadioGetGfskTimeOnAirNumerator( uint32_t datarate, uint8_t coderate,
uint16_t preambleLen, bool fixLen, uint8_t payloadLen,
bool crcOn )
{
const RadioAddressComp_t addrComp = RADIO_ADDRESSCOMP_FILT_OFF;
const uint8_t syncWordLength = 3;
return ( preambleLen << 3 ) +
( ( fixLen == false ) ? 8 : 0 ) +
( syncWordLength << 3 ) +
( ( payloadLen +
( addrComp == RADIO_ADDRESSCOMP_FILT_OFF ? 0 : 1 ) +
( ( crcOn == true ) ? 2 : 0 )
) << 3
);
}
static uint32_t RadioGetLoRaTimeOnAirNumerator( uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint16_t preambleLen, bool fixLen, uint8_t payloadLen,
bool crcOn )
{
int32_t crDenom = coderate + 4;
bool lowDatareOptimize = false;
// Ensure that the preamble length is at least 12 symbols when using SF5 or
// SF6
if( ( datarate == 5 ) || ( datarate == 6 ) )
{
if( preambleLen < 12 )
{
preambleLen = 12;
}
}
if( ( ( bandwidth == 0 ) && ( ( datarate == 11 ) || ( datarate == 12 ) ) ) ||
( ( bandwidth == 1 ) && ( datarate == 12 ) ) )
{
lowDatareOptimize = true;
}
int32_t ceilDenominator;
int32_t ceilNumerator = ( payloadLen << 3 ) +
( crcOn ? 16 : 0 ) -
( 4 * datarate ) +
( fixLen ? 0 : 20 );
if( datarate <= 6 )
{
ceilDenominator = 4 * datarate;
}
else
{
ceilNumerator += 8;
if( lowDatareOptimize == true )
{
ceilDenominator = 4 * ( datarate - 2 );
}
else
{
ceilDenominator = 4 * datarate;
}
}
if( ceilNumerator < 0 )
{
ceilNumerator = 0;
}
// Perform integral ceil()
int32_t intermediate =
( ( ceilNumerator + ceilDenominator - 1 ) / ceilDenominator ) * crDenom + preambleLen + 12;
if( datarate <= 6 )
{
intermediate += 2;
}
return ( uint32_t )( ( 4 * intermediate + 1 ) * ( 1 << ( datarate - 2 ) ) );
}
uint32_t RadioTimeOnAir( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint16_t preambleLen, bool fixLen, uint8_t payloadLen,
bool crcOn )
{
uint32_t numerator = 0;
uint32_t denominator = 1;
switch( modem )
{
case MODEM_FSK:
{
numerator = 1000U * RadioGetGfskTimeOnAirNumerator( datarate, coderate,
preambleLen, fixLen,
payloadLen, crcOn );
denominator = datarate;
}
break;
case MODEM_LORA:
{
numerator = 1000U * RadioGetLoRaTimeOnAirNumerator( bandwidth, datarate,
coderate, preambleLen,
fixLen, payloadLen, crcOn );
denominator = RadioGetLoRaBandwidthInHz( Bandwidths[bandwidth] );
}
break;
}
// Perform integral ceil()
return ( numerator + denominator - 1 ) / denominator;
}
void RadioSend( uint8_t *buffer, uint8_t size )
{
SX126xSetDioIrqParams( IRQ_TX_DONE,
IRQ_TX_DONE,
IRQ_RADIO_NONE,
IRQ_RADIO_NONE );
if( SX126xGetPacketType( ) == PACKET_TYPE_LORA )
{
SX126x.PacketParams.Params.LoRa.PayloadLength = size;
}
else
{
SX126x.PacketParams.Params.Gfsk.PayloadLength = size;
}
SX126xSetPacketParams( &SX126x.PacketParams );
SX126xSendPayload( buffer, size, 0 );
}
void RadioSleep( void )
{
SleepParams_t params = { 0 };
params.Fields.WarmStart = 1;
SX126xSetSleep( params );
usleep( 2000 );
}
void RadioStandby( void )
{
SX126xSetStandby( STDBY_RC );
}
void RadioRx( uint32_t timeout )
{
SX126xSetDioIrqParams( IRQ_RX_DONE,
IRQ_RX_DONE,
IRQ_RADIO_NONE,
IRQ_RADIO_NONE );
if( RxContinuous == true )
{
SX126xSetRx( 0xFFFFFF ); // Rx Continuous
}
else
{
SX126xSetRx( RxTimeout << 6 );
}
}
void RadioRxBoosted( uint32_t timeout )
{
SX126xSetDioIrqParams( IRQ_RADIO_ALL, //IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT,
IRQ_RADIO_ALL, //IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT,
IRQ_RADIO_NONE,
IRQ_RADIO_NONE );
if( RxContinuous == true )
{
SX126xSetRxBoosted( 0xFFFFFF ); // Rx Continuous
}
else
{
SX126xSetRxBoosted( RxTimeout << 6 );
}
}
void RadioSetRxDutyCycle( uint32_t rxTime, uint32_t sleepTime )
{
SX126xSetRxDutyCycle( rxTime, sleepTime );
}
void RadioStartCad( void )
{
SX126xSetDioIrqParams( IRQ_CAD_DONE | IRQ_CAD_ACTIVITY_DETECTED, IRQ_CAD_DONE | IRQ_CAD_ACTIVITY_DETECTED, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
SX126xSetCad( );
}
void RadioSetTxContinuousWave( uint32_t freq, int8_t power, uint16_t time )
{
uint32_t timeout = ( uint32_t )time * 1000;
SX126xSetRfFrequency( freq );
SX126xSetRfTxPower( power );
SX126xSetTxContinuousWave( );
}
int16_t RadioRssi( RadioModems_t modem )
{
return SX126xGetRssiInst( );
}
void RadioWrite( uint32_t addr, uint8_t data )
{
SX126xWriteRegister( addr, data );
}
uint8_t RadioRead( uint32_t addr )
{
return SX126xReadRegister( addr );
}
void RadioWriteBuffer( uint32_t addr, uint8_t *buffer, uint8_t size )
{
SX126xWriteRegisters( addr, buffer, size );
}
void RadioReadBuffer( uint32_t addr, uint8_t *buffer, uint8_t size )
{
SX126xReadRegisters( addr, buffer, size );
}
void RadioSetMaxPayloadLength( RadioModems_t modem, uint8_t max )
{
if( modem == MODEM_LORA )
{
SX126x.PacketParams.Params.LoRa.PayloadLength = MaxPayloadLength = max;
SX126xSetPacketParams( &SX126x.PacketParams );
}
else
{
if( SX126x.PacketParams.Params.Gfsk.HeaderType == RADIO_PACKET_VARIABLE_LENGTH )
{
SX126x.PacketParams.Params.Gfsk.PayloadLength = MaxPayloadLength = max;
SX126xSetPacketParams( &SX126x.PacketParams );
}
}
}
void RadioSetPublicNetwork( bool enable )
{
RadioPublicNetwork.Current = RadioPublicNetwork.Previous = enable;
RadioSetModem( MODEM_LORA );
if( enable == true )
{
// Change LoRa modem SyncWord
SX126xWriteRegister( REG_LR_SYNCWORD, ( LORA_MAC_PUBLIC_SYNCWORD >> 8 ) & 0xFF );
SX126xWriteRegister( REG_LR_SYNCWORD + 1, LORA_MAC_PUBLIC_SYNCWORD & 0xFF );
}
else
{
// Change LoRa modem SyncWord
SX126xWriteRegister( REG_LR_SYNCWORD, ( LORA_MAC_PRIVATE_SYNCWORD >> 8 ) & 0xFF );
SX126xWriteRegister( REG_LR_SYNCWORD + 1, LORA_MAC_PRIVATE_SYNCWORD & 0xFF );
}
}
uint32_t RadioGetWakeupTime( void )
{
return SX126xGetBoardTcxoWakeupTime( ) + RADIO_WAKEUP_TIME;
}
void RadioOnTxTimeoutIrq( void* context )
{
if( ( RadioEvents != NULL ) && ( RadioEvents->TxTimeout != NULL ) )
{
RadioEvents->TxTimeout( );
}
}
void RadioOnRxTimeoutIrq( void* context )
{
if( ( RadioEvents != NULL ) && ( RadioEvents->RxTimeout != NULL ) )
{
RadioEvents->RxTimeout( );
}
}
void RadioOnDioIrq( void* context )
{
IrqFired = true;
}
void RadioIrqProcess( void )
{
uint8_t payload_offset, payload_size;
if( IrqFired == true )
{
// Clear IRQ flag
IrqFired = false;
uint16_t irqRegs = SX126xGetIrqStatus( );
SX126xClearIrqStatus( 0xFF );
if( ( irqRegs & IRQ_TX_DONE ) == IRQ_TX_DONE )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
if( ( RadioEvents != NULL ) && ( RadioEvents->TxDone != NULL ) )
{
RadioEvents->TxDone( );
}
}
if( ( irqRegs & IRQ_RX_DONE ) == IRQ_RX_DONE )
{
if( ( irqRegs & IRQ_CRC_ERROR ) == IRQ_CRC_ERROR )
{
if( RxContinuous == false )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
}
if( ( RadioEvents != NULL ) && ( RadioEvents->RxError ) )
{
RadioEvents->RxError( );
}
}
else
{
uint8_t size;
if( RxContinuous == false )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
// WORKAROUND - Implicit Header Mode Timeout Behavior, see DS_SX1261-2_V1.2 datasheet chapter 15.3
// RegRtcControl = @address 0x0902
SX126xWriteRegister( 0x0902, 0x00 );
// RegEventMask = @address 0x0944
SX126xWriteRegister( 0x0944, SX126xReadRegister( 0x0944 ) | ( 1 << 1 ) );
// WORKAROUND END
}
SX126xGetPayload( RadioRxPayload, &size , 255 );
SX126xGetPacketStatus( &RadioPktStatus );
if( ( RadioEvents != NULL ) && ( RadioEvents->RxDone != NULL ) )
{
RadioEvents->RxDone( RadioRxPayload, size, RadioPktStatus.Params.LoRa.RssiPkt, RadioPktStatus.Params.LoRa.SnrPkt );
}
}
}
if( ( irqRegs & IRQ_CAD_DONE ) == IRQ_CAD_DONE )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
if( ( RadioEvents != NULL ) && ( RadioEvents->CadDone != NULL ) )
{
RadioEvents->CadDone( ( ( irqRegs & IRQ_CAD_ACTIVITY_DETECTED ) == IRQ_CAD_ACTIVITY_DETECTED ) );
}
}
if( ( irqRegs & IRQ_RX_TX_TIMEOUT ) == IRQ_RX_TX_TIMEOUT )
{
if( SX126xGetOperatingMode( ) == MODE_TX )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
if( ( RadioEvents != NULL ) && ( RadioEvents->TxTimeout != NULL ) )
{
RadioEvents->TxTimeout( );
}
}
else if( SX126xGetOperatingMode( ) == MODE_RX )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
if( ( RadioEvents != NULL ) && ( RadioEvents->RxTimeout != NULL ) )
{
RadioEvents->RxTimeout( );
}
}
}
if( ( irqRegs & IRQ_PREAMBLE_DETECTED ) == IRQ_PREAMBLE_DETECTED )
{
//__NOP( );
}
if( ( irqRegs & IRQ_SYNCWORD_VALID ) == IRQ_SYNCWORD_VALID )
{
//__NOP( );
}
if( ( irqRegs & IRQ_HEADER_VALID ) == IRQ_HEADER_VALID )
{
//__NOP( );
}
if( ( irqRegs & IRQ_HEADER_ERROR ) == IRQ_HEADER_ERROR )
{
if( RxContinuous == false )
{
//!< Update operating mode state to a value lower than \ref MODE_STDBY_XOSC
SX126xSetOperatingMode( MODE_STDBY_RC );
}
if( ( RadioEvents != NULL ) && ( RadioEvents->RxTimeout != NULL ) )
{
RadioEvents->RxTimeout( );
}
}
}
}
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/radio.c
|
C
|
apache-2.0
| 42,006
|
/*!
* \file radio.h
*
* \brief Radio driver API definition
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#ifndef __RADIO_H__
#define __RADIO_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <stdbool.h>
/*!
* Radio driver supported modems
*/
typedef enum
{
MODEM_FSK = 0,
MODEM_LORA,
}RadioModems_t;
/*!
* Radio driver internal state machine states definition
*/
typedef enum
{
RF_IDLE = 0, //!< The radio is idle
RF_RX_RUNNING, //!< The radio is in reception state
RF_TX_RUNNING, //!< The radio is in transmission state
RF_CAD, //!< The radio is doing channel activity detection
}RadioState_t;
/*!
* \brief Radio driver callback functions
*/
typedef struct
{
/*!
* \brief Tx Done callback prototype.
*/
void ( *TxDone )( void );
/*!
* \brief Tx Timeout callback prototype.
*/
void ( *TxTimeout )( void );
/*!
* \brief Rx Done callback prototype.
*
* \param [IN] payload Received buffer pointer
* \param [IN] size Received buffer size
* \param [IN] rssi RSSI value computed while receiving the frame [dBm]
* \param [IN] snr SNR value computed while receiving the frame [dB]
* FSK : N/A ( set to 0 )
* LoRa: SNR value in dB
*/
void ( *RxDone )( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr );
/*!
* \brief Rx Timeout callback prototype.
*/
void ( *RxTimeout )( void );
/*!
* \brief Rx Error callback prototype.
*/
void ( *RxError )( void );
/*!
* \brief FHSS Change Channel callback prototype.
*
* \param [IN] currentChannel Index number of the current channel
*/
void ( *FhssChangeChannel )( uint8_t currentChannel );
/*!
* \brief CAD Done callback prototype.
*
* \param [IN] channelDetected Channel Activity detected during the CAD
*/
void ( *CadDone ) ( bool channelActivityDetected );
/*!
* \brief Gnss Done Done callback prototype.
*/
void ( *GnssDone )( void );
/*!
* \brief Gnss Done Done callback prototype.
*/
void ( *WifiDone )( void );
}RadioEvents_t;
/*!
* \brief Radio driver definition
*/
struct Radio_s
{
/*!
* \brief Initializes the radio
*
* \param [IN] events Structure containing the driver callback functions
*/
void ( *Init )( RadioEvents_t *events );
/*!
* Return current radio status
*
* \param status Radio status.[RF_IDLE, RF_RX_RUNNING, RF_TX_RUNNING]
*/
RadioState_t ( *GetStatus )( void );
/*!
* \brief Configures the radio with the given modem
*
* \param [IN] modem Modem to be used [0: FSK, 1: LoRa]
*/
void ( *SetModem )( RadioModems_t modem );
/*!
* \brief Sets the channel frequency
*
* \param [IN] freq Channel RF frequency
*/
void ( *SetChannel )( uint32_t freq );
/*!
* \brief Checks if the channel is free for the given time
*
* \remark The FSK modem is always used for this task as we can select the Rx bandwidth at will.
*
* \param [IN] freq Channel RF frequency in Hertz
* \param [IN] rxBandwidth Rx bandwidth in Hertz
* \param [IN] rssiThresh RSSI threshold in dBm
* \param [IN] maxCarrierSenseTime Max time in milliseconds while the RSSI is measured
*
* \retval isFree [true: Channel is free, false: Channel is not free]
*/
bool ( *IsChannelFree )( uint32_t freq, uint32_t rxBandwidth, int16_t rssiThresh, uint32_t maxCarrierSenseTime );
/*!
* \brief Generates a 32 bits random value based on the RSSI readings
*
* \remark This function sets the radio in LoRa modem mode and disables
* all interrupts.
* After calling this function either Radio.SetRxConfig or
* Radio.SetTxConfig functions must be called.
*
* \retval randomValue 32 bits random value
*/
uint32_t ( *Random )( void );
/*!
* \brief Sets the reception parameters
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] bandwidth Sets the bandwidth
* FSK : >= 2600 and <= 250000 Hz
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] bandwidthAfc Sets the AFC Bandwidth (FSK only)
* FSK : >= 2600 and <= 250000 Hz
* LoRa: N/A ( set to 0 )
* \param [IN] preambleLen Sets the Preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] symbTimeout Sets the RxSingle timeout value
* FSK : timeout in number of bytes
* LoRa: timeout in symbols
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] payloadLen Sets payload length when fixed length is used
* \param [IN] crcOn Enables/Disables the CRC [0: OFF, 1: ON]
* \param [IN] freqHopOn Enables disables the intra-packet frequency hopping
* FSK : N/A ( set to 0 )
* LoRa: [0: OFF, 1: ON]
* \param [IN] hopPeriod Number of symbols between each hop
* FSK : N/A ( set to 0 )
* LoRa: Number of symbols
* \param [IN] iqInverted Inverts IQ signals (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [0: not inverted, 1: inverted]
* \param [IN] rxContinuous Sets the reception in continuous mode
* [false: single mode, true: continuous mode]
*/
void ( *SetRxConfig )( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint32_t bandwidthAfc, uint16_t preambleLen,
uint16_t symbTimeout, bool fixLen,
uint8_t payloadLen,
bool crcOn, bool freqHopOn, uint8_t hopPeriod,
bool iqInverted, bool rxContinuous );
/*!
* \brief Sets the transmission parameters
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] power Sets the output power [dBm]
* \param [IN] fdev Sets the frequency deviation (FSK only)
* FSK : [Hz]
* LoRa: 0
* \param [IN] bandwidth Sets the bandwidth (LoRa only)
* FSK : 0
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] preambleLen Sets the preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] crcOn Enables disables the CRC [0: OFF, 1: ON]
* \param [IN] freqHopOn Enables disables the intra-packet frequency hopping
* FSK : N/A ( set to 0 )
* LoRa: [0: OFF, 1: ON]
* \param [IN] hopPeriod Number of symbols between each hop
* FSK : N/A ( set to 0 )
* LoRa: Number of symbols
* \param [IN] iqInverted Inverts IQ signals (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [0: not inverted, 1: inverted]
* \param [IN] timeout Transmission timeout [ms]
*/
void ( *SetTxConfig )( RadioModems_t modem, int8_t power, uint32_t fdev,
uint32_t bandwidth, uint32_t datarate,
uint8_t coderate, uint16_t preambleLen,
bool fixLen, bool crcOn, bool freqHopOn,
uint8_t hopPeriod, bool iqInverted, uint32_t timeout );
/*!
* \brief Checks if the given RF frequency is supported by the hardware
*
* \param [IN] frequency RF frequency to be checked
* \retval isSupported [true: supported, false: unsupported]
*/
bool ( *CheckRfFrequency )( uint32_t frequency );
/*!
* \brief Computes the packet time on air in ms for the given payload
*
* \Remark Can only be called once SetRxConfig or SetTxConfig have been called
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] bandwidth Sets the bandwidth
* FSK : >= 2600 and <= 250000 Hz
* LoRa: [0: 125 kHz, 1: 250 kHz,
* 2: 500 kHz, 3: Reserved]
* \param [IN] datarate Sets the Datarate
* FSK : 600..300000 bits/s
* LoRa: [6: 64, 7: 128, 8: 256, 9: 512,
* 10: 1024, 11: 2048, 12: 4096 chips]
* \param [IN] coderate Sets the coding rate (LoRa only)
* FSK : N/A ( set to 0 )
* LoRa: [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
* \param [IN] preambleLen Sets the Preamble length
* FSK : Number of bytes
* LoRa: Length in symbols (the hardware adds 4 more symbols)
* \param [IN] fixLen Fixed length packets [0: variable, 1: fixed]
* \param [IN] payloadLen Sets payload length when fixed length is used
* \param [IN] crcOn Enables/Disables the CRC [0: OFF, 1: ON]
*
* \retval airTime Computed airTime (ms) for the given packet payload length
*/
uint32_t ( *TimeOnAir )( RadioModems_t modem, uint32_t bandwidth,
uint32_t datarate, uint8_t coderate,
uint16_t preambleLen, bool fixLen, uint8_t payloadLen,
bool crcOn );
/*!
* \brief Sends the buffer of size. Prepares the packet to be sent and sets
* the radio in transmission
*
* \param [IN]: buffer Buffer pointer
* \param [IN]: size Buffer size
*/
void ( *Send )( uint8_t *buffer, uint8_t size );
/*!
* \brief Sets the radio in sleep mode
*/
void ( *Sleep )( void );
/*!
* \brief Sets the radio in standby mode
*/
void ( *Standby )( void );
/*!
* \brief Sets the radio in reception mode for the given time
* \param [IN] timeout Reception timeout [ms]
* [0: continuous, others timeout]
*/
void ( *Rx )( uint32_t timeout );
/*!
* \brief Start a Channel Activity Detection
*/
void ( *StartCad )( void );
/*!
* \brief Sets the radio in continuous wave transmission mode
*
* \param [IN]: freq Channel RF frequency
* \param [IN]: power Sets the output power [dBm]
* \param [IN]: time Transmission mode timeout [s]
*/
void ( *SetTxContinuousWave )( uint32_t freq, int8_t power, uint16_t time );
/*!
* \brief Reads the current RSSI value
*
* \retval rssiValue Current RSSI value in [dBm]
*/
int16_t ( *Rssi )( RadioModems_t modem );
/*!
* \brief Writes the radio register at the specified address
*
* \param [IN]: addr Register address
* \param [IN]: data New register value
*/
void ( *Write )( uint32_t addr, uint8_t data );
/*!
* \brief Reads the radio register at the specified address
*
* \param [IN]: addr Register address
* \retval data Register value
*/
uint8_t ( *Read )( uint32_t addr );
/*!
* \brief Writes multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [IN] buffer Buffer containing the new register's values
* \param [IN] size Number of registers to be written
*/
void ( *WriteBuffer )( uint32_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Reads multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [OUT] buffer Buffer where to copy the registers data
* \param [IN] size Number of registers to be read
*/
void ( *ReadBuffer )( uint32_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Sets the maximum payload length.
*
* \param [IN] modem Radio modem to be used [0: FSK, 1: LoRa]
* \param [IN] max Maximum payload length in bytes
*/
void ( *SetMaxPayloadLength )( RadioModems_t modem, uint8_t max );
/*!
* \brief Sets the network to public or private. Updates the sync byte.
*
* \remark Applies to LoRa modem only
*
* \param [IN] enable if true, it enables a public network
*/
void ( *SetPublicNetwork )( bool enable );
/*!
* \brief Gets the time required for the board plus radio to get out of sleep.[ms]
*
* \retval time Radio plus board wakeup time in ms.
*/
uint32_t ( *GetWakeupTime )( void );
/*!
* \brief Process radio irq
*/
void ( *IrqProcess )( void );
/*
* The next functions are available only on SX126x radios.
*/
/*!
* \brief Sets the radio in reception mode with Max LNA gain for the given time
*
* \remark Available on SX126x radios only.
*
* \param [IN] timeout Reception timeout [ms]
* [0: continuous, others timeout]
*/
void ( *RxBoosted )( uint32_t timeout );
/*!
* \brief Sets the Rx duty cycle management parameters
*
* \remark Available on SX126x radios only.
*
* \param [in] rxTime Structure describing reception timeout value
* \param [in] sleepTime Structure describing sleep timeout value
*/
void ( *SetRxDutyCycle ) ( uint32_t rxTime, uint32_t sleepTime );
};
/*!
* \brief Radio driver
*
* \remark This variable is defined and initialized in the specific radio
* board implementation
*/
extern const struct Radio_s Radio;
#ifdef __cplusplus
}
#endif
#endif // __RADIO_H__
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/radio.h
|
C
|
apache-2.0
| 16,114
|
/*!
* \file sx126x-board.h
*
* \brief Target board SX126x driver implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#ifndef __SX126x_BOARD_H__
#define __SX126x_BOARD_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <stdbool.h>
#include "sx126x.h"
/*!
* \brief Initializes the radio I/Os pins interface
*/
void SX126xIoInit( void );
/*!
* \brief Initializes DIO IRQ handlers
*
* \param [IN] irqHandlers Array containing the IRQ callback functions
*/
void SX126xIoIrqInit( DioIrqHandler dioIrq );
/*!
* \brief De-initializes the radio I/Os pins interface.
*
* \remark Useful when going in MCU low power modes
*/
void SX126xIoDeInit( void );
/*!
* \brief Initializes the TCXO power pin.
*/
void SX126xIoTcxoInit( void );
/*!
* \brief Initializes RF switch control pins.
*/
void SX126xIoRfSwitchInit( void );
/*!
* \brief Initializes the radio debug pins.
*/
void SX126xIoDbgInit( void );
/*!
* \brief HW Reset of the radio
*/
void SX126xReset( void );
/*!
* \brief Blocking loop to wait while the Busy pin in high
*/
void SX126xWaitOnBusy( void );
/*!
* \brief Wakes up the radio
*/
void SX126xWakeup( void );
/*!
* \brief Send a command that write data to the radio
*
* \param [in] opcode Opcode of the command
* \param [in] buffer Buffer to be send to the radio
* \param [in] size Size of the buffer to send
*/
void SX126xWriteCommand( RadioCommands_t opcode, uint8_t *buffer, uint16_t size );
/*!
* \brief Send a command that read data from the radio
*
* \param [in] opcode Opcode of the command
* \param [out] buffer Buffer holding data from the radio
* \param [in] size Size of the buffer
*
* \retval status Return command radio status
*/
uint8_t SX126xReadCommand( RadioCommands_t opcode, uint8_t *buffer, uint16_t size );
/*!
* \brief Write a single byte of data to the radio memory
*
* \param [in] address The address of the first byte to write in the radio
* \param [in] value The data to be written in radio's memory
*/
void SX126xWriteRegister( uint16_t address, uint8_t value );
/*!
* \brief Read a single byte of data from the radio memory
*
* \param [in] address The address of the first byte to write in the radio
*
* \retval value The value of the byte at the given address in radio's memory
*/
uint8_t SX126xReadRegister( uint16_t address );
/*!
* \brief Sets the radio output power.
*
* \param [IN] power Sets the RF output power
*/
void SX126xSetRfTxPower( int8_t power );
/*!
* \brief Gets the device ID
*
* \retval id Connected device ID
*/
uint8_t SX126xGetDeviceId( void );
/*!
* \brief Initializes the RF Switch I/Os pins interface
*/
void SX126xAntSwOn( void );
/*!
* \brief De-initializes the RF Switch I/Os pins interface
*
* \remark Needed to decrease the power consumption in MCU low power modes
*/
void SX126xAntSwOff( void );
/*!
* \brief Checks if the given RF frequency is supported by the hardware
*
* \param [IN] frequency RF frequency to be checked
* \retval isSupported [true: supported, false: unsupported]
*/
bool SX126xCheckRfFrequency( uint32_t frequency );
/*!
* \brief Gets the Defines the time required for the TCXO to wakeup [ms].
*
* \retval time Board TCXO wakeup time in ms.
*/
uint32_t SX126xGetBoardTcxoWakeupTime( void );
/*!
* \brief Gets the current Radio OperationMode variable
*
* \retval RadioOperatingModes_t last operating mode
*/
RadioOperatingModes_t SX126xGetOperatingMode( void );
/*!
* \brief Sets/Updates the current Radio OperationMode variable.
*
* \remark WARNING: This function is only required to reflect the current radio
* operating mode when processing interrupts.
*
* \param [in] mode New operating mode
*/
void SX126xSetOperatingMode( RadioOperatingModes_t mode );
/*!
* Radio hardware and global parameters
*/
extern SX126x_t SX126x;
#ifdef __cplusplus
}
#endif
#endif // __SX126x_BOARD_H__
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/sx126x-board.h
|
C
|
apache-2.0
| 4,563
|
/*!
* \file sx1261mbxbas-board.c
*
* \brief Target board SX1261MBXBAS shield driver implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#include <stdlib.h>
#include <string.h>
#include "board.h"
#include "radio.h"
#include "ulog/ulog.h"
#include "sx126x-board.h"
#include <drivers/u_ld.h>
#include <vfsdev/spi_dev.h>
#include <vfsdev/gpio_dev.h>
#include <devicevfs/devicevfs.h>
#include <drivers/char/u_device.h>
#include "aos/hal/gpio.h"
/*!
* \brief Holds the internal operating mode of the radio
*/
static RadioOperatingModes_t OperatingMode;
static int g_gpio_fd = 0;
#define NSS_CRT(up) if (up == 1) { \
SX126x.NSS.data = 1; \
ioctl(g_gpio_fd, IOC_GPIO_SET, (unsigned long)&SX126x.NSS); \
} else if (up == 0) { \
SX126x.NSS.data = 0; \
ioctl(g_gpio_fd, IOC_GPIO_SET, (unsigned long)&SX126x.NSS); \
} else { \
LOG("invalid nss ctr\n"); \
}
#define SPI_SANITY_CHECK(ret) if(ret) {LOG("[%s][%d]spi err(%d)", __func__, __LINE__, ret); return;}
#define CRITICAL_SECTION_BEGIN()
#define CRITICAL_SECTION_END()
void SX126xIoInit( void )
{
memset(&SX126x, 0, sizeof(SX126x_t));
SX126x.Spi = open("/dev/spi0", 0);
if (SX126x.Spi <= 0) {
LOG("[%s][%d]faild to open spi device!", __FUNCTION__, __LINE__);
return;
} else {
LOG("[%s][%d]succeed to open spi device(%d)!", __FUNCTION__, __LINE__, SX126x.Spi);
}
int ret = ioctl(SX126x.Spi, IOC_SPI_SET_CFLAG, SPI_NO_CS | SPI_MODE_3 | SPI_MSB | SPI_TRANSFER_NORMAL_MODE | SPI_DATA_8BIT);
SPI_SANITY_CHECK(ret);
ret = ioctl(SX126x.Spi, IOC_SPI_SET_FREQ, 2000000);
SPI_SANITY_CHECK(ret);
g_gpio_fd = open("/dev/gpio", 0);
SX126x.NSS.id = 22; //p2-6
SX126x.NSS.config = GPIO_IO_OUTPUT | GPIO_IO_OUTPUT_PP;
SX126x.Reset.id = 33; //p4-1
SX126x.Reset.config=GPIO_IO_OUTPUT | GPIO_IO_OUTPUT_PP;
SX126x.DIO1.id = 32; //p4-0
SX126x.BUSY.id = 39; //p4-7
SX126x.BUSY.data = 0;
SX126x.BUSY.config=GPIO_IO_INPUT | GPIO_IO_INPUT_PD;
}
void SX126xIoIrqInit( DioIrqHandler dioIrq )
{
SX126x.DIO1.config = GPIO_IRQ_CLEAR;
int ret = ioctl(g_gpio_fd, IOC_GPIO_SET_IRQ, &SX126x.DIO1);
if (ret) {
LOG("clear gpio irq failed, ret %d", ret);
return;
}
SX126x.DIO1.config = GPIO_IRQ_DISABLE;
ret = ioctl(g_gpio_fd, IOC_GPIO_SET_IRQ, &SX126x.DIO1);
if (ret) {
LOG("clear gpio irq failed, ret %d", ret);
return;
}
SX126x.DIO1.config = GPIO_IRQ_ENABLE | GPIO_IRQ_EDGE_RISING;
SX126x.DIO1.cb = dioIrq;
SX126x.DIO1.arg = NULL;
ret = ioctl(g_gpio_fd, IOC_GPIO_SET_IRQ, &SX126x.DIO1);
if (ret) {
LOG("enable gpio irq failed, ret %d", ret);
return -1;
}
}
void SX126xIoDeInit( void )
{
}
void SX126xIoDbgInit( void )
{
}
void SX126xIoTcxoInit( void )
{
// No TCXO component available on this board design.
}
uint32_t SX126xGetBoardTcxoWakeupTime( void )
{
return 0;
}
void SX126xIoRfSwitchInit( void )
{
SX126xSetDio2AsRfSwitchCtrl( true );
}
RadioOperatingModes_t SX126xGetOperatingMode( void )
{
return OperatingMode;
}
void SX126xSetOperatingMode( RadioOperatingModes_t mode )
{
OperatingMode = mode;
}
void SX126xReset( void )
{
SX126x.Reset.data = 0;
ioctl(g_gpio_fd, IOC_GPIO_SET, (unsigned long)&SX126x.Reset);
usleep(500000);
SX126x.Reset.data = 1;
ioctl(g_gpio_fd, IOC_GPIO_SET, (unsigned long)&SX126x.Reset);
}
void SX126xWaitOnBusy( void )
{
int32_t ret = 0;
uint32_t busy = 1;
while(0 == ret) {
if (busy) {
usleep(5000);
} else {
break;
}
busy = ioctl(g_gpio_fd, IOC_GPIO_GET, (unsigned long)&SX126x.BUSY);
}
}
uint8_t SpiInOut(uint8_t cmd) {
uint8_t ack = 0;
ioc_spi_transfer_t t = {.rx_buf = &ack, .rx_size = 1, .tx_buf = &cmd, .tx_size = 1};
int ret = ioctl(SX126x.Spi, IOC_SPI_SEND_RECV, &t);
SPI_SANITY_CHECK(ret)
return ack;
}
void SpiOut(uint8_t cmd) {
write(SX126x.Spi, &cmd, 1);
usleep(10);
}
void SpiIn(uint8_t *ack) {
read(SX126x.Spi, ack, 1);
}
void SX126xWakeup( void )
{
CRITICAL_SECTION_BEGIN( );
int32_t ret = 0;
NSS_CRT( 0 );
SpiOut( RADIO_GET_STATUS );
RadioStatus_t status = (RadioStatus_t)SpiInOut( 0x00 );
// LOG("[%s]chip mode:%d command status:%d\n", __func__, status.Fields.ChipMode, status.Fields.CmdStatus);
NSS_CRT( 1 );
// Wait for chip to be ready.
SX126xWaitOnBusy( );
// Update operating mode context variable
SX126xSetOperatingMode( MODE_STDBY_RC );
CRITICAL_SECTION_END( );
}
void SX126xWriteCommand( RadioCommands_t command, uint8_t *buffer, uint16_t size )
{
int32_t ret = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( ( uint8_t )command );
for( uint16_t i = 0; i < size; i++ )
{
SpiOut( buffer[i] );
}
NSS_CRT( 1 );
if( command != RADIO_SET_SLEEP )
{
SX126xWaitOnBusy( );
}
}
uint8_t SX126xReadCommand( RadioCommands_t command, uint8_t *buffer, uint16_t size )
{
int32_t ret = 0;
uint8_t status = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( ( uint8_t )command );
if (command == RADIO_GET_STATUS)
{
status = SpiInOut( 0x00 );
}
else
{
SpiOut( 0x00 );
}
for( uint16_t i = 0; i < size; i++ )
{
if (command == RADIO_GET_RXBUFFERSTATUS) {
SpiIn( buffer+i );
} else {
buffer[i] = SpiInOut( 0 );
}
}
NSS_CRT( 1 );
SX126xWaitOnBusy( );
return status;
}
void SX126xWriteRegisters( uint16_t address, uint8_t *buffer, uint16_t size )
{
int32_t ret = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( RADIO_WRITE_REGISTER );
SpiOut( ( address & 0xFF00 ) >> 8 );
SpiOut( address & 0x00FF );
for( uint16_t i = 0; i < size; i++ )
{
SpiOut( buffer[i] );
}
NSS_CRT( 1 );
SX126xWaitOnBusy( );
}
void SX126xWriteRegister( uint16_t address, uint8_t value )
{
SX126xWriteRegisters( address, &value, 1 );
}
void SX126xReadRegisters( uint16_t address, uint8_t *buffer, uint16_t size )
{
int32_t ret = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( RADIO_READ_REGISTER );
SpiOut( ( address & 0xFF00 ) >> 8 );
SpiOut( address & 0x00FF );
SpiOut( 0 );
for( uint16_t i = 0; i < size; i++ )
{
//buffer[i] = SpiInOut( 0 );
SpiIn(buffer+i);
}
NSS_CRT( 1 );
SX126xWaitOnBusy( );
}
uint8_t SX126xReadRegister( uint16_t address )
{
uint8_t data;
SX126xReadRegisters( address, &data, 1 );
return data;
}
void SX126xWriteBuffer( uint8_t offset, uint8_t *buffer, uint8_t size )
{
int32_t ret = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( RADIO_WRITE_BUFFER );
SpiOut( offset );
for( uint16_t i = 0; i < size; i++ )
{
SpiOut( buffer[i] );
}
NSS_CRT( 1 );
SX126xWaitOnBusy( );
}
void SX126xReadBuffer( uint8_t offset, uint8_t *buffer, uint8_t size )
{
int32_t ret = 0;
SX126xCheckDeviceReady( );
NSS_CRT( 0 );
SpiOut( RADIO_READ_BUFFER );
SpiOut( offset );
SpiOut( 0 );
for( uint16_t i = 0; i < size; i++ )
{
SpiIn(buffer+i);
}
NSS_CRT( 1 );
SX126xWaitOnBusy( );
}
void SX126xSetRfTxPower( int8_t power )
{
SX126xSetTxParams( power, RADIO_RAMP_40_US );
}
uint8_t SX126xGetDeviceId( void )
{
return SX1262;
}
void SX126xAntSwOn( void )
{
}
void SX126xAntSwOff( void )
{
}
bool SX126xCheckRfFrequency( uint32_t frequency )
{
// Implement check. Currently all frequencies are supported
return true;
}
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/sx126x-haas.c
|
C
|
apache-2.0
| 8,674
|
/*!
* \file sx126x.c
*
* \brief SX126x driver implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#include <string.h>
#include "radio.h"
#include "sx126x.h"
#include "sx126x-board.h"
#include "ulog/ulog.h"
/*!
* \brief Radio registers definition
*/
typedef struct
{
uint16_t Addr; //!< The address of the register
uint8_t Value; //!< The value of the register
}RadioRegisters_t;
/*!
* \brief Stores the current packet type set in the radio
*/
static RadioPacketTypes_t PacketType;
/*!
* \brief Stores the current packet header type set in the radio
*/
static volatile RadioLoRaPacketLengthsMode_t LoRaHeaderType;
/*!
* \brief Stores the last frequency error measured on LoRa received packet
*/
volatile uint32_t FrequencyError = 0;
/*!
* \brief Hold the status of the Image calibration
*/
static bool ImageCalibrated = false;
/*
* SX126x DIO IRQ callback functions prototype
*/
/*!
* \brief DIO 0 IRQ callback
*/
void SX126xOnDioIrq( void );
/*!
* \brief DIO 0 IRQ callback
*/
void SX126xSetPollingMode( void );
/*!
* \brief DIO 0 IRQ callback
*/
void SX126xSetInterruptMode( void );
/*
* \brief Process the IRQ if handled by the driver
*/
void SX126xProcessIrqs( void );
void SX126xInit( DioIrqHandler dioIrq )
{
SX126xIoInit( );
SX126xReset( );
SX126xIoIrqInit( dioIrq );
SX126xWakeup( );
SX126xSetStandby( STDBY_RC );
// Initialize TCXO control
SX126xIoTcxoInit( );
// Initialize RF switch control
SX126xIoRfSwitchInit( );
SX126xSetOperatingMode( MODE_STDBY_RC );
}
void SX126xCheckDeviceReady( void )
{
if( ( SX126xGetOperatingMode( ) == MODE_SLEEP ) || ( SX126xGetOperatingMode( ) == MODE_RX_DC ) )
{
SX126xWakeup( );
// Switch is turned off when device is in sleep mode and turned on is all other modes
SX126xAntSwOn( );
}
SX126xWaitOnBusy( );
}
void SX126xSetPayload( uint8_t *payload, uint8_t size )
{
SX126xWriteBuffer( 0x00, payload, size );
}
uint8_t SX126xGetPayload( uint8_t *buffer, uint8_t *size, uint8_t maxSize )
{
uint8_t offset = 0;
SX126xGetRxBufferStatus( size, &offset );
if( *size > maxSize )
{
return 1;
}
SX126xReadBuffer( offset, buffer, *size );
return 0;
}
void SX126xSendPayload( uint8_t *payload, uint8_t size, uint32_t timeout )
{
SX126xSetPayload( payload, size );
SX126xSetTx( timeout );
}
uint8_t SX126xSetSyncWord( uint8_t *syncWord )
{
SX126xWriteRegisters( REG_LR_SYNCWORDBASEADDRESS, syncWord, 8 );
return 0;
}
void SX126xSetCrcSeed( uint16_t seed )
{
uint8_t buf[2];
buf[0] = ( uint8_t )( ( seed >> 8 ) & 0xFF );
buf[1] = ( uint8_t )( seed & 0xFF );
switch( SX126xGetPacketType( ) )
{
case PACKET_TYPE_GFSK:
SX126xWriteRegisters( REG_LR_CRCSEEDBASEADDR, buf, 2 );
break;
default:
break;
}
}
void SX126xSetCrcPolynomial( uint16_t polynomial )
{
uint8_t buf[2];
buf[0] = ( uint8_t )( ( polynomial >> 8 ) & 0xFF );
buf[1] = ( uint8_t )( polynomial & 0xFF );
switch( SX126xGetPacketType( ) )
{
case PACKET_TYPE_GFSK:
SX126xWriteRegisters( REG_LR_CRCPOLYBASEADDR, buf, 2 );
break;
default:
break;
}
}
void SX126xSetWhiteningSeed( uint16_t seed )
{
uint8_t regValue = 0;
switch( SX126xGetPacketType( ) )
{
case PACKET_TYPE_GFSK:
regValue = SX126xReadRegister( REG_LR_WHITSEEDBASEADDR_MSB ) & 0xFE;
regValue = ( ( seed >> 8 ) & 0x01 ) | regValue;
SX126xWriteRegister( REG_LR_WHITSEEDBASEADDR_MSB, regValue ); // only 1 bit.
SX126xWriteRegister( REG_LR_WHITSEEDBASEADDR_LSB, ( uint8_t )seed );
break;
default:
break;
}
}
uint32_t SX126xGetRandom( void )
{
uint32_t number = 0;
uint8_t regAnaLna = 0;
uint8_t regAnaMixer = 0;
regAnaLna = SX126xReadRegister( REG_ANA_LNA );
SX126xWriteRegister( REG_ANA_LNA, regAnaLna & ~( 1 << 0 ) );
regAnaMixer = SX126xReadRegister( REG_ANA_MIXER );
SX126xWriteRegister( REG_ANA_MIXER, regAnaMixer & ~( 1 << 7 ) );
// Set radio in continuous reception
SX126xSetRx( 0xFFFFFF ); // Rx Continuous
SX126xReadRegisters( RANDOM_NUMBER_GENERATORBASEADDR, ( uint8_t* )&number, 4 );
SX126xSetStandby( STDBY_RC );
SX126xWriteRegister( REG_ANA_LNA, regAnaLna );
SX126xWriteRegister( REG_ANA_MIXER, regAnaMixer );
return number;
}
void SX126xSetSleep( SleepParams_t sleepConfig )
{
SX126xAntSwOff( );
uint8_t value = ( ( ( uint8_t )sleepConfig.Fields.WarmStart << 2 ) |
( ( uint8_t )sleepConfig.Fields.Reset << 1 ) |
( ( uint8_t )sleepConfig.Fields.WakeUpRTC ) );
SX126xWriteCommand( RADIO_SET_SLEEP, &value, 1 );
SX126xSetOperatingMode( MODE_SLEEP );
}
void SX126xSetStandby( RadioStandbyModes_t standbyConfig )
{
SX126xWriteCommand( RADIO_SET_STANDBY, ( uint8_t* )&standbyConfig, 1 );
if( standbyConfig == STDBY_RC )
{
SX126xSetOperatingMode( MODE_STDBY_RC );
}
else
{
SX126xSetOperatingMode( MODE_STDBY_XOSC );
}
}
void SX126xSetFs( void )
{
SX126xWriteCommand( RADIO_SET_FS, 0, 0 );
SX126xSetOperatingMode( MODE_FS );
}
void SX126xSetTx( uint32_t timeout )
{
uint8_t buf[3];
SX126xSetOperatingMode( MODE_TX );
buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
buf[2] = ( uint8_t )( timeout & 0xFF );
SX126xWriteCommand( RADIO_SET_TX, buf, 3 );
}
void SX126xSetRx( uint32_t timeout )
{
uint8_t buf[3];
SX126xSetOperatingMode( MODE_RX );
buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
buf[2] = ( uint8_t )( timeout & 0xFF );
SX126xWriteCommand( RADIO_SET_RX, buf, 3 );
}
void SX126xSetRxBoosted( uint32_t timeout )
{
uint8_t buf[3];
SX126xSetOperatingMode( MODE_RX );
SX126xWriteRegister( REG_RX_GAIN, 0x96 ); // max LNA gain, increase current by ~2mA for around ~3dB in sensivity
buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
buf[2] = ( uint8_t )( timeout & 0xFF );
SX126xWriteCommand( RADIO_SET_RX, buf, 3 );
}
void SX126xSetRxDutyCycle( uint32_t rxTime, uint32_t sleepTime )
{
uint8_t buf[6];
buf[0] = ( uint8_t )( ( rxTime >> 16 ) & 0xFF );
buf[1] = ( uint8_t )( ( rxTime >> 8 ) & 0xFF );
buf[2] = ( uint8_t )( rxTime & 0xFF );
buf[3] = ( uint8_t )( ( sleepTime >> 16 ) & 0xFF );
buf[4] = ( uint8_t )( ( sleepTime >> 8 ) & 0xFF );
buf[5] = ( uint8_t )( sleepTime & 0xFF );
SX126xWriteCommand( RADIO_SET_RXDUTYCYCLE, buf, 6 );
SX126xSetOperatingMode( MODE_RX_DC );
}
void SX126xSetCad( void )
{
SX126xWriteCommand( RADIO_SET_CAD, 0, 0 );
SX126xSetOperatingMode( MODE_CAD );
}
void SX126xSetTxContinuousWave( void )
{
SX126xWriteCommand( RADIO_SET_TXCONTINUOUSWAVE, 0, 0 );
SX126xSetOperatingMode( MODE_TX );
}
void SX126xSetTxInfinitePreamble( void )
{
SX126xWriteCommand( RADIO_SET_TXCONTINUOUSPREAMBLE, 0, 0 );
SX126xSetOperatingMode( MODE_TX );
}
void SX126xSetStopRxTimerOnPreambleDetect( bool enable )
{
SX126xWriteCommand( RADIO_SET_STOPRXTIMERONPREAMBLE, ( uint8_t* )&enable, 1 );
}
void SX126xSetLoRaSymbNumTimeout( uint8_t symbNum )
{
SX126xWriteCommand( RADIO_SET_LORASYMBTIMEOUT, &symbNum, 1 );
if( symbNum >= 64 )
{
uint8_t mant = symbNum >> 1;
uint8_t exp = 0;
uint8_t reg = 0;
while( mant > 31 )
{
mant >>= 2;
exp++;
}
reg = exp + ( mant << 3 );
SX126xWriteRegister( REG_LR_SYNCH_TIMEOUT, reg );
}
}
void SX126xSetRegulatorMode( RadioRegulatorMode_t mode )
{
SX126xWriteCommand( RADIO_SET_REGULATORMODE, ( uint8_t* )&mode, 1 );
}
void SX126xCalibrate( CalibrationParams_t calibParam )
{
uint8_t value = ( ( ( uint8_t )calibParam.Fields.ImgEnable << 6 ) |
( ( uint8_t )calibParam.Fields.ADCBulkPEnable << 5 ) |
( ( uint8_t )calibParam.Fields.ADCBulkNEnable << 4 ) |
( ( uint8_t )calibParam.Fields.ADCPulseEnable << 3 ) |
( ( uint8_t )calibParam.Fields.PLLEnable << 2 ) |
( ( uint8_t )calibParam.Fields.RC13MEnable << 1 ) |
( ( uint8_t )calibParam.Fields.RC64KEnable ) );
SX126xWriteCommand( RADIO_CALIBRATE, &value, 1 );
}
void SX126xCalibrateImage( uint32_t freq )
{
uint8_t calFreq[2];
if( freq > 900000000 )
{
calFreq[0] = 0xE1;
calFreq[1] = 0xE9;
}
else if( freq > 850000000 )
{
calFreq[0] = 0xD7;
calFreq[1] = 0xDB;
}
else if( freq > 770000000 )
{
calFreq[0] = 0xC1;
calFreq[1] = 0xC5;
}
else if( freq > 460000000 )
{
calFreq[0] = 0x75;
calFreq[1] = 0x81;
}
else if( freq > 425000000 )
{
calFreq[0] = 0x6B;
calFreq[1] = 0x6F;
}
SX126xWriteCommand( RADIO_CALIBRATEIMAGE, calFreq, 2 );
}
void SX126xSetPaConfig( uint8_t paDutyCycle, uint8_t hpMax, uint8_t deviceSel, uint8_t paLut )
{
uint8_t buf[4];
buf[0] = paDutyCycle;
buf[1] = hpMax;
buf[2] = deviceSel;
buf[3] = paLut;
SX126xWriteCommand( RADIO_SET_PACONFIG, buf, 4 );
}
void SX126xSetRxTxFallbackMode( uint8_t fallbackMode )
{
SX126xWriteCommand( RADIO_SET_TXFALLBACKMODE, &fallbackMode, 1 );
}
void SX126xSetDioIrqParams( uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask, uint16_t dio3Mask )
{
uint8_t buf[8];
buf[0] = ( uint8_t )( ( irqMask >> 8 ) & 0x00FF );
buf[1] = ( uint8_t )( irqMask & 0x00FF );
buf[2] = ( uint8_t )( ( dio1Mask >> 8 ) & 0x00FF );
buf[3] = ( uint8_t )( dio1Mask & 0x00FF );
buf[4] = ( uint8_t )( ( dio2Mask >> 8 ) & 0x00FF );
buf[5] = ( uint8_t )( dio2Mask & 0x00FF );
buf[6] = ( uint8_t )( ( dio3Mask >> 8 ) & 0x00FF );
buf[7] = ( uint8_t )( dio3Mask & 0x00FF );
SX126xWriteCommand( RADIO_CFG_DIOIRQ, buf, 8 );
}
uint16_t SX126xGetIrqStatus( void )
{
uint8_t irqStatus[5] = {0}; //irqNo, irqMask, dio0Mask, dio1Mask, dio2Mask
uint8_t status = SX126xReadCommand( RADIO_GET_IRQSTATUS, irqStatus, sizeof(irqStatus) );
/*
LOG("cmdStatus:%d, irqNo:0x%02x, irqMask:0x%02x, dio0Mask:0x%02x, dio1Mask:0x%02x, dio2Mask:0x%02x", status, irqStatus[0]
, irqStatus[1], irqStatus[2]
, irqStatus[3], irqStatus[4]);
*/
return irqStatus[0];
}
void SX126xSetDio2AsRfSwitchCtrl( uint8_t enable )
{
SX126xWriteCommand( RADIO_SET_RFSWITCHMODE, &enable, 1 );
}
void SX126xSetDio3AsTcxoCtrl( RadioTcxoCtrlVoltage_t tcxoVoltage, uint32_t timeout )
{
uint8_t buf[4];
buf[0] = tcxoVoltage & 0x07;
buf[1] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
buf[2] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
buf[3] = ( uint8_t )( timeout & 0xFF );
SX126xWriteCommand( RADIO_SET_TCXOMODE, buf, 4 );
}
void SX126xSetRfFrequency( uint32_t frequency )
{
uint8_t buf[4];
uint32_t freq = 0;
if( ImageCalibrated == false )
{
SX126xCalibrateImage( frequency );
ImageCalibrated = true;
}
freq = ( uint32_t )( ( double )frequency / ( double )FREQ_STEP );
buf[0] = ( uint8_t )( ( freq >> 24 ) & 0xFF );
buf[1] = ( uint8_t )( ( freq >> 16 ) & 0xFF );
buf[2] = ( uint8_t )( ( freq >> 8 ) & 0xFF );
buf[3] = ( uint8_t )( freq & 0xFF );
SX126xWriteCommand( RADIO_SET_RFFREQUENCY, buf, 4 );
}
void SX126xSetPacketType( RadioPacketTypes_t packetType )
{
// Save packet type internally to avoid questioning the radio
PacketType = packetType;
SX126xWriteCommand( RADIO_SET_PACKETTYPE, ( uint8_t* )&packetType, 1 );
}
RadioPacketTypes_t SX126xGetPacketType( void )
{
return PacketType;
}
void SX126xSetTxParams( int8_t power, RadioRampTimes_t rampTime )
{
uint8_t buf[2];
if( SX126xGetDeviceId( ) == SX1261 )
{
if( power == 15 )
{
SX126xSetPaConfig( 0x06, 0x00, 0x01, 0x01 );
}
else
{
SX126xSetPaConfig( 0x04, 0x00, 0x01, 0x01 );
}
if( power >= 14 )
{
power = 14;
}
else if( power < -17 )
{
power = -17;
}
}
else // sx1262
{
// WORKAROUND - Better Resistance of the SX1262 Tx to Antenna Mismatch, see DS_SX1261-2_V1.2 datasheet chapter 15.2
// RegTxClampConfig = @address 0x08D8
SX126xWriteRegister( 0x08D8, SX126xReadRegister( 0x08D8 ) | ( 0x0F << 1 ) );
// WORKAROUND END
SX126xSetPaConfig( 0x04, 0x07, 0x00, 0x01 );
if( power > 22 )
{
power = 22;
}
else if( power < -9 )
{
power = -9;
}
}
buf[0] = power;
buf[1] = ( uint8_t )rampTime;
SX126xWriteCommand( RADIO_SET_TXPARAMS, buf, 2 );
}
void SX126xSetModulationParams( ModulationParams_t *modulationParams )
{
uint8_t n;
uint32_t tempVal = 0;
uint8_t buf[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
// Check if required configuration corresponds to the stored packet type
// If not, silently update radio packet type
if( PacketType != modulationParams->PacketType )
{
SX126xSetPacketType( modulationParams->PacketType );
}
switch( modulationParams->PacketType )
{
case PACKET_TYPE_GFSK:
n = 8;
tempVal = ( uint32_t )( 32 * ( ( double )XTAL_FREQ / ( double )modulationParams->Params.Gfsk.BitRate ) );
buf[0] = ( tempVal >> 16 ) & 0xFF;
buf[1] = ( tempVal >> 8 ) & 0xFF;
buf[2] = tempVal & 0xFF;
buf[3] = modulationParams->Params.Gfsk.ModulationShaping;
buf[4] = modulationParams->Params.Gfsk.Bandwidth;
tempVal = ( uint32_t )( ( double )modulationParams->Params.Gfsk.Fdev / ( double )FREQ_STEP );
buf[5] = ( tempVal >> 16 ) & 0xFF;
buf[6] = ( tempVal >> 8 ) & 0xFF;
buf[7] = ( tempVal& 0xFF );
SX126xWriteCommand( RADIO_SET_MODULATIONPARAMS, buf, n );
break;
case PACKET_TYPE_LORA:
n = 4;
buf[0] = modulationParams->Params.LoRa.SpreadingFactor;
buf[1] = modulationParams->Params.LoRa.Bandwidth;
buf[2] = modulationParams->Params.LoRa.CodingRate;
buf[3] = modulationParams->Params.LoRa.LowDatarateOptimize;
SX126xWriteCommand( RADIO_SET_MODULATIONPARAMS, buf, n );
break;
default:
case PACKET_TYPE_NONE:
return;
}
}
void SX126xSetPacketParams( PacketParams_t *packetParams )
{
uint8_t n;
uint8_t crcVal = 0;
uint8_t buf[9] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
// Check if required configuration corresponds to the stored packet type
// If not, silently update radio packet type
if( PacketType != packetParams->PacketType )
{
SX126xSetPacketType( packetParams->PacketType );
}
switch( packetParams->PacketType )
{
case PACKET_TYPE_GFSK:
if( packetParams->Params.Gfsk.CrcLength == RADIO_CRC_2_BYTES_IBM )
{
SX126xSetCrcSeed( CRC_IBM_SEED );
SX126xSetCrcPolynomial( CRC_POLYNOMIAL_IBM );
crcVal = RADIO_CRC_2_BYTES;
}
else if( packetParams->Params.Gfsk.CrcLength == RADIO_CRC_2_BYTES_CCIT )
{
SX126xSetCrcSeed( CRC_CCITT_SEED );
SX126xSetCrcPolynomial( CRC_POLYNOMIAL_CCITT );
crcVal = RADIO_CRC_2_BYTES_INV;
}
else
{
crcVal = packetParams->Params.Gfsk.CrcLength;
}
n = 9;
buf[0] = ( packetParams->Params.Gfsk.PreambleLength >> 8 ) & 0xFF;
buf[1] = packetParams->Params.Gfsk.PreambleLength;
buf[2] = packetParams->Params.Gfsk.PreambleMinDetect;
buf[3] = ( packetParams->Params.Gfsk.SyncWordLength /*<< 3*/ ); // convert from byte to bit
buf[4] = packetParams->Params.Gfsk.AddrComp;
buf[5] = packetParams->Params.Gfsk.HeaderType;
buf[6] = packetParams->Params.Gfsk.PayloadLength;
buf[7] = crcVal;
buf[8] = packetParams->Params.Gfsk.DcFree;
break;
case PACKET_TYPE_LORA:
n = 6;
buf[0] = ( packetParams->Params.LoRa.PreambleLength >> 8 ) & 0xFF;
buf[1] = packetParams->Params.LoRa.PreambleLength;
buf[2] = LoRaHeaderType = packetParams->Params.LoRa.HeaderType;
buf[3] = packetParams->Params.LoRa.PayloadLength;
buf[4] = packetParams->Params.LoRa.CrcMode;
buf[5] = packetParams->Params.LoRa.InvertIQ;
break;
default:
case PACKET_TYPE_NONE:
return;
}
SX126xWriteCommand( RADIO_SET_PACKETPARAMS, buf, n );
}
void SX126xSetCadParams( RadioLoRaCadSymbols_t cadSymbolNum, uint8_t cadDetPeak, uint8_t cadDetMin, RadioCadExitModes_t cadExitMode, uint32_t cadTimeout )
{
uint8_t buf[7];
buf[0] = ( uint8_t )cadSymbolNum;
buf[1] = cadDetPeak;
buf[2] = cadDetMin;
buf[3] = ( uint8_t )cadExitMode;
buf[4] = ( uint8_t )( ( cadTimeout >> 16 ) & 0xFF );
buf[5] = ( uint8_t )( ( cadTimeout >> 8 ) & 0xFF );
buf[6] = ( uint8_t )( cadTimeout & 0xFF );
SX126xWriteCommand( RADIO_SET_CADPARAMS, buf, 7 );
SX126xSetOperatingMode( MODE_CAD );
}
void SX126xSetBufferBaseAddress( uint8_t txBaseAddress, uint8_t rxBaseAddress )
{
uint8_t buf[2];
buf[0] = txBaseAddress;
buf[1] = rxBaseAddress;
SX126xWriteCommand( RADIO_SET_BUFFERBASEADDRESS, buf, 2 );
}
RadioStatus_t SX126xGetStatus( void )
{
uint8_t stat = 0;
RadioStatus_t status = { .Value = 0 };
stat = SX126xReadCommand( RADIO_GET_STATUS, NULL, 0 );
status.Fields.CmdStatus = ( stat & ( 0x07 << 1 ) ) >> 1;
status.Fields.ChipMode = ( stat & ( 0x07 << 4 ) ) >> 4;
LOG("stat:%d, chip mode:%d command status:%d", stat, status.Fields.ChipMode, status.Fields.CmdStatus);
return status;
}
int8_t SX126xGetRssiInst( void )
{
uint8_t buf[1];
int8_t rssi = 0;
SX126xReadCommand( RADIO_GET_RSSIINST, buf, 1 );
rssi = -buf[0] >> 1;
return rssi;
}
void SX126xGetRxBufferStatus( uint8_t *payloadLength, uint8_t *rxStartBufferPointer )
{
uint8_t status[2];
uint8_t cmdStatus = SX126xReadCommand( RADIO_GET_RXBUFFERSTATUS, status, 2 );
//LOG("[%s]cmdStatus:%d, PayloadLengthRx:%d, RxStartBufferPointer:%d", __func__, cmdStatus, status[0], status[1]);
// In case of LORA fixed header, the payloadLength is obtained by reading
// the register REG_LR_PAYLOADLENGTH
if( ( SX126xGetPacketType( ) == PACKET_TYPE_LORA ) && ( LoRaHeaderType == LORA_PACKET_FIXED_LENGTH ) )
{
*payloadLength = SX126xReadRegister( REG_LR_PAYLOADLENGTH );
}
else
{
*payloadLength = status[0];
}
*rxStartBufferPointer = status[1];
}
void SX126xGetPacketStatus( PacketStatus_t *pktStatus )
{
uint8_t status[3];
SX126xReadCommand( RADIO_GET_PACKETSTATUS, status, 3 );
pktStatus->packetType = SX126xGetPacketType( );
switch( pktStatus->packetType )
{
case PACKET_TYPE_GFSK:
pktStatus->Params.Gfsk.RxStatus = status[0];
pktStatus->Params.Gfsk.RssiSync = -status[1] >> 1;
pktStatus->Params.Gfsk.RssiAvg = -status[2] >> 1;
pktStatus->Params.Gfsk.FreqError = 0;
break;
case PACKET_TYPE_LORA:
pktStatus->Params.LoRa.RssiPkt = -status[0] >> 1;
// Returns SNR value [dB] rounded to the nearest integer value
pktStatus->Params.LoRa.SnrPkt = ( ( ( int8_t )status[1] ) + 2 ) >> 2;
pktStatus->Params.LoRa.SignalRssiPkt = -status[2] >> 1;
pktStatus->Params.LoRa.FreqError = FrequencyError;
break;
default:
case PACKET_TYPE_NONE:
// In that specific case, we set everything in the pktStatus to zeros
// and reset the packet type accordingly
memset( pktStatus, 0, sizeof( PacketStatus_t ) );
pktStatus->packetType = PACKET_TYPE_NONE;
break;
}
}
RadioError_t SX126xGetDeviceErrors( void )
{
uint8_t err[] = { 0, 0 };
RadioError_t error = { .Value = 0 };
SX126xReadCommand( RADIO_GET_ERROR, ( uint8_t* )err, 2 );
error.Fields.PaRamp = ( err[0] & ( 1 << 0 ) ) >> 0;
error.Fields.PllLock = ( err[1] & ( 1 << 6 ) ) >> 6;
error.Fields.XoscStart = ( err[1] & ( 1 << 5 ) ) >> 5;
error.Fields.ImgCalib = ( err[1] & ( 1 << 4 ) ) >> 4;
error.Fields.AdcCalib = ( err[1] & ( 1 << 3 ) ) >> 3;
error.Fields.PllCalib = ( err[1] & ( 1 << 2 ) ) >> 2;
error.Fields.Rc13mCalib = ( err[1] & ( 1 << 1 ) ) >> 1;
error.Fields.Rc64kCalib = ( err[1] & ( 1 << 0 ) ) >> 0;
return error;
}
void SX126xClearDeviceErrors( void )
{
uint8_t buf[2] = { 0x00, 0x00 };
SX126xWriteCommand( RADIO_CLR_ERROR, buf, 2 );
}
void SX126xClearIrqStatus( uint16_t irq )
{
uint8_t buf[2];
buf[0] = ( uint8_t )( ( ( uint16_t )irq >> 8 ) & 0x00FF );
buf[1] = ( uint8_t )( ( uint16_t )irq & 0x00FF );
SX126xWriteCommand( RADIO_CLR_IRQSTATUS, buf, 2 );
}
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/sx126x.c
|
C
|
apache-2.0
| 22,099
|
/*!
* \file sx126x.h
*
* \brief SX126x driver implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*/
#ifndef __SX126x_H__
#define __SX126x_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include "radio.h"
#include <aos/kernel.h>
#include "aos/init.h"
#include <vfsdev/spi_dev.h>
#include <drivers/u_ld.h>
#include <vfsdev/spi_dev.h>
#include <devicevfs/devicevfs.h>
#include <drivers/char/u_device.h>
#include <vfsdev/gpio_dev.h>
#include "aos/hal/gpio.h"
#define SX1261 1
#define SX1262 2
/*!
* Radio complete Wake-up Time with margin for temperature compensation
*/
#define RADIO_WAKEUP_TIME 3 // [ms]
/*!
* \brief Compensation delay for SetAutoTx/Rx functions in 15.625 microseconds
*/
#define AUTO_RX_TX_OFFSET 2
/*!
* \brief LFSR initial value to compute IBM type CRC
*/
#define CRC_IBM_SEED 0xFFFF
/*!
* \brief LFSR initial value to compute CCIT type CRC
*/
#define CRC_CCITT_SEED 0x1D0F
/*!
* \brief Polynomial used to compute IBM CRC
*/
#define CRC_POLYNOMIAL_IBM 0x8005
/*!
* \brief Polynomial used to compute CCIT CRC
*/
#define CRC_POLYNOMIAL_CCITT 0x1021
/*!
* \brief The address of the register holding the first byte defining the CRC seed
*
*/
#define REG_LR_CRCSEEDBASEADDR 0x06BC
/*!
* \brief The address of the register holding the first byte defining the CRC polynomial
*/
#define REG_LR_CRCPOLYBASEADDR 0x06BE
/*!
* \brief The address of the register holding the first byte defining the whitening seed
*/
#define REG_LR_WHITSEEDBASEADDR_MSB 0x06B8
#define REG_LR_WHITSEEDBASEADDR_LSB 0x06B9
/*!
* \brief The address of the register holding the packet configuration
*/
#define REG_LR_PACKETPARAMS 0x0704
/*!
* \brief The address of the register holding the payload size
*/
#define REG_LR_PAYLOADLENGTH 0x0702
/*!
* \brief The address of the register holding the re-calculated number of symbols
*/
#define REG_LR_SYNCH_TIMEOUT 0x0706
/*!
* \brief The addresses of the registers holding SyncWords values
*/
#define REG_LR_SYNCWORDBASEADDRESS 0x06C0
/*!
* \brief The addresses of the register holding LoRa Modem SyncWord value
*/
#define REG_LR_SYNCWORD 0x0740
/*!
* Syncword for Private LoRa networks
*/
#define LORA_MAC_PRIVATE_SYNCWORD 0x1424
/*!
* Syncword for Public LoRa networks
*/
#define LORA_MAC_PUBLIC_SYNCWORD 0x3444
/*!
* The address of the register giving a 32-bit random number
*/
#define RANDOM_NUMBER_GENERATORBASEADDR 0x0819
/*!
* The address of the register used to disable the LNA
*/
#define REG_ANA_LNA 0x08E2
/*!
* The address of the register used to disable the mixer
*/
#define REG_ANA_MIXER 0x08E5
/*!
* The address of the register holding RX Gain value (0x94: power saving, 0x96: rx boosted)
*/
#define REG_RX_GAIN 0x08AC
/*!
* Change the value on the device internal trimming capacitor
*/
#define REG_XTA_TRIM 0x0911
/*!
* Set the current max value in the over current protection
*/
#define REG_OCP 0x08E7
/*!
* \brief Structure describing the radio status
*/
typedef union RadioStatus_u
{
uint8_t Value;
struct
{ //bit order is lsb -> msb
uint8_t : 1; //!< Reserved
uint8_t CmdStatus : 3; //!< Command status
uint8_t ChipMode : 3; //!< Chip mode
uint8_t : 1; //!< Reserved
}Fields;
}RadioStatus_t;
/*!
* \brief Structure describing the error codes for callback functions
*/
typedef enum
{
IRQ_HEADER_ERROR_CODE = 0x01,
IRQ_SYNCWORD_ERROR_CODE = 0x02,
IRQ_CRC_ERROR_CODE = 0x04,
}IrqErrorCode_t;
enum IrqPblSyncHeaderCode_t
{
IRQ_PBL_DETECT_CODE = 0x01,
IRQ_SYNCWORD_VALID_CODE = 0x02,
IRQ_HEADER_VALID_CODE = 0x04,
};
/*!
* \brief Represents the operating mode the radio is actually running
*/
typedef enum
{
MODE_SLEEP = 0x00, //! The radio is in sleep mode
MODE_STDBY_RC, //! The radio is in standby mode with RC oscillator
MODE_STDBY_XOSC, //! The radio is in standby mode with XOSC oscillator
MODE_FS, //! The radio is in frequency synthesis mode
MODE_TX, //! The radio is in transmit mode
MODE_RX, //! The radio is in receive mode
MODE_RX_DC, //! The radio is in receive duty cycle mode
MODE_CAD //! The radio is in channel activity detection mode
}RadioOperatingModes_t;
/*!
* \brief Declares the oscillator in use while in standby mode
*
* Using the STDBY_RC standby mode allow to reduce the energy consumption
* STDBY_XOSC should be used for time critical applications
*/
typedef enum
{
STDBY_RC = 0x00,
STDBY_XOSC = 0x01,
}RadioStandbyModes_t;
/*!
* \brief Declares the power regulation used to power the device
*
* This command allows the user to specify if DC-DC or LDO is used for power regulation.
* Using only LDO implies that the Rx or Tx current is doubled
*/
typedef enum
{
USE_LDO = 0x00, // default
USE_DCDC = 0x01,
}RadioRegulatorMode_t;
/*!
* \brief Represents the possible packet type (i.e. modem) used
*/
typedef enum
{
PACKET_TYPE_GFSK = 0x00,
PACKET_TYPE_LORA = 0x01,
PACKET_TYPE_NONE = 0x0F,
}RadioPacketTypes_t;
/*!
* \brief Represents the ramping time for power amplifier
*/
typedef enum
{
RADIO_RAMP_10_US = 0x00,
RADIO_RAMP_20_US = 0x01,
RADIO_RAMP_40_US = 0x02,
RADIO_RAMP_80_US = 0x03,
RADIO_RAMP_200_US = 0x04,
RADIO_RAMP_800_US = 0x05,
RADIO_RAMP_1700_US = 0x06,
RADIO_RAMP_3400_US = 0x07,
}RadioRampTimes_t;
/*!
* \brief Represents the number of symbols to be used for channel activity detection operation
*/
typedef enum
{
LORA_CAD_01_SYMBOL = 0x00,
LORA_CAD_02_SYMBOL = 0x01,
LORA_CAD_04_SYMBOL = 0x02,
LORA_CAD_08_SYMBOL = 0x03,
LORA_CAD_16_SYMBOL = 0x04,
}RadioLoRaCadSymbols_t;
/*!
* \brief Represents the Channel Activity Detection actions after the CAD operation is finished
*/
typedef enum
{
LORA_CAD_ONLY = 0x00,
LORA_CAD_RX = 0x01,
LORA_CAD_LBT = 0x10,
}RadioCadExitModes_t;
/*!
* \brief Represents the modulation shaping parameter
*/
typedef enum
{
MOD_SHAPING_OFF = 0x00,
MOD_SHAPING_G_BT_03 = 0x08,
MOD_SHAPING_G_BT_05 = 0x09,
MOD_SHAPING_G_BT_07 = 0x0A,
MOD_SHAPING_G_BT_1 = 0x0B,
}RadioModShapings_t;
/*!
* \brief Represents the modulation shaping parameter
*/
typedef enum
{
RX_BW_4800 = 0x1F,
RX_BW_5800 = 0x17,
RX_BW_7300 = 0x0F,
RX_BW_9700 = 0x1E,
RX_BW_11700 = 0x16,
RX_BW_14600 = 0x0E,
RX_BW_19500 = 0x1D,
RX_BW_23400 = 0x15,
RX_BW_29300 = 0x0D,
RX_BW_39000 = 0x1C,
RX_BW_46900 = 0x14,
RX_BW_58600 = 0x0C,
RX_BW_78200 = 0x1B,
RX_BW_93800 = 0x13,
RX_BW_117300 = 0x0B,
RX_BW_156200 = 0x1A,
RX_BW_187200 = 0x12,
RX_BW_234300 = 0x0A,
RX_BW_312000 = 0x19,
RX_BW_373600 = 0x11,
RX_BW_467000 = 0x09,
}RadioRxBandwidth_t;
/*!
* \brief Represents the possible spreading factor values in LoRa packet types
*/
typedef enum
{
LORA_SF5 = 0x05,
LORA_SF6 = 0x06,
LORA_SF7 = 0x07,
LORA_SF8 = 0x08,
LORA_SF9 = 0x09,
LORA_SF10 = 0x0A,
LORA_SF11 = 0x0B,
LORA_SF12 = 0x0C,
}RadioLoRaSpreadingFactors_t;
/*!
* \brief Represents the bandwidth values for LoRa packet type
*/
typedef enum
{
LORA_BW_500 = 6,
LORA_BW_250 = 5,
LORA_BW_125 = 4,
LORA_BW_062 = 3,
LORA_BW_041 = 10,
LORA_BW_031 = 2,
LORA_BW_020 = 9,
LORA_BW_015 = 1,
LORA_BW_010 = 8,
LORA_BW_007 = 0,
}RadioLoRaBandwidths_t;
/*!
* \brief Represents the coding rate values for LoRa packet type
*/
typedef enum
{
LORA_CR_4_5 = 0x01,
LORA_CR_4_6 = 0x02,
LORA_CR_4_7 = 0x03,
LORA_CR_4_8 = 0x04,
}RadioLoRaCodingRates_t;
/*!
* \brief Represents the preamble length used to detect the packet on Rx side
*/
typedef enum
{
RADIO_PREAMBLE_DETECTOR_OFF = 0x00, //!< Preamble detection length off
RADIO_PREAMBLE_DETECTOR_08_BITS = 0x04, //!< Preamble detection length 8 bits
RADIO_PREAMBLE_DETECTOR_16_BITS = 0x05, //!< Preamble detection length 16 bits
RADIO_PREAMBLE_DETECTOR_24_BITS = 0x06, //!< Preamble detection length 24 bits
RADIO_PREAMBLE_DETECTOR_32_BITS = 0x07, //!< Preamble detection length 32 bit
}RadioPreambleDetection_t;
/*!
* \brief Represents the possible combinations of SyncWord correlators activated
*/
typedef enum
{
RADIO_ADDRESSCOMP_FILT_OFF = 0x00, //!< No correlator turned on, i.e. do not search for SyncWord
RADIO_ADDRESSCOMP_FILT_NODE = 0x01,
RADIO_ADDRESSCOMP_FILT_NODE_BROAD = 0x02,
}RadioAddressComp_t;
/*!
* \brief Radio GFSK packet length mode
*/
typedef enum
{
RADIO_PACKET_FIXED_LENGTH = 0x00, //!< The packet is known on both sides, no header included in the packet
RADIO_PACKET_VARIABLE_LENGTH = 0x01, //!< The packet is on variable size, header included
}RadioPacketLengthModes_t;
/*!
* \brief Represents the CRC length
*/
typedef enum
{
RADIO_CRC_OFF = 0x01, //!< No CRC in use
RADIO_CRC_1_BYTES = 0x00,
RADIO_CRC_2_BYTES = 0x02,
RADIO_CRC_1_BYTES_INV = 0x04,
RADIO_CRC_2_BYTES_INV = 0x06,
RADIO_CRC_2_BYTES_IBM = 0xF1,
RADIO_CRC_2_BYTES_CCIT = 0xF2,
}RadioCrcTypes_t;
/*!
* \brief Radio whitening mode activated or deactivated
*/
typedef enum
{
RADIO_DC_FREE_OFF = 0x00,
RADIO_DC_FREEWHITENING = 0x01,
}RadioDcFree_t;
/*!
* \brief Holds the Radio lengths mode for the LoRa packet type
*/
typedef enum
{
LORA_PACKET_VARIABLE_LENGTH = 0x00, //!< The packet is on variable size, header included
LORA_PACKET_FIXED_LENGTH = 0x01, //!< The packet is known on both sides, no header included in the packet
LORA_PACKET_EXPLICIT = LORA_PACKET_VARIABLE_LENGTH,
LORA_PACKET_IMPLICIT = LORA_PACKET_FIXED_LENGTH,
}RadioLoRaPacketLengthsMode_t;
/*!
* \brief Represents the CRC mode for LoRa packet type
*/
typedef enum
{
LORA_CRC_ON = 0x01, //!< CRC activated
LORA_CRC_OFF = 0x00, //!< CRC not used
}RadioLoRaCrcModes_t;
/*!
* \brief Represents the IQ mode for LoRa packet type
*/
typedef enum
{
LORA_IQ_NORMAL = 0x00,
LORA_IQ_INVERTED = 0x01,
}RadioLoRaIQModes_t;
/*!
* \brief Represents the voltage used to control the TCXO on/off from DIO3
*/
typedef enum
{
TCXO_CTRL_1_6V = 0x00,
TCXO_CTRL_1_7V = 0x01,
TCXO_CTRL_1_8V = 0x02,
TCXO_CTRL_2_2V = 0x03,
TCXO_CTRL_2_4V = 0x04,
TCXO_CTRL_2_7V = 0x05,
TCXO_CTRL_3_0V = 0x06,
TCXO_CTRL_3_3V = 0x07,
}RadioTcxoCtrlVoltage_t;
/*!
* \brief Represents the interruption masks available for the radio
*
* \remark Note that not all these interruptions are available for all packet types
*/
typedef enum
{
IRQ_RADIO_NONE = 0x0000,
IRQ_TX_DONE = 0x0001,
IRQ_RX_DONE = 0x0002,
IRQ_PREAMBLE_DETECTED = 0x0004,
IRQ_SYNCWORD_VALID = 0x0008,
IRQ_HEADER_VALID = 0x0010,
IRQ_HEADER_ERROR = 0x0020,
IRQ_CRC_ERROR = 0x0040,
IRQ_CAD_DONE = 0x0080,
IRQ_CAD_ACTIVITY_DETECTED = 0x0100,
IRQ_RX_TX_TIMEOUT = 0x0200,
IRQ_RADIO_ALL = 0xFFFF,
}RadioIrqMasks_t;
/*!
* \brief Represents all possible opcode understood by the radio
*/
typedef enum RadioCommands_e
{
RADIO_GET_STATUS = 0xC0,
RADIO_WRITE_REGISTER = 0x0D,
RADIO_READ_REGISTER = 0x1D,
RADIO_WRITE_BUFFER = 0x0E,
RADIO_READ_BUFFER = 0x1E,
RADIO_SET_SLEEP = 0x84,
RADIO_SET_STANDBY = 0x80,
RADIO_SET_FS = 0xC1,
RADIO_SET_TX = 0x83,
RADIO_SET_RX = 0x82,
RADIO_SET_RXDUTYCYCLE = 0x94,
RADIO_SET_CAD = 0xC5,
RADIO_SET_TXCONTINUOUSWAVE = 0xD1,
RADIO_SET_TXCONTINUOUSPREAMBLE = 0xD2,
RADIO_SET_PACKETTYPE = 0x8A,
RADIO_GET_PACKETTYPE = 0x11,
RADIO_SET_RFFREQUENCY = 0x86,
RADIO_SET_TXPARAMS = 0x8E,
RADIO_SET_PACONFIG = 0x95,
RADIO_SET_CADPARAMS = 0x88,
RADIO_SET_BUFFERBASEADDRESS = 0x8F,
RADIO_SET_MODULATIONPARAMS = 0x8B,
RADIO_SET_PACKETPARAMS = 0x8C,
RADIO_GET_RXBUFFERSTATUS = 0x13,
RADIO_GET_PACKETSTATUS = 0x14,
RADIO_GET_RSSIINST = 0x15,
RADIO_GET_STATS = 0x10,
RADIO_RESET_STATS = 0x00,
RADIO_CFG_DIOIRQ = 0x08,
RADIO_GET_IRQSTATUS = 0x12,
RADIO_CLR_IRQSTATUS = 0x02,
RADIO_CALIBRATE = 0x89,
RADIO_CALIBRATEIMAGE = 0x98,
RADIO_SET_REGULATORMODE = 0x96,
RADIO_GET_ERROR = 0x17,
RADIO_CLR_ERROR = 0x07,
RADIO_SET_TCXOMODE = 0x97,
RADIO_SET_TXFALLBACKMODE = 0x93,
RADIO_SET_RFSWITCHMODE = 0x9D,
RADIO_SET_STOPRXTIMERONPREAMBLE = 0x9F,
RADIO_SET_LORASYMBTIMEOUT = 0xA0,
}RadioCommands_t;
/*!
* \brief The type describing the modulation parameters for every packet types
*/
typedef struct
{
RadioPacketTypes_t PacketType; //!< Packet to which the modulation parameters are referring to.
struct
{
struct
{
uint32_t BitRate;
uint32_t Fdev;
RadioModShapings_t ModulationShaping;
uint8_t Bandwidth;
}Gfsk;
struct
{
RadioLoRaSpreadingFactors_t SpreadingFactor; //!< Spreading Factor for the LoRa modulation
RadioLoRaBandwidths_t Bandwidth; //!< Bandwidth for the LoRa modulation
RadioLoRaCodingRates_t CodingRate; //!< Coding rate for the LoRa modulation
uint8_t LowDatarateOptimize; //!< Indicates if the modem uses the low datarate optimization
}LoRa;
}Params; //!< Holds the modulation parameters structure
}ModulationParams_t;
/*!
* \brief The type describing the packet parameters for every packet types
*/
typedef struct
{
RadioPacketTypes_t PacketType; //!< Packet to which the packet parameters are referring to.
struct
{
/*!
* \brief Holds the GFSK packet parameters
*/
struct
{
uint16_t PreambleLength; //!< The preamble Tx length for GFSK packet type in bit
RadioPreambleDetection_t PreambleMinDetect; //!< The preamble Rx length minimal for GFSK packet type
uint8_t SyncWordLength; //!< The synchronization word length for GFSK packet type
RadioAddressComp_t AddrComp; //!< Activated SyncWord correlators
RadioPacketLengthModes_t HeaderType; //!< If the header is explicit, it will be transmitted in the GFSK packet. If the header is implicit, it will not be transmitted
uint8_t PayloadLength; //!< Size of the payload in the GFSK packet
RadioCrcTypes_t CrcLength; //!< Size of the CRC block in the GFSK packet
RadioDcFree_t DcFree;
}Gfsk;
/*!
* \brief Holds the LoRa packet parameters
*/
struct
{
uint16_t PreambleLength; //!< The preamble length is the number of LoRa symbols in the preamble
RadioLoRaPacketLengthsMode_t HeaderType; //!< If the header is explicit, it will be transmitted in the LoRa packet. If the header is implicit, it will not be transmitted
uint8_t PayloadLength; //!< Size of the payload in the LoRa packet
RadioLoRaCrcModes_t CrcMode; //!< Size of CRC block in LoRa packet
RadioLoRaIQModes_t InvertIQ; //!< Allows to swap IQ for LoRa packet
}LoRa;
}Params; //!< Holds the packet parameters structure
}PacketParams_t;
/*!
* \brief Represents the packet status for every packet type
*/
typedef struct
{
RadioPacketTypes_t packetType; //!< Packet to which the packet status are referring to.
struct
{
struct
{
uint8_t RxStatus;
int8_t RssiAvg; //!< The averaged RSSI
int8_t RssiSync; //!< The RSSI measured on last packet
uint32_t FreqError;
}Gfsk;
struct
{
int8_t RssiPkt; //!< The RSSI of the last packet
int8_t SnrPkt; //!< The SNR of the last packet
int8_t SignalRssiPkt;
uint32_t FreqError;
}LoRa;
}Params;
}PacketStatus_t;
/*!
* \brief Represents the Rx internal counters values when GFSK or LoRa packet type is used
*/
typedef struct
{
RadioPacketTypes_t packetType; //!< Packet to which the packet status are referring to.
uint16_t PacketReceived;
uint16_t CrcOk;
uint16_t LengthError;
}RxCounter_t;
/*!
* \brief Represents a calibration configuration
*/
typedef union
{
struct
{
uint8_t RC64KEnable : 1; //!< Calibrate RC64K clock
uint8_t RC13MEnable : 1; //!< Calibrate RC13M clock
uint8_t PLLEnable : 1; //!< Calibrate PLL
uint8_t ADCPulseEnable : 1; //!< Calibrate ADC Pulse
uint8_t ADCBulkNEnable : 1; //!< Calibrate ADC bulkN
uint8_t ADCBulkPEnable : 1; //!< Calibrate ADC bulkP
uint8_t ImgEnable : 1;
uint8_t : 1;
}Fields;
uint8_t Value;
}CalibrationParams_t;
/*!
* \brief Represents a sleep mode configuration
*/
typedef union
{
struct
{
uint8_t WakeUpRTC : 1; //!< Get out of sleep mode if wakeup signal received from RTC
uint8_t Reset : 1;
uint8_t WarmStart : 1;
uint8_t Reserved : 5;
}Fields;
uint8_t Value;
}SleepParams_t;
/*!
* \brief Represents the possible radio system error states
*/
typedef union
{
struct
{
uint8_t Rc64kCalib : 1; //!< RC 64kHz oscillator calibration failed
uint8_t Rc13mCalib : 1; //!< RC 13MHz oscillator calibration failed
uint8_t PllCalib : 1; //!< PLL calibration failed
uint8_t AdcCalib : 1; //!< ADC calibration failed
uint8_t ImgCalib : 1; //!< Image calibration failed
uint8_t XoscStart : 1; //!< XOSC oscillator failed to start
uint8_t PllLock : 1; //!< PLL lock failed
uint8_t : 1; //!< Buck converter failed to start
uint8_t PaRamp : 1; //!< PA ramp failed
uint8_t : 7; //!< Reserved
}Fields;
uint16_t Value;
}RadioError_t;
/*!
* Radio hardware and global parameters
*/
typedef struct SX126x_s
{
int Spi;
gpio_io_config_t NSS;
gpio_io_config_t BUSY;
gpio_io_config_t Reset;
gpio_irq_config_t DIO1;
gpio_irq_config_t DIO2;
gpio_irq_config_t DIO3;
PacketParams_t PacketParams;
PacketStatus_t PacketStatus;
ModulationParams_t ModulationParams;
}SX126x_t;
/*!
* Hardware IO IRQ callback function definition
*/
typedef void ( DioIrqHandler )( void* context );
/*!
* SX126x definitions
*/
/*!
* \brief Provides the frequency of the chip running on the radio and the frequency step
*
* \remark These defines are used for computing the frequency divider to set the RF frequency
*/
#define XTAL_FREQ ( double )32000000
#define FREQ_DIV ( double )pow( 2.0, 25.0 )
#define FREQ_STEP ( double )( XTAL_FREQ / FREQ_DIV )
#define RX_BUFFER_SIZE 256
/*!
* \brief The radio callbacks structure
* Holds function pointers to be called on radio interrupts
*/
typedef struct
{
void ( *txDone )( void ); //!< Pointer to a function run on successful transmission
void ( *rxDone )( void ); //!< Pointer to a function run on successful reception
void ( *rxPreambleDetect )( void ); //!< Pointer to a function run on successful Preamble detection
void ( *rxSyncWordDone )( void ); //!< Pointer to a function run on successful SyncWord reception
void ( *rxHeaderDone )( bool isOk ); //!< Pointer to a function run on successful Header reception
void ( *txTimeout )( void ); //!< Pointer to a function run on transmission timeout
void ( *rxTimeout )( void ); //!< Pointer to a function run on reception timeout
void ( *rxError )( IrqErrorCode_t errCode ); //!< Pointer to a function run on reception error
void ( *cadDone )( bool cadFlag ); //!< Pointer to a function run on channel activity detected
}SX126xCallbacks_t;
/*!
* ============================================================================
* Public functions prototypes
* ============================================================================
*/
/*!
* \brief Initializes the radio driver
*/
void SX126xInit( DioIrqHandler dioIrq );
/*!
* \brief Wakeup the radio if it is in Sleep mode and check that Busy is low
*/
void SX126xCheckDeviceReady( void );
/*!
* \brief Saves the payload to be send in the radio buffer
*
* \param [in] payload A pointer to the payload
* \param [in] size The size of the payload
*/
void SX126xSetPayload( uint8_t *payload, uint8_t size );
/*!
* \brief Reads the payload received. If the received payload is longer
* than maxSize, then the method returns 1 and do not set size and payload.
*
* \param [out] payload A pointer to a buffer into which the payload will be copied
* \param [out] size A pointer to the size of the payload received
* \param [in] maxSize The maximal size allowed to copy into the buffer
*/
uint8_t SX126xGetPayload( uint8_t *payload, uint8_t *size, uint8_t maxSize );
/*!
* \brief Sends a payload
*
* \param [in] payload A pointer to the payload to send
* \param [in] size The size of the payload to send
* \param [in] timeout The timeout for Tx operation
*/
void SX126xSendPayload( uint8_t *payload, uint8_t size, uint32_t timeout );
/*!
* \brief Sets the Sync Word given by index used in GFSK
*
* \param [in] syncWord SyncWord bytes ( 8 bytes )
*
* \retval status [0: OK, 1: NOK]
*/
uint8_t SX126xSetSyncWord( uint8_t *syncWord );
/*!
* \brief Sets the Initial value for the LFSR used for the CRC calculation
*
* \param [in] seed Initial LFSR value ( 2 bytes )
*
*/
void SX126xSetCrcSeed( uint16_t seed );
/*!
* \brief Sets the seed used for the CRC calculation
*
* \param [in] seed The seed value
*
*/
void SX126xSetCrcPolynomial( uint16_t polynomial );
/*!
* \brief Sets the Initial value of the LFSR used for the whitening in GFSK protocols
*
* \param [in] seed Initial LFSR value
*/
void SX126xSetWhiteningSeed( uint16_t seed );
/*!
* \brief Gets a 32-bit random value generated by the radio
*
* \remark A valid packet type must have been configured with \ref SX126xSetPacketType
* before using this command.
*
* \remark The radio must be in reception mode before executing this function
* This code can potentially result in interrupt generation. It is the responsibility of
* the calling code to disable radio interrupts before calling this function,
* and re-enable them afterwards if necessary, or be certain that any interrupts
* generated during this process will not cause undesired side-effects in the software.
*
* Please note that the random numbers produced by the generator do not have a uniform or Gaussian distribution. If
* uniformity is needed, perform appropriate software post-processing.
*
* \retval randomValue 32 bits random value
*/
uint32_t SX126xGetRandom( void );
/*!
* \brief Sets the radio in sleep mode
*
* \param [in] sleepConfig The sleep configuration describing data
* retention and RTC wake-up
*/
void SX126xSetSleep( SleepParams_t sleepConfig );
/*!
* \brief Sets the radio in configuration mode
*
* \param [in] mode The standby mode to put the radio into
*/
void SX126xSetStandby( RadioStandbyModes_t mode );
/*!
* \brief Sets the radio in FS mode
*/
void SX126xSetFs( void );
/*!
* \brief Sets the radio in transmission mode
*
* \param [in] timeout Structure describing the transmission timeout value
*/
void SX126xSetTx( uint32_t timeout );
/*!
* \brief Sets the radio in reception mode
*
* \param [in] timeout Structure describing the reception timeout value
*/
void SX126xSetRx( uint32_t timeout );
/*!
* \brief Sets the radio in reception mode with Boosted LNA gain
*
* \param [in] timeout Structure describing the reception timeout value
*/
void SX126xSetRxBoosted( uint32_t timeout );
/*!
* \brief Sets the Rx duty cycle management parameters
*
* \param [in] rxTime Structure describing reception timeout value
* \param [in] sleepTime Structure describing sleep timeout value
*/
void SX126xSetRxDutyCycle( uint32_t rxTime, uint32_t sleepTime );
/*!
* \brief Sets the radio in CAD mode
*/
void SX126xSetCad( void );
/*!
* \brief Sets the radio in continuous wave transmission mode
*/
void SX126xSetTxContinuousWave( void );
/*!
* \brief Sets the radio in continuous preamble transmission mode
*/
void SX126xSetTxInfinitePreamble( void );
/*!
* \brief Decide which interrupt will stop the internal radio rx timer.
*
* \param [in] enable [0: Timer stop after header/syncword detection
* 1: Timer stop after preamble detection]
*/
void SX126xSetStopRxTimerOnPreambleDetect( bool enable );
/*!
* \brief Set the number of symbol the radio will wait to validate a reception
*
* \param [in] SymbNum number of LoRa symbols
*/
void SX126xSetLoRaSymbNumTimeout( uint8_t SymbNum );
/*!
* \brief Sets the power regulators operating mode
*
* \param [in] mode [0: LDO, 1:DC_DC]
*/
void SX126xSetRegulatorMode( RadioRegulatorMode_t mode );
/*!
* \brief Calibrates the given radio block
*
* \param [in] calibParam The description of blocks to be calibrated
*/
void SX126xCalibrate( CalibrationParams_t calibParam );
/*!
* \brief Calibrates the Image rejection depending of the frequency
*
* \param [in] freq The operating frequency
*/
void SX126xCalibrateImage( uint32_t freq );
/*!
* \brief Activate the extention of the timeout when long preamble is used
*
* \param [in] enable The radio will extend the timeout to cope with long preamble
*/
void SX126xSetLongPreamble( uint8_t enable );
/*!
* \brief Sets the transmission parameters
*
* \param [in] paDutyCycle Duty Cycle for the PA
* \param [in] hpMax 0 for sx1261, 7 for sx1262
* \param [in] deviceSel 1 for sx1261, 0 for sx1262
* \param [in] paLut 0 for 14dBm LUT, 1 for 22dBm LUT
*/
void SX126xSetPaConfig( uint8_t paDutyCycle, uint8_t hpMax, uint8_t deviceSel, uint8_t paLut );
/*!
* \brief Defines into which mode the chip goes after a TX / RX done
*
* \param [in] fallbackMode The mode in which the radio goes
*/
void SX126xSetRxTxFallbackMode( uint8_t fallbackMode );
/*!
* \brief Write data to the radio memory
*
* \param [in] address The address of the first byte to write in the radio
* \param [in] buffer The data to be written in radio's memory
* \param [in] size The number of bytes to write in radio's memory
*/
void SX126xWriteRegisters( uint16_t address, uint8_t *buffer, uint16_t size );
/*!
* \brief Read data from the radio memory
*
* \param [in] address The address of the first byte to read from the radio
* \param [out] buffer The buffer that holds data read from radio
* \param [in] size The number of bytes to read from radio's memory
*/
void SX126xReadRegisters( uint16_t address, uint8_t *buffer, uint16_t size );
/*!
* \brief Write data to the buffer holding the payload in the radio
*
* \param [in] offset The offset to start writing the payload
* \param [in] buffer The data to be written (the payload)
* \param [in] size The number of byte to be written
*/
void SX126xWriteBuffer( uint8_t offset, uint8_t *buffer, uint8_t size );
/*!
* \brief Read data from the buffer holding the payload in the radio
*
* \param [in] offset The offset to start reading the payload
* \param [out] buffer A pointer to a buffer holding the data from the radio
* \param [in] size The number of byte to be read
*/
void SX126xReadBuffer( uint8_t offset, uint8_t *buffer, uint8_t size );
/*!
* \brief Sets the IRQ mask and DIO masks
*
* \param [in] irqMask General IRQ mask
* \param [in] dio1Mask DIO1 mask
* \param [in] dio2Mask DIO2 mask
* \param [in] dio3Mask DIO3 mask
*/
void SX126xSetDioIrqParams( uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask, uint16_t dio3Mask );
/*!
* \brief Returns the current IRQ status
*
* \retval irqStatus IRQ status
*/
uint16_t SX126xGetIrqStatus( void );
/*!
* \brief Indicates if DIO2 is used to control an RF Switch
*
* \param [in] enable true of false
*/
void SX126xSetDio2AsRfSwitchCtrl( uint8_t enable );
/*!
* \brief Indicates if the Radio main clock is supplied from a tcxo
*
* \param [in] tcxoVoltage voltage used to control the TCXO
* \param [in] timeout time given to the TCXO to go to 32MHz
*/
void SX126xSetDio3AsTcxoCtrl( RadioTcxoCtrlVoltage_t tcxoVoltage, uint32_t timeout );
/*!
* \brief Sets the RF frequency
*
* \param [in] frequency RF frequency [Hz]
*/
void SX126xSetRfFrequency( uint32_t frequency );
/*!
* \brief Sets the radio for the given protocol
*
* \param [in] packetType [PACKET_TYPE_GFSK, PACKET_TYPE_LORA]
*
* \remark This method has to be called before SetRfFrequency,
* SetModulationParams and SetPacketParams
*/
void SX126xSetPacketType( RadioPacketTypes_t packetType );
/*!
* \brief Gets the current radio protocol
*
* \retval packetType [PACKET_TYPE_GFSK, PACKET_TYPE_LORA]
*/
RadioPacketTypes_t SX126xGetPacketType( void );
/*!
* \brief Sets the transmission parameters
*
* \param [in] power RF output power [-18..13] dBm
* \param [in] rampTime Transmission ramp up time
*/
void SX126xSetTxParams( int8_t power, RadioRampTimes_t rampTime );
/*!
* \brief Set the modulation parameters
*
* \param [in] modParams A structure describing the modulation parameters
*/
void SX126xSetModulationParams( ModulationParams_t *modParams );
/*!
* \brief Sets the packet parameters
*
* \param [in] packetParams A structure describing the packet parameters
*/
void SX126xSetPacketParams( PacketParams_t *packetParams );
/*!
* \brief Sets the Channel Activity Detection (CAD) parameters
*
* \param [in] cadSymbolNum The number of symbol to use for CAD operations
* [LORA_CAD_01_SYMBOL, LORA_CAD_02_SYMBOL,
* LORA_CAD_04_SYMBOL, LORA_CAD_08_SYMBOL,
* LORA_CAD_16_SYMBOL]
* \param [in] cadDetPeak Limit for detection of SNR peak used in the CAD
* \param [in] cadDetMin Set the minimum symbol recognition for CAD
* \param [in] cadExitMode Operation to be done at the end of CAD action
* [LORA_CAD_ONLY, LORA_CAD_RX, LORA_CAD_LBT]
* \param [in] cadTimeout Defines the timeout value to abort the CAD activity
*/
void SX126xSetCadParams( RadioLoRaCadSymbols_t cadSymbolNum, uint8_t cadDetPeak, uint8_t cadDetMin, RadioCadExitModes_t cadExitMode, uint32_t cadTimeout );
/*!
* \brief Sets the data buffer base address for transmission and reception
*
* \param [in] txBaseAddress Transmission base address
* \param [in] rxBaseAddress Reception base address
*/
void SX126xSetBufferBaseAddress( uint8_t txBaseAddress, uint8_t rxBaseAddress );
/*!
* \brief Gets the current radio status
*
* \retval status Radio status
*/
RadioStatus_t SX126xGetStatus( void );
/*!
* \brief Returns the instantaneous RSSI value for the last packet received
*
* \retval rssiInst Instantaneous RSSI
*/
int8_t SX126xGetRssiInst( void );
/*!
* \brief Gets the last received packet buffer status
*
* \param [out] payloadLength Last received packet payload length
* \param [out] rxStartBuffer Last received packet buffer address pointer
*/
void SX126xGetRxBufferStatus( uint8_t *payloadLength, uint8_t *rxStartBuffer );
/*!
* \brief Gets the last received packet payload length
*
* \param [out] pktStatus A structure of packet status
*/
void SX126xGetPacketStatus( PacketStatus_t *pktStatus );
/*!
* \brief Returns the possible system errors
*
* \retval sysErrors Value representing the possible sys failures
*/
RadioError_t SX126xGetDeviceErrors( void );
/*!
* \brief Clear all the errors in the device
*/
void SX126xClearDeviceErrors( void );
/*!
* \brief Clears the IRQs
*
* \param [in] irq IRQ(s) to be cleared
*/
void SX126xClearIrqStatus( uint16_t irq );
#ifdef __cplusplus
}
#endif
#endif // __SX126x_H__
|
YifuLiu/AliOS-Things
|
solutions/lora_p2p_demo/sx126x.h
|
C
|
apache-2.0
| 39,069
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo AOS SDK Done
sdk:
$(CPRE) aos sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
ifeq ($(OS), Windows_NT)
$(CPRE) if exist aos_sdk rmdir /s /q aos_sdk
$(CPRE) if exist binary rmdir /s /q binary
$(CPRE) if exist out rmdir /s /q out
$(CPRE) if exist aos.elf del /f /q aos.elf
$(CPRE) if exist aos.map del /f /q aos.map
else
$(CPRE) rm -rf aos_sdk binary out aos.elf aos.map
endif
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/Makefile
|
Makefile
|
apache-2.0
| 599
|
#! /bin/env python
from aostools import Make
# default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin
# defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin')
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/SConstruct
|
Python
|
apache-2.0
| 303
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
* If board have no component for example board_xx_init, it indicates that this
* app does not support this board.
* Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t *init_args);
/*
* For user config
* kinit.argc = 0;
* kinit.argv = NULL;
* kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/*
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void *arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
int application_start(int argc, char *argv[])
{
int ret;
aos_set_log_level(AOS_LL_DEBUG);
ret = BleCfg_run();
if (ret) {
return ret;
}
aos_msleep(100);
(void)BleCfg_recovery_wifi();
(void)BleCfg_recovery_devinfo();
while (1) {
aos_msleep(1000);
};
return 0;
}
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/maintask.c
|
C
|
apache-2.0
| 1,525
|
App({
globalData: {
sysname: '',
},
onLaunch(options) {
let sysInfo = my.getSystemInfoSync()
let sysname = sysInfo.platform.toLowerCase()
if (sysname.includes('ios') || sysname.includes('iphone')) {
this.globalData.sysname = 'ios'
} else {
this.globalData.sysname = 'android'
}
console.log(this.globalData.sysname)
},
onShow(options) {
// 从后台被 scheme 重新打开
// options.query == {number:1}
},
});
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/app.js
|
JavaScript
|
apache-2.0
| 470
|
Page({
data: {},
onLoad() { },
scan() {
my.scan({
scanType: ['qrCode'],
success: (res) => {
console.log(res.code)
if (/.*\.vapp.cloudhost.link/.test(res.code)) {
my.alert({ contant: "请扫描正确的预览二维码" });
return;
}
my.navigateTo({ url: '/pages/webview/webview?address=' + encodeURIComponent(res.code) });
},
});
}
});
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/pages/linkIot/linkIot.js
|
JavaScript
|
apache-2.0
| 421
|
var app = getApp();
var ble_util = require("../../utils/ble_util.js")
var hex_util = require("../../utils/hex_util.js")
Page({
data: {
ProductKey: '',
DeviceName: '',
DeviceSecret: '',
link_lp_devices: [],
selected_device_index: 0,
LinkLpState: {
scanning: false,
linking: false,
},
LinkState: 0
},
notifyCheckInt: null,
notifyCheckCnt: 0,
onLoad() {
},
genTriadPacket(ProductKey, DeviceName, DeviceSecret) {
let ret = "ffb0"
ret += ProductKey.length < 16 ? ('0' + (ProductKey.length).toString(16)) : ((ProductKey.length).toString(16))
ret += DeviceName.length < 16 ? ('0' + (DeviceName.length).toString(16)) : ((DeviceName.length).toString(16))
ret += DeviceSecret.length < 16 ? ('0' + (DeviceSecret.length).toString(16)) : ((DeviceSecret.length).toString(16))
for (let i = 0; i < ProductKey.length; i++) {
ret += ProductKey.charCodeAt(i) < 16 ? ('0' + ProductKey.charCodeAt(i).toString(16)) : ProductKey.charCodeAt(i).toString(16);
}
for (let i = 0; i < DeviceName.length; i++) {
ret += DeviceName.charCodeAt(i) < 16 ? ('0' + DeviceName.charCodeAt(i).toString(16)) : DeviceName.charCodeAt(i).toString(16);
}
for (let i = 0; i < DeviceSecret.length; i++) {
ret += DeviceSecret.charCodeAt(i) < 16 ? ('0' + DeviceSecret.charCodeAt(i).toString(16)) : DeviceSecret.charCodeAt(i).toString(16);
}
return ret
},
scanTriadQr() {
my.scan({
scanType: ['qrCode'],
success: (res) => {
console.log(res.code)
let Triad = JSON.parse(res.code)
console.log(Triad)
if (Triad.ProductKey != undefined && Triad.DeviceName != undefined && Triad.DeviceSecret != undefined) {
this.setData({
ProductKey: Triad.ProductKey,
DeviceName: Triad.DeviceName,
DeviceSecret: Triad.DeviceSecret
})
} else {
my.alert({ content: "二维码格式错误" });
}
},
});
},
async startLinkLpDevicesDiscovery() {
this.setData({ 'LinkLpState.scanning': true })
this.setData({ link_lp_devices: [] })
await ble_util.OpenBluetoothAdapter().catch(err => { console.error(err) })
let res;
for (let retry = 10; retry > 0; retry--) {
console.log(retry)
res = await ble_util.DiscoveryBLEDevice('FFB0')
if (res && res.devices != null) {
console.log(res.devices)
this.setData({
link_lp_devices: res.devices
})
break;
}
}
console.log(res)
if (res.devices == null)
my.alert({ content: res.content })
this.setData({ 'LinkLpState.scanning': false })
},
bindDevicePickerChange(event) {
this.setData({
selected_device_index: event.detail.value,
});
},
async sendTriad() {
if (this.data.ProductKey.length < 1 || this.data.DeviceName.length < 1 || this.data.DeviceSecret.length < 1) {
my.alert({ content: '请输入正确的三元组信息' })
}
await this.OpenBluetoothAdapter().catch(err => { console.error(err) })
this.setData({ 'LinkLpState.linking': true })
await ble_util.DisconnectBLEDevice(this.data.net_config_devices[this.data.selected_device_index].deviceId).catch(err => { console.error(err) })
my.connectBLEDevice({
deviceId: this.data.link_lp_devices[this.data.selected_device_index].deviceId,
success: res => {
console.log('connect with ' + this.data.link_lp_devices[this.data.selected_device_index].deviceId + ' success')
console.log(res)
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.link_lp_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_NOTIFY[app.globalData.sysname],
success: () => {
my.offBLECharacteristicValueChange();
my.onBLECharacteristicValueChange((res) => {
console.log('得到响应数据 = ' + res.value);
console.log(hex_util.hexString2String(res.value))
this.LinkLpNotifyFormat(res.value)
});
console.log('监听成功');
},
fail: error => {
this.setData({ 'LinkLpState.linking': false })
console.log({ content: '监听失败' + JSON.stringify(error) });
},
});
my.writeBLECharacteristicValue({
deviceId: this.data.link_lp_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_WRITE[app.globalData.sysname],
value: this.genTriadPacket(this.data.ProductKey, this.data.DeviceName, this.data.DeviceSecret),
success: res => {
console.log(res);
// retry here
var notifyCheckCnt = 5
var notifyCheckInt = setInterval(() => {
if (this.data.LinkLpState.linking == 0) {
notifyCheckCnt = notifyCheckCnt - 1
console.log('notifyCheckCnt ' + notifyCheckCnt)
if (notifyCheckCnt < 0) {
clearInterval(notifyCheckInt)
this.setData({ 'LinkLpState.linking': false })
my.alert({ content: "下发三元组失败:设备无回复" })
}
}
}, 1000)
},
fail: error => {
this.setData({ 'linkLpState.linking': false })
console.log(error);
},
});
},
fail: error => {
this.setData({ 'LinkLpState.linking': false })
console.log(error);
},
})
},
LinkLpNotifyFormat(str) {
console.log("LinkLpNotifyFormat")
if (hex_util.hexString2String(str) == 'DEVSETOK') {
console.log("link done")
this.setData({
'LinkLpState.linking': false,
LinkState: 1
})
}
},
pkOnInput(e) {
this.setData({
ProductKey: e.detail.value
})
},
dnOnInput(e) {
this.setData({
DeviceName: e.detail.value
})
},
dsOnInput(e) {
this.setData({
DeviceSecret: e.detail.value
})
},
onHide() {
my.closeBluetoothAdapter();
}
});
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/pages/linkLP/linkLP.js
|
JavaScript
|
apache-2.0
| 6,347
|
var app = getApp();
var ble_util = require("../../utils/ble_util.js")
var hex_util = require("../../utils/hex_util.js")
Page({
data: {
ssid: '',
ssidList: [],
password: '',
net_config_devices: [],
selected_device_index: 0,
netCfgState: {
scanning: false,
configing: false,
},
wifiSelect: false,
netState: -1,
ipAddr: null
},
onLoad() {
},
async startNetConfigDevicesDiscovery() {
this.setData({ 'netCfgState.scanning': true })
this.setData({ net_config_devices: [] })
await ble_util.OpenBluetoothAdapter().catch(err => { console.error(err) })
let res;
for (let retry = 10; retry > 0; retry--) {
console.log(retry)
res = await ble_util.DiscoveryBLEDevice('FFA0') // TODO 传参数找
if (res && res.devices != null) {
console.log(res.devices)
this.setData({
net_config_devices: res.devices
})
break;
}
}
console.log(res)
if (res.devices == null)
my.alert({ content: res.content })
this.setData({ 'netCfgState.scanning': false })
},
bindDevicePickerChange(event) {
this.setData({
selected_device_index: event.detail.value,
});
},
async getWiFiList() {
if (this.data.net_config_devices.length == 0) {
my.alert({ content: "请选择目标设备" })
}
this.setData({ ssidList: [] })
my.showLoading({ content: "扫描中", mask: true });
my.connectBLEDevice({
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
success: res => {
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_NOTIFY[app.globalData.sysname],
success: () => {
my.offBLECharacteristicValueChange();
let wifiListHexStr = ""
let headStr = "FFD"
let headNum = 0
my.onBLECharacteristicValueChange((res) => {
console.log(res)
console.log('得到响应数据 = ' + res.value);
console.log(hex_util.hexString2String(res.value))
if (res.value.indexOf(headStr) == 0) {
if (res.value.length > 4) {
if (res.value[3] == ("" + headNum)) {
wifiListHexStr += res.value.slice(4)
headNum += 1
} else {
console.error("数据传输错误,请重试")
my.hideLoading();
}
} else {
my.hideLoading();
console.log(wifiListHexStr)
console.log(hex_util.hexString2String(wifiListHexStr))
let wifiListStr = hex_util.hexString2String(wifiListHexStr)
this.setData({ ssidList: wifiListStr.slice(1).split(")(").slice(0, -2) })
if (this.data.ssidList.length > 0) {
my.hideLoading();
this.setData({ wifiSelect: true })
} else {
my.hideLoading();
my.showToast({
type: 'fail',
content: '未扫描到可用 Wi-Fi',
duration: 2000,
});
}
}
}
});
console.log('监听成功');
},
fail: error => {
my.hideLoading();
console.log({ content: '监听失败' + JSON.stringify(error) });
},
});
my.writeBLECharacteristicValue({
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_WRITE[app.globalData.sysname],
value: "FFC0",
success: res => {
console.log(res);
var notifyCheckCnt = 5
var notifyCheckInt = setInterval(() => {
if (this.data.ipAddr == null) {
this.notifyCheckCnt = this.notifyCheckCnt - 1
console.log('notifyCheckCnt ' + this.notifyCheckCnt)
if (notifyCheckCnt < 0) {
clearInterval(notifyCheckInt)
this.setData({ 'netCfgState.configing': false })
my.alert({ content: "配网失败,设备无回复" })
}
}
}, 1000)
},
fail: error => {
this.setData({ 'netCfgState.configing': false })
console.log(error);
},
});
},
fail: error => {
this.setData({ 'netCfgState.configing': false })
console.log(error);
},
})
},
async setNetConfig() {
if (this.data.ssid.length < 1) {
my.alert({ content: '请输入正确的SSID' })
return
}
if (this.data.password.length < 8) {
my.alert({ content: '请输入正确的密码' })
return
}
await ble_util.OpenBluetoothAdapter().catch(err => { console.error(err) })
this.setData({ 'netCfgState.configing': true })
await ble_util.DisconnectBLEDevice(this.data.net_config_devices[this.data.selected_device_index].deviceId).catch(err => { console.error(err) })
my.connectBLEDevice({
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
success: res => {
console.log('connect with ' + this.data.net_config_devices[this.data.selected_device_index].deviceId + ' success')
console.log(res)
console.log(ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname])
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_NOTIFY[app.globalData.sysname],
success: () => {
my.offBLECharacteristicValueChange();
my.onBLECharacteristicValueChange((res) => {
console.log('得到响应数据 = ' + res.value);
console.log(hex_util.hexString2String(res.value))
this.notifyFormat(res.value)
});
console.log('监听成功');
},
fail: error => {
this.setData({ 'netCfgState.configing': false })
console.log({ content: '监听失败' + JSON.stringify(error) });
},
});
my.writeBLECharacteristicValue({
deviceId: this.data.net_config_devices[this.data.selected_device_index].deviceId,
serviceId: ble_util.UUID_VENDOR_SERVICE[app.globalData.sysname],
characteristicId: ble_util.UUID_VENDOR_CHAR_WRITE[app.globalData.sysname],
value: this.genNetConfigPacket(this.data.ssid, this.data.password),
success: res => {
console.log(res);
console.log('写入数据成功!' + this.genNetConfigPacket(this.data.ssid, this.data.password));
// retry here
var notifyCheckCnt = 5
var notifyCheckInt = setInterval(() => {
if (this.data.ipAddr == null) {
notifyCheckCnt = notifyCheckCnt - 1
console.log('notifyCheckCnt ' + notifyCheckCnt)
if (notifyCheckCnt < 0) {
clearInterval(notifyCheckInt)
this.setData({ 'netCfgState.configing': false })
my.alert({ content: "配网失败,设备无回复" })
} else if (this.data.netCfgState.configing == false) {
clearInterval(notifyCheckInt)
}
}
}, 1000)
},
fail: error => {
this.setData({ 'netCfgState.configing': false })
console.log(error);
},
});
},
fail: error => {
this.setData({ 'netCfgState.configing': false })
console.log(error);
},
})
},
notifyFormat(str) {
if (str.length > 2) {
let maybeIp = hex_util.hexString2String(str)
console.log(maybeIp)
if (this.StrIsIp(maybeIp)) {
this.setData({
ipAddr: maybeIp
})
this.setData({ 'netCfgState.configing': false })
}
}
},
genNetConfigPacket(ssid, password) {
// [(num)ssid_len, (num)psd_len, (str)ssid, (str)psd] => acsii => hex str
// 9, 6, 'A','U'.. '9','1','4'...
// 06 09 4155524F5241393134323238383431
// console.log(this.stringToBytes(String.fromCharCode(ssid.length) + String.fromCharCode(password.length) + ssid + password))
let ret = "ffa0"
ret += ssid.length < 16 ? ('0' + (ssid.length).toString(16)) : ((ssid.length).toString(16))
ret += password.length < 16 ? ('0' + (password.length).toString(16)) : ((password.length).toString(16))
for (let i = 0; i < ssid.length; i++) {
ret += ssid.charCodeAt(i) < 16 ? ('0' + ssid.charCodeAt(i).toString(16)) : ssid.charCodeAt(i).toString(16);
}
for (let i = 0; i < password.length; i++) {
ret += password.charCodeAt(i) < 16 ? ('0' + password.charCodeAt(i).toString(16)) : password.charCodeAt(i).toString(16);
}
return ret
},
StrIsIp(str) {
return /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(str)
},
ssidOnInput(e) {
this.setData({
ssid: e.detail.value
})
},
passwordOnInput(e) {
this.setData({
password: e.detail.value
})
},
bindSSIDPickerChange(event) {
console.log(event)
this.setData({
ssid: this.data.ssidList[event.detail.value]
})
},
wifiSelectCancel() {
this.setData({ wifiSelect: false })
},
wifiPickerOnChange(e) {
console.log(e)
this.wifiSelectIndex = e.detail.value
},
wifiSelectConform() {
this.setData({ wifiSelect: false, ssid: this.data.ssidList[this.wifiSelectIndex] })
},
onHide() {
my.closeBluetoothAdapter();
}
});
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/pages/netCfg/netCfg.js
|
JavaScript
|
apache-2.0
| 10,292
|
export default {
getDeviceNameList(devices) {
let device_name_list = []
for(let index = 0; index < devices.length; index++){
device_name_list.push(devices[index].localName)
}
console.log(device_name_list)
return device_name_list
}
}
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/pages/netCfg/netCfg.sjs
|
JavaScript
|
apache-2.0
| 264
|
Page({
data: {
link: ''
},
onLoad(query) {
console.warn(decodeURIComponent(query.address))
this.setData({ link: decodeURIComponent(query.address) })
},
});
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/pages/webview/webview.js
|
JavaScript
|
apache-2.0
| 176
|
const UUID_VENDOR_SERVICE = { "android": "0000FFA0-0000-1000-8000-00805F9B34FB", "ios": "FFA0" }
const UUID_VENDOR_CHAR_READ = { "android": "0000FFA1-0000-1000-8000-00805F9B34FB", "ios": "FFA1" }
const UUID_VENDOR_CHAR_WRITE = { "android": "0000FFA2-0000-1000-8000-00805F9B34FB", "ios": "FFA2" }
const UUID_VENDOR_CHAR_NOTIFY = { "android": "0000FFA3-0000-1000-8000-00805F9B34FB", "ios": "FFA3" }
function GetBluetoothAdapterState() {
return new Promise((resolve, reject) => {
my.getBluetoothAdapterState({
success: res => {
console.log(res)
resolve(res);
},
fail: error => {
reject(error);
},
})
})
}
function OpenBluetoothAdapter() {
return new Promise((resolve, reject) => {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
reject({ content: '抱歉,您的手机蓝牙暂不可用' });
}
resolve({ content: '初始化成功!' });
},
fail: error => {
reject({ content: JSON.stringify(error) });
},
});
})
}
function CloseBluetoothAdapter() {
return new Promise((resolve, reject) => {
my.offBLECharacteristicValueChange();
my.closeBluetoothAdapter({
success: () => {
resolve({ content: '关闭蓝牙成功!' });
},
fail: error => {
reject({ content: JSON.stringify(error) });
},
});
})
}
function ConnectBLEDevice(deviceId) {
return new Promise((resolve, reject) => {
my.connectBLEDevice({
deviceId: deviceId,
success: res => {
resolve({ content: res });
},
fail: error => {
reject({ content: JSON.stringify(error) });
},
})
})
}
function DisconnectBLEDevice(deviceId) {
return new Promise((resolve, reject) => {
my.disconnectBLEDevice({
deviceId: deviceId,
success: res => {
resolve({ content: res });
},
fail: error => {
reject({ content: JSON.stringify(error) });
},
})
})
}
function DiscoveryBLEDevice(targetUUID) {
return new Promise((resolve, reject) => {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: () => {
setTimeout(() => {
my.getBluetoothDevices({
success: res => {
console.log(res)
let _net_config_devices = [];
for (let index = 0; index < res.devices.length; index++) {
if (res.devices[index].advertisServiceUUIDs != undefined && res.devices[index].advertisServiceUUIDs[0] == targetUUID) {
_net_config_devices.push(res.devices[index]);
}
}
if (_net_config_devices.length > 0) {
resolve({ devices: _net_config_devices, content: 'success' })
} else {
resolve({ devices: null, content: '未搜索到目标设备' })
}
},
fail: error => {
resolve({ devices: null, content: '获取设备失败' + JSON.stringify(error) });
},
});
}, 500)
},
fail: error => {
resolve({ devices: null, content: '启动扫描失败' + JSON.stringify(error) });
},
});
});
}
module.exports = {
GetBluetoothAdapterState: GetBluetoothAdapterState,
OpenBluetoothAdapter: OpenBluetoothAdapter,
CloseBluetoothAdapter: CloseBluetoothAdapter,
ConnectBLEDevice: ConnectBLEDevice,
DisconnectBLEDevice: DisconnectBLEDevice,
DiscoveryBLEDevice: DiscoveryBLEDevice,
UUID_VENDOR_SERVICE,
UUID_VENDOR_CHAR_READ,
UUID_VENDOR_CHAR_WRITE,
UUID_VENDOR_CHAR_NOTIFY
}
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/utils/ble_util.js
|
JavaScript
|
apache-2.0
| 3,652
|
function String2hexString(str) {
var val = "";
for (var i = 0; i < str.length; i++) {
if (val == "")
val = str.charCodeAt(i).toString(16);
else
val += str.charCodeAt(i).toString(16);
}
return val
}
function hexString2String(hex) {
var arr = hex.split("")
var out = ""
for (var i = 0; i < arr.length / 2; i++) {
var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
var charValue = String.fromCharCode(tmp);
out += charValue
}
return out
}
module.exports = {
hexString2String: hexString2String,
String2hexString: String2hexString
}
|
YifuLiu/AliOS-Things
|
solutions/miniapp_agent_demo/miniapp/utils/hex_util.js
|
JavaScript
|
apache-2.0
| 577
|
CPRE := @
ifeq ($(V),1)
CPRE :=
VERB := --verbose
endif
MK_GENERATED_IMGS_PATH:=generated
PRODUCT_BIN:=product
.PHONY:startup
startup: all
all:
@echo "Build Solution by $(BOARD) "
$(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS)
@echo YoC SDK Done
@echo [INFO] Create bin files
# $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -i $(MK_GENERATED_IMGS_PATH)/data -l -p
# $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -e $(MK_GENERATED_IMGS_PATH) -x
.PHONY:flash
flash:
$(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -w prim
.PHONY:flashall
flashall:
$(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -a
sdk:
$(CPRE) yoc sdk
.PHONY:clean
clean:
$(CPRE) scons -c --board=$(BOARD)
$(CPRE) find . -name "*.[od]" -delete
$(CPRE) rm yoc_sdk yoc.* generated out -rf
|
YifuLiu/AliOS-Things
|
solutions/ota_demo/Makefile
|
Makefile
|
apache-2.0
| 868
|
#! /bin/env python
from aostools import Make
defconfig = Make()
Export('defconfig')
defconfig.build_components()
|
YifuLiu/AliOS-Things
|
solutions/ota_demo/SConstruct
|
Python
|
apache-2.0
| 117
|
/* user space */
#ifndef RHINO_CONFIG_USER_SPACE
#define RHINO_CONFIG_USER_SPACE 0
#endif
|
YifuLiu/AliOS-Things
|
solutions/ota_demo/k_app_config.h
|
C
|
apache-2.0
| 106
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#ifndef AOS_BINS
extern int application_start(int argc, char *argv[]);
#endif
/*
If board have no component for example board_xx_init, it indicates that this app does not support this board.
Set the correspondence in file platform\board\aaboard_demo\ucube.py.
*/
extern void board_tick_init(void);
extern void board_stduart_init(void);
extern void board_dma_init(void);
extern void board_gpio_init(void);
extern void board_kinit_init(kinit_t* init_args);
/* For user config
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
*/
static kinit_t kinit = {0, NULL, 1};
/**
* @brief Board Initialization Function
* @param None
* @retval None
*/
void board_init(void)
{
board_tick_init();
board_stduart_init();
board_dma_init();
board_gpio_init();
}
void aos_maintask(void* arg)
{
board_init();
board_kinit_init(&kinit);
aos_components_init(&kinit);
#ifndef AOS_BINS
application_start(kinit.argc, kinit.argv); /* jump to app entry */
#endif
}
|
YifuLiu/AliOS-Things
|
solutions/ota_demo/maintask.c
|
C
|
apache-2.0
| 1,192
|