diff --git a/docs/API_reference/en/Note.md b/docs/API_reference/en/Note.md new file mode 100644 index 0000000000000000000000000000000000000000..168f336cd30357a6724ddcc7ac0258ae63590d8c --- /dev/null +++ b/docs/API_reference/en/Note.md @@ -0,0 +1,69 @@ +# QuecPython API 参考手册编写注意事项 + +## 编写规范 + +参考[Quectel_QuecPython_WiKi编写规范.pdf](https://knowledge.quectel.com/download/attachments/151561997/%5BInternal%5DQuectel_QuecPython_WiKi%E7%BC%96%E5%86%99%E8%A7%84%E8%8C%83_V1.0.0_Preliminary_20230112.pdf?api=v2)。 + +## 目录结构 + +API 参考手册根目录下存在一个名为`README.md`的文件,该文件用来描述 QuecPython 的简介和 API 三个板块的的入口链接。 + +> 文档中心使用的[teedoc](https://gitee.com/teedoc)架构要求每个版块的首页文件都要是名为`README.md`的文件。 + +参照原官网的三个主要板块,将 API 参考手册的目录结构整体划分为 [QuecPython 标准库](https://python.quectel.com/wiki/#/zh-cn/api/pythonStdlib)、[QuecPython类库](https://python.quectel.com/wiki/#/zh-cn/api/QuecPythonClasslib) 和 [QuecPython组件库](https://python.quectel.com/wiki/#/zh-cn/api/QuecPythonThirdlib)。 + +每个目录结构下,均有对应的同名md文件,这些md文件分别对相应的板块做了综合叙述,并列出了板块中包含了哪些模块,点击这些模块名,就可以跳转到对应的模块的md文件中。 + +同时,每个目录下,也包含了一系列名为`.md`的文件,用来描述名为``的模块的API;若模块下包含类,则在该目录下创建名为`..md`。以`machine`模块为例,在`QuecPython类库`目录下应创建`machine.md`文件,其下存在`Pin`等类,需要创建`machime.Pin.md`文件。 + +所有md文件中引用的图片,均存放于media目录中: +- README.md中的图片存放于media根目录。 +- 其余文件中的图片请存放于media下的对应目录中。 +- 图片统一为png格式,命名请见名知意,如`machine.Pin.xxx.png`,其中`xxx`表示用简短英文编写的图片作用描述。 + +目录结构示例如下: + +``` +QuecPython官网文档中心/API手册 +├── README.md +├── QuecPython标准库 +│   ├── README.md +│   ├── gc.md +│   ├── ubinascii.md +│   ├── ucollections.md +│   ├── uos.md +│   └── urandom.md +├── QuecPython类库 +│   ├── README.md +│   ├── atcmd.md +│   ├── cellLocator.md +│   ├── dataCall.md +│   ├── example.md +│   ├── machine.Pin.md +│   ├── machine.md +│   └── wifilocator.md +├── QuecPython组件库 +│   ├── README.md +│   ├── TenCentYun.md +│   ├── aLiYun.md +│   ├── log.md +│   ├── request.md +│   └── umqtt.md +└── media +    ├── QuecPython架构.png +    ├── QuecPython标准库 +    │   └── uos.xxx.png +    ├── QuecPython类库 +    │ ├── machine.xxx.png +    │   └── machine.Pin.xxx.png +    └── QuecPython组件库 +    └── umqtt.xxx.png +``` + +## README.md + +README.md作为板块的首页入口,需要对该板块做综合性描述,并且在最后提供板块的所有二级目录链接。 + +## QuecPython API 参考手册 + +[点此查看](./README.md) diff --git a/docs/API_reference/en/README.md b/docs/API_reference/en/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1721f433217a4fd092aab4e57a02f245b8146c --- /dev/null +++ b/docs/API_reference/en/README.md @@ -0,0 +1,43 @@ +# QuecPython API Reference Manual + +**Author** + +   QuecPython Developer Team + +**Version** + +   1.12 + +QuecPython is a solution created by Quectel, which is based on the open-source project MicroPython. It inherits the basic features of MicroPython and expands the features related to Quectel's communication modules. With QuecPython, developers can easily develop embedded Internet of Things (IoT) projects. + +If you are not familiar with QuecPython, you may not know its advantages compared to other embedded IoT project development methods. However, once you get to know QuecPython, you will immediately discover its charm and superiority. + +## QuecPython Overview + +QuecPython is a platform name created by combining "Quectel" and "microPython". It is compatible with Python 3 grammar specification. The minimum ROM storage space required is 150 KB, and the minimum RAM storage space required is 50 KB. + +Thanks to Python's inherent advantages, QuecPython has many advantages, such as `cross-platform compatibility`, `no need for compilation`, `dynamic loading` and `providing a rich and mature application framework`. QuecPython also provides solutions for `smart meters`, `smart locators`, `public network intercoms`, `BMS communication cloud boxes` and more ([click here for details](https://python.quectel.com/en/solutions)). + +The QuecPython team also provides rich development tools such as QPYcom, VSCode plugins, and production testing tools, facilitating the development and production testing. + +## QuecPython Architecture + +With the rapid development of IoT market in recent years, networking of embedded devices has become a trend. Traditional embedded IoT project development still ports or develops functional components based on the RTOS kernel in C language. This approach has low development efficiency, requires high platform adaptation workloads, and requires high developer capabilities. + +QuecPython integrates various commonly used components for embedded IoT projects in the system, and users can implement corresponding features by simply calling Python interfaces. The system architecture is shown in the figure below: + +![](./media/README/QuecPython_Architecture.png) + +## QuecPython API Reference Manual + +- [Python Standard Library](./stdlib/README.md) +- [Cellular Communication](./iotlib/README.md) +- [Peripherals](./peripherals/README.md) +- [System Library](./syslib/README.md) +- [Multimedia Library](./medialib/README.md) +- [Wi-Fi](./wifilib/README.md) +- [Bluetooth](./btlib/README.md) +- [Network Applications](./networklib/README.md) +- [Positioning Applications](./gnsslib/README.md) +- [Open Source Components](./componentlib/README.md) +- [Error Code List](./errcode/README.md) \ No newline at end of file diff --git a/docs/API_reference/en/btlib/README.md b/docs/API_reference/en/btlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a39c18118d514a89f8a40276ace2c8a930b7bba1 --- /dev/null +++ b/docs/API_reference/en/btlib/README.md @@ -0,0 +1,10 @@ +# QuecPython Bluetooth communication + +> QuecPython Bluetooth communication library includes Bluetooth low power related function modules and classic Bluetooth related function modules + +This article describes the modules in the QuecPython Bluetooth communication-related library. + +## QuecPython Bluetooth communication library list + +- [ble - Bluetooth Low Energy related features](./ble.md) +- [bt - Classic Bluetooth related features](./bt.md) \ No newline at end of file diff --git a/docs/API_reference/en/btlib/ble.md b/docs/API_reference/en/btlib/ble.md new file mode 100644 index 0000000000000000000000000000000000000000..292729b2a4e20fae722d626ee3e701a94a12348a --- /dev/null +++ b/docs/API_reference/en/btlib/ble.md @@ -0,0 +1,2529 @@ +# ble-Bluetooth Low Energy + +The `ble` module provides BLE GATT Server (slave) and BLE GATT Client (master) features based on the BLE 4.2 protocol. + +**Example**: + +```python +#BLE Server + +import ble +import utime + + +BLE_GATT_SYS_SERVICE = 0 # 0-Removes the system default GAP and GATT services 1-Keeps the system default GAP and GATT services +BLE_SERVER_HANDLE = 0 +_BLE_NAME = "Quectel_ble" + + +event_dict = { + 'BLE_START_STATUS_IND': 0, # Start BLE + 'BLE_STOP_STATUS_IND': 1, # Stop BLE + 'BLE_CONNECT_IND': 16, # Connect BLE + 'BLE_DISCONNECT_IND': 17, # Disconnect BLE + 'BLE_UPDATE_CONN_PARAM_IND': 18, # BLE update connection parameter + 'BLE_SCAN_REPORT_IND': 19, # BLE GATT client scan and report other devices + 'BLE_GATT_MTU': 20, # BLE connection mtu + 'BLE_GATT_RECV_WRITE_IND': 21, # When the BLE client writes a characteristic value or descriptor, the server gets the notice. + 'BLE_GATT_RECV_READ_IND': 22, # When the BLE client reads a characteristic value or descriptor, the server gets the notice. + 'BLE_GATT_RECV_NOTIFICATION_IND': 23, # Client receives notification + 'BLE_GATT_RECV_INDICATION_IND': 24, # Client receives indication + 'BLE_GATT_SEND_END': 25, # Server sends notification, and receives notice sent by the peer end +} + +class EVENT(dict): + def __getattr__(self, item): + return self[item] + + def __setattr__(self, key, value): + raise ValueError("{} is read-only.".format(key)) + + +event = EVENT(event_dict) + + +def ble_callback(args): + global BLE_GATT_SYS_SERVICE + global BLE_SERVER_HANDLE + event_id = args[0] + status = args[1] + print('[ble_callback]: event_id={}, status={}'.format(event_id, status)) + + if event_id == event.BLE_START_STATUS_IND: # Start BLE + if status == 0: + print('[callback] BLE start success.') + mac = ble.getPublicAddr() + if mac != -1 and len(mac) == 6: + addr = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]) + print('BLE public addr : {}'.format(addr)) + ret = ble_gatt_set_name() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_set_param() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_set_data() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_set_rsp_data() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_add_service() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_add_characteristic() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_add_characteristic_value() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_add_characteristic_desc() + if ret != 0: + ble_gatt_close() + return + ret = ble_gatt_add_service_complete() + if ret != 0: + ble_gatt_close() + return + if BLE_GATT_SYS_SERVICE == 0: + BLE_SERVER_HANDLE = 1 + else: + BLE_SERVER_HANDLE = 16 + ret = ble_adv_start() + if ret != 0: + ble_gatt_close() + return + else: + print('[callback] BLE start failed.') + elif event_id == event.BLE_STOP_STATUS_IND: # Stop BLE + if status == 0: + print('[callback] ble stop successful.') + ble_status = ble.getStatus() + print('ble status is {}'.format(ble_status)) + ble_gatt_server_release() + else: + print('[callback] ble stop failed.') + elif event_id == event.BLE_CONNECT_IND: # Connect BLE + if status == 0: + print('[callback] ble connect successful.') + connect_id = args[2] + addr = args[3] + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + + ret = ble_gatt_send_notification() + if ret == 0: + print('[callback] ble_gatt_send_notification successful.') + else: + print('[callback] ble_gatt_send_notification failed.') + ble_gatt_close() + return + else: + print('[callback] ble connect failed.') + elif event_id == event.BLE_DISCONNECT_IND: # Disconnect BLE + if status == 0: + print('[callback] ble disconnect successful.') + connect_id = args[2] + addr = args[3] + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + ble_gatt_close() + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + else: + print('[callback] ble disconnect failed.') + ble_gatt_close() + return + elif event_id == event.BLE_UPDATE_CONN_PARAM_IND: # BLE update connection parameter + if status == 0: + print('[callback] ble update parameter successful.') + connect_id = args[2] + max_interval = args[3] + min_interval = args[4] + latency = args[5] + timeout = args[6] + print('[callback] connect_id={},max_interval={},min_interval={},latency={},timeout={}'.format(connect_id, max_interval, min_interval, latency, timeout)) + else: + print('[callback] ble update parameter failed.') + ble_gatt_close() + return + elif event_id == event.BLE_GATT_MTU: # BLE connection MTU + if status == 0: + print('[callback] ble connect mtu successful.') + handle = args[2] + ble_mtu = args[3] + print('[callback] handle = {:#06x}, ble_mtu = {}'.format(handle, ble_mtu)) + else: + print('[callback] ble connect mtu failed.') + ble_gatt_close() + return + elif event_id == event.BLE_GATT_RECV_WRITE_IND: + if status == 0: + print('[callback] ble recv successful.') + data_len = args[2] + data = args[3] # a bytearray + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # a bytearray + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv failed.') + ble_gatt_close() + return + elif event_id == event.BLE_GATT_RECV_READ_IND: + if status == 0: + print('[callback] ble recv read successful.') + data_len = args[2] + data = args[3] # a bytearray + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # a bytearray + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv read failed.') + ble_gatt_close() + return + elif event_id == event.BLE_GATT_SEND_END: + if status == 0: + print('[callback] ble send data successful.') + else: + print('[callback] ble send data failed.') + else: + print('unknown event id.') + + +def ble_gatt_server_init(cb): + ret = ble.serverInit(cb) + if ret != 0: + print('ble_gatt_server_init failed.') + return -1 + print('ble_gatt_server_init success.') + return 0 + + +def ble_gatt_server_release(): + ret = ble.serverRelease() + if ret != 0: + print('ble_gatt_server_release failed.') + return -1 + print('ble_gatt_server_release success.') + return 0 + + +def ble_gatt_open(): + ret = ble.gattStart() + if ret != 0: + print('ble_gatt_open failed.') + return -1 + print('ble_gatt_open success.') + return 0 + + +def ble_gatt_close(): + ret = ble.gattStop() + if ret != 0: + print('ble_gatt_close failed.') + return -1 + print('ble_gatt_close success.') + return 0 + + +def ble_gatt_set_name(): + code = 0 # utf8 + name = _BLE_NAME + ret = ble.setLocalName(code, name) + if ret != 0: + print('ble_gatt_set_name failed.') + return -1 + print('ble_gatt_set_name success.') + return 0 + + +def ble_gatt_set_param(): + min_adv = 0x300 + max_adv = 0x320 + adv_type = 0 # Connectable undirected advertising (default) + addr_type = 0 # Public address + channel = 0x07 + filter_strategy = 0 # Allow scan request from any, allow connect request from any + discov_mode = 2 + no_br_edr = 1 + enable_adv = 1 + ret = ble.setAdvParam(min_adv, max_adv, adv_type, addr_type, channel, filter_strategy, discov_mode, no_br_edr, enable_adv) + if ret != 0: + print('ble_gatt_set_param failed.') + return -1 + print('ble_gatt_set_param success.') + return 0 + + +def ble_gatt_set_data(): + adv_data = [0x02, 0x01, 0x05] + ble_name = _BLE_NAME + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvData(data) + if ret != 0: + print('ble_gatt_set_data failed.') + return -1 + print('ble_gatt_set_data success.') + return 0 + + +def ble_gatt_set_rsp_data(): + adv_data = [] + ble_name = _BLE_NAME + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_rsp_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvRspData(data) + if ret != 0: + print('ble_gatt_set_rsp_data failed.') + return -1 + print('ble_gatt_set_rsp_data success.') + return 0 + + +def ble_gatt_add_service(): + primary = 1 + server_id = 0x01 + uuid_type = 1 # Short UUID + uuid_s = 0x180F + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addService(primary, server_id, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_service failed.') + return -1 + print('ble_gatt_add_service success.') + return 0 + + +def ble_gatt_add_characteristic(): + server_id = 0x01 + chara_id = 0x01 + chara_prop = 0x02 | 0x10 | 0x20 # 0x02-Readable; 0x10-Notification; 0x20-Indication + uuid_type = 1 # Short UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addChara(server_id, chara_id, chara_prop, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_characteristic failed.') + return -1 + print('ble_gatt_add_characteristic success.') + return 0 + + +def ble_gatt_add_characteristic_value(): + data = [] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # short UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + for i in range(0, 244): + data.append(0x00) + value = bytearray(data) + ret = ble.addCharaValue(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_value failed.') + return -1 + print('ble_gatt_add_characteristic_value success.') + return 0 + + +def ble_gatt_add_characteristic_desc(): + data = [0x00, 0x00] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # Short UUID + uuid_s = 0x2902 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + value = bytearray(data) + ret = ble.addCharaDesc(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_desc failed.') + return -1 + print('ble_gatt_add_characteristic_desc success.') + return 0 + + +def ble_gatt_send_notification(): + global BLE_SERVER_HANDLE + data = [0x39, 0x39, 0x39, 0x39, 0x39] # Test data + conn_id = 0 + attr_handle = BLE_SERVER_HANDLE + 2 + value = bytearray(data) + ret = ble.sendNotification(conn_id, attr_handle, value) + if ret != 0: + print('ble_gatt_send_notification failed.') + return -1 + print('ble_gatt_send_notification success.') + return 0 + + +def ble_gatt_add_service_complete(): + global BLE_GATT_SYS_SERVICE + ret = ble.addOrClearService(1, BLE_GATT_SYS_SERVICE) + if ret != 0: + print('ble_gatt_add_service_complete failed.') + return -1 + print('ble_gatt_add_service_complete success.') + return 0 + + +def ble_gatt_clear_service_complete(): + global BLE_GATT_SYS_SERVICE + ret = ble.addOrClearService(0, BLE_GATT_SYS_SERVICE) + if ret != 0: + print('ble_gatt_clear_service_complete failed.') + return -1 + print('ble_gatt_clear_service_complete success.') + return 0 + + +def ble_adv_start(): + ret = ble.advStart() + if ret != 0: + print('ble_adv_start failed.') + return -1 + print('ble_adv_start success.') + return 0 + + +def ble_adv_stop(): + ret = ble.advStop() + if ret != 0: + print('ble_adv_stop failed.') + return -1 + print('ble_adv_stop success.') + return 0 + + +def main(): + ret = ble_gatt_server_init(ble_callback) + if ret == 0: + ret = ble_gatt_open() + if ret != 0: + return -1 + else: + return -1 + count = 0 + while True: + utime.sleep(1) + count += 1 + if count % 5 == 0: + print('##### BLE running, count = {}......'.format(count)) + if count > 120: + count = 0 + print('!!!!! stop BLE now !!!!!') + ble_gatt_close() + return 0 + + +if __name__ == '__main__': + main() + +``` + +```python +#BLE Client + +import ble +import utime +import _thread +import checkNet +from queue import Queue + +PROJECT_NAME = "QuecPython_BLE_Client_Example" +PROJECT_VERSION = "1.0.0" +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +event_dict = { + 'BLE_START_STATUS_IND': 0, # Start BLE + 'BLE_STOP_STATUS_IND': 1, # Stop BLE + 'BLE_CONNECT_IND': 16, # Connect BLE + 'BLE_DISCONNECT_IND': 17, # Disconnect BLE + 'BLE_UPDATE_CONN_PARAM_IND': 18, # BLE update connection parameter + 'BLE_SCAN_REPORT_IND': 19, # BLE GATT client scan and report other devices + 'BLE_GATT_MTU': 20, # BLE connection MTU + 'BLE_GATT_RECV_NOTIFICATION_IND': 23, # Client receive notification + 'BLE_GATT_RECV_INDICATION_IND': 24, # Client receive indication + 'BLE_GATT_START_DISCOVER_SERVICE_IND': 26, # Start discover service + 'BLE_GATT_DISCOVER_SERVICE_IND': 27, # Discover service + 'BLE_GATT_DISCOVER_CHARACTERISTIC_DATA_IND': 28, # Discover characteristic + 'BLE_GATT_DISCOVER_CHARA_DESC_IND': 29, # Discover characteristic descriptor + 'BLE_GATT_CHARA_WRITE_WITH_RSP_IND': 30, # Write characteristic value with response + 'BLE_GATT_CHARA_WRITE_WITHOUT_RSP_IND': 31, # Write characteristic value without response + 'BLE_GATT_CHARA_READ_IND': 32, # Read characteristic value by handle + 'BLE_GATT_CHARA_READ_BY_UUID_IND': 33, # Read characteristic value by UUID + 'BLE_GATT_CHARA_MULTI_READ_IND': 34, # Read multiple characteristic value + 'BLE_GATT_DESC_WRITE_WITH_RSP_IND': 35, # Write characteristic descriptor + 'BLE_GATT_DESC_READ_IND': 36, # Read characteristic descriptor + 'BLE_GATT_ATT_ERROR_IND': 37, # Attribute error +} + +gatt_status_dict = { + 'BLE_GATT_IDLE' : 0, + 'BLE_GATT_DISCOVER_SERVICE': 1, + 'BLE_GATT_DISCOVER_INCLUDES': 2, + 'BLE_GATT_DISCOVER_CHARACTERISTIC': 3, + 'BLE_GATT_WRITE_CHARA_VALUE': 4, + 'BLE_GATT_WRITE_CHARA_DESC': 5, + 'BLE_GATT_READ_CHARA_VALUE': 6, + 'BLE_GATT_READ_CHARA_DESC': 7, +} + +class EVENT(dict): + def __getattr__(self, item): + return self[item] + + def __setattr__(self, key, value): + raise ValueError("{} is read-only.".format(key)) + + +class BleClient(object): + def __init__(self): + self.ble_server_name = 'Quectel_ble' #The BLE name of the target device + self.connect_id = 0 + self.connect_addr = 0 + self.gatt_statue = 0 + self.discover_service_mode = 0 # 0-discover all service, 1-discover service by uuid + + self.scan_param = { + 'scan_mode' : 1, # Active scanning + 'interval' : 0x100, + 'scan_window' : 0x50, + 'filter_policy' : 0, + 'local_addr_type' : 0, + } + + self.scan_report_info = { + 'event_type' : 0, + 'name' : '', + 'addr_type' : 0, + 'addr' : 0, # 0 indicates invalid value when initializing. The value is in bytearray + 'rssi' : 0, + 'data_len' : 0, + 'raw_data' : 0, + } + + self.target_service = { + 'start_handle' : 0, + 'end_handle' : 0, + 'uuid_type' : 1, # Short UUID + 'short_uuid' : 0x180F, # Battery power service + 'long_uuid' : bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + } + + self.characteristic_list = [] + self.descriptor_list = [] + self.characteristic_count = 0 # ql_ble_gatt_chara_count + self.chara_descriptor_count = 0 # ql_ble_gatt_chara_desc_count + self.characteristic_index = 0 # ql_ble_gatt_chara_desc_index + self.current_chara_index = 0 # ql_ble_gatt_cur_chara + self.current_desc_index = 0 # ql_ble_gatt_chara_cur_desc + self.ble_short_uuid_pair_len = 7 + self.ble_long_uuid_pair_len = 21 + + ret = ble.clientInit(self.ble_client_callback) + if ret != 0: + print('ble client initialize failed.') + raise ValueError("BLE Client Init failed.") + else: + print('ble client initialize successful.') + print('') + + @staticmethod + def gatt_open(): + ret = ble.gattStart() + if ret != 0: + print('ble open failed.') + else: + print('ble open successful.') + print('') + return ret + + @staticmethod + def gatt_close(): + ret = ble.gattStop() + if ret != 0: + print('ble close failed.') + else: + print('ble close successful.') + print('') + return ret + + @staticmethod + def gatt_get_status(): + return ble.getStatus() + + @staticmethod + def release(): + ret = ble.clientRelease() + if ret != 0: + print('ble client release failed.') + else: + print('ble client release successful.') + print('') + return ret + + def set_scan_param(self): + scan_mode = self.scan_param['scan_mode'] + interval = self.scan_param['interval'] + scan_time = self.scan_param['scan_window'] + filter_policy = self.scan_param['filter_policy'] + local_addr_type = self.scan_param['local_addr_type'] + ret = ble.setScanParam(scan_mode, interval, scan_time, filter_policy, local_addr_type) + if ret != 0: + print('ble client set scan-parameters failed.') + else: + print('ble client set scan-parameters successful.') + print('') + return ret + + @staticmethod + def start_scan(): + ret = ble.scanStart() + if ret != 0: + print('ble client scan failed.') + else: + print('ble client scan successful.') + print('') + return ret + + @staticmethod + def stop_scan(): + ret = ble.scanStop() + if ret != 0: + print('ble client failed to stop scanning.') + else: + print('ble client scan stopped successfully.') + print('') + return ret + + def connect(self): + print('start to connect.....') + addr_type = self.scan_report_info['addr_type'] + addr = self.scan_report_info['addr'] + if addr != 0 and len(addr) == 6: + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('addr_type : {}, addr : {}'.format(addr_type, addr_str)) + ret = ble.connect(addr_type, addr) + if ret != 0: + print('ble client connect failed.') + else: + print('ble client connect successful.') + print('') + return ret + + def cancel_connect(self): + ret = ble.cancelConnect(self.scan_report_info['addr']) + if ret != 0: + print('ble client cancel connect failed.') + else: + print('ble client cancel connect successful.') + print('') + return ret + + def disconnect(self): + ret = ble.disconnect(self.connect_id) + if ret != 0: + print('ble client disconnect failed.') + else: + print('ble client disconnect successful.') + print('') + return ret + + def discover_all_service(self): + ret = ble.discoverAllService(self.connect_id) + if ret != 0: + print('ble client discover all service failed.') + else: + print('ble client discover all service successful.') + print('') + return ret + + def discover_service_by_uuid(self): + connect_id = self.connect_id + uuid_type = self.target_service['uuid_type'] + short_uuid = self.target_service['short_uuid'] + long_uuid = self.target_service['long_uuid'] + ret = ble.discoverByUUID(connect_id, uuid_type, short_uuid, long_uuid) + if ret != 0: + print('ble client discover service by uuid failed.') + else: + print('ble client discover service by uuid successful.') + print('') + return ret + + def discover_all_includes(self): + connect_id = self.connect_id + start_handle = self.target_service['start_handle'] + end_handle = self.target_service['end_handle'] + ret = ble.discoverAllIncludes(connect_id, start_handle, end_handle) + if ret != 0: + print('ble client discover all includes failed.') + else: + print('ble client discover all includes successful.') + print('') + return ret + + def discover_all_characteristic(self): + connect_id = self.connect_id + start_handle = self.target_service['start_handle'] + end_handle = self.target_service['end_handle'] + ret = ble.discoverAllChara(connect_id, start_handle, end_handle) + if ret != 0: + print('ble client discover all characteristic failed.') + else: + print('ble client discover all characteristic successful.') + print('') + return ret + + def discover_all_characteristic_descriptor(self): + connect_id = self.connect_id + index = self.characteristic_index + start_handle = self.characteristic_list[index]['value_handle'] + 1 + + if self.characteristic_index == (self.characteristic_count - 1): + end_handle = self.target_service['end_handle'] + print('[1]start_handle = {:#06x}, end_handle = {:#06x}'.format(start_handle - 1, end_handle)) + ret = ble.discoverAllCharaDesc(connect_id, start_handle, end_handle) + else: + end_handle = self.characteristic_list[index+1]['handle'] - 1 + print('[2]start_handle = {:#06x}, end_handle = {:#06x}'.format(start_handle - 1, end_handle)) + ret = ble.discoverAllCharaDesc(connect_id, start_handle, end_handle) + self.characteristic_index += 1 + if ret != 0: + print('ble client discover all characteristic descriptor failed.') + else: + print('ble client discover all characteristic descriptor successful.') + print('') + return ret + + def read_characteristic_by_uuid(self): + connect_id = self.connect_id + index = self.current_chara_index # Modify the value according to actual needs + start_handle = self.characteristic_list[index]['handle'] + end_handle = self.characteristic_list[index]['value_handle'] + uuid_type = 1 + short_uuid = self.characteristic_list[index]['short_uuid'] + long_uuid = bytearray([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]) + + ret = ble.readCharaByUUID(connect_id, start_handle, end_handle, uuid_type, short_uuid, long_uuid) + if ret != 0: + print('ble client read characteristic by uuid failed.') + else: + print('ble client read characteristic by uuid successful.') + print('') + return ret + + def read_characteristic_by_handle(self): + connect_id = self.connect_id + index = self.current_chara_index # Modify the value according to actual needs + handle = self.characteristic_list[index]['value_handle'] + offset = 0 + is_long = 0 + + ret = ble.readCharaByHandle(connect_id, handle, offset, is_long) + if ret != 0: + print('ble client read characteristic by handle failed.') + else: + print('ble client read characteristic by handle successful.') + print('') + return ret + + def read_characteristic_descriptor(self): + connect_id = self.connect_id + index = self.current_desc_index # Modify the value according to actual needs + handle = self.descriptor_list[index]['handle'] + print('handle = {:#06x}'.format(handle)) + is_long = 0 + ret = ble.readCharaDesc(connect_id, handle, is_long) + if ret != 0: + print('ble client read characteristic descriptor failed.') + else: + print('ble client read characteristic descriptor successful.') + print('') + return ret + + def write_characteristic(self): + connect_id = self.connect_id + index = self.current_chara_index # Modify the value according to actual needs + handle = self.characteristic_list[index]['value_handle'] + offset = 0 + is_long = 0 + data = bytearray([0x40, 0x00]) + print('value_handle = {:#06x}, uuid = {:#06x}'.format(handle, self.characteristic_list[index]['short_uuid'])) + ret = ble.writeChara(connect_id, handle, offset, is_long, data) + if ret != 0: + print('ble client write characteristic failed.') + else: + print('ble client read characteristic successful.') + print('') + return ret + + def write_characteristic_no_rsp(self): + connect_id = self.connect_id + index = self.current_chara_index # Modify the value according to actual needs + handle = self.characteristic_list[index]['value_handle'] + data = bytearray([0x20, 0x00]) + print('value_handle = {:#06x}, uuid = {:#06x}'.format(handle, self.characteristic_list[index]['short_uuid'])) + ret = ble.writeCharaNoRsp(connect_id, handle, data) + if ret != 0: + print('ble client write characteristic no rsp failed.') + else: + print('ble client read characteristic no rsp successful.') + print('') + return ret + + def write_characteristic_descriptor(self): + connect_id = self.connect_id + index = self.current_desc_index # Modify the value according to actual needs + handle = self.descriptor_list[index]['handle'] + data = bytearray([0x01, 0x02]) + print('handle = {:#06x}'.format(handle)) + + ret = ble.writeCharaDesc(connect_id, handle, data) + if ret != 0: + print('ble client write characteristic descriptor failed.') + else: + print('ble client read characteristic descriptor successful.') + print('') + return ret + + @staticmethod + def ble_client_callback(args): + global msg_queue + msg_queue.put(args) + + +def ble_gatt_client_event_handler(): + global msg_queue + old_time = 0 + + while True: + cur_time = utime.localtime() + timestamp = "{:02d}:{:02d}:{:02d}".format(cur_time[3], cur_time[4], cur_time[5]) + if cur_time[5] != old_time and cur_time[5] % 5 == 0: + old_time = cur_time[5] + print('[{}]event handler running.....'.format(timestamp)) + print('') + msg = msg_queue.get() # It will be blocked here when there is no message. + # print('msg : {}'.format(msg)) + event_id = msg[0] + status = msg[1] + + if event_id == event.BLE_START_STATUS_IND: + print('') + print('event_id : BLE_START_STATUS_IND, status = {}'.format(status)) + if status == 0: + print('BLE start successful.') + ble_status = ble_client.gatt_get_status() + if ble_status == 0: + print('BLE Status : stopped.') + break + elif ble_status == 1: + print('BLE Status : started.') + else: + print('get ble status error.') + ble_client.gatt_close() + break + + ret = ble_client.set_scan_param() + if ret != 0: + ble_client.gatt_close() + break + ret = ble_client.start_scan() + if ret != 0: + ble_client.gatt_close() + break + else: + print('BLE start failed.') + break + elif event_id == event.BLE_STOP_STATUS_IND: + print('') + print('event_id : BLE_STOP_STATUS_IND, status = {}'.format(status)) + if status == 0: + print('ble stop successful.') + else: + print('ble stop failed.') + break + elif event_id == event.BLE_CONNECT_IND: + print('') + print('event_id : BLE_CONNECT_IND, status = {}'.format(status)) + if status == 0: + ble_client.connect_id = msg[2] + ble_client.connect_addr = msg[3] + addr = ble_client.connect_addr + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('connect_id : {:#x}, connect_addr : {}'.format(ble_client.connect_id, addr_str)) + else: + print('ble connect failed.') + break + elif event_id == event.BLE_DISCONNECT_IND: + print('') + print('event_id : BLE_DISCONNECT_IND, status = {}'.format(status)) + if status == 0: + ble_client.connect_id = msg[2] + ble_client.connect_addr = msg[3] + addr = ble_client.connect_addr + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('connect_id : {:#x}, connect_addr : {}'.format(ble_client.connect_id, addr_str)) + else: + print('ble disconnect failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_UPDATE_CONN_PARAM_IND: + print('') + print('event_id : BLE_UPDATE_CONN_PARAM_IND, status = {}'.format(status)) + if status == 0: + connect_id = msg[2] + max_interval = msg[3] + min_interval = msg[4] + latency = msg[5] + timeout = msg[6] + print('connect_id={},max_interval={},min_interval={},latency={},timeout={}'.format(connect_id,max_interval,min_interval,latency,timeout)) + else: + print('ble update parameter failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_SCAN_REPORT_IND: + if status == 0: + # print(' ble scan successful.') + + ble_client.scan_report_info['event_type'] = msg[2] + ble_client.scan_report_info['name'] = msg[3] + ble_client.scan_report_info['addr_type'] = msg[4] + ble_client.scan_report_info['addr'] = msg[5] + ble_client.scan_report_info['rssi'] = msg[6] + ble_client.scan_report_info['data_len'] = msg[7] + ble_client.scan_report_info['raw_data'] = msg[8] + + device_name = ble_client.scan_report_info['name'] + addr = ble_client.scan_report_info['addr'] + rssi = ble_client.scan_report_info['rssi'] + addr_type = ble_client.scan_report_info['addr_type'] + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + if device_name != '' and rssi != 0: + print('name: {}, addr: {}, rssi: {}, addr_type: {}'.format(device_name, addr_str, rssi, addr_type)) + print('raw_data: {}'.format(ble_client.scan_report_info['raw_data'])) + + if device_name == ble_client.ble_server_name: # Stop scanning once the target device is discovered + ret = ble_client.stop_scan() + if ret != 0: + ble_client.gatt_close() + break + + ret = ble_client.connect() + if ret != 0: + ble_client.gatt_close() + break + else: + print('ble scan failed.') + ret = ble_client.stop_scan() + if ret != 0: + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_MTU: + print('') + print('event_id : BLE_GATT_MTU, status = {}'.format(status)) + if status == 0: + handle = msg[2] + ble_mtu = msg[3] + print('handle = {:#06x}, ble_mtu = {}'.format(handle, ble_mtu)) + else: + print('ble connect mtu failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_RECV_NOTIFICATION_IND: + print('') + print('event_id : BLE_GATT_RECV_NOTIFICATION_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('len={}, data:{}'.format(data_len, data)) + handle = (data[1] << 8) | data[0] + print('handle = {:#06x}'.format(handle)) + else: + print('ble receive notification failed.') + break + elif event_id == event.BLE_GATT_RECV_INDICATION_IND: + print('') + print('event_id : BLE_GATT_RECV_INDICATION_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('len={}, data:{}'.format(data_len, data)) + else: + print('ble receive indication failed.') + break + elif event_id == event.BLE_GATT_START_DISCOVER_SERVICE_IND: + print('') + print('event_id : BLE_GATT_START_DISCOVER_SERVICE_IND, status = {}'.format(status)) + if status == 0: + ble_client.characteristic_count = 0 + ble_client.chara_descriptor_count = 0 + ble_client.characteristic_index = 0 + ble_client.gatt_statue = gatt_status.BLE_GATT_DISCOVER_SERVICE + + if ble_client.discover_service_mode == 0: + print('execute the function discover_all_service.') + ret = ble_client.discover_all_service() + else: + print('execute the function discover_service_by_uuid.') + ret = ble_client.discover_service_by_uuid() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + else: + print('ble start discover service failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_DISCOVER_SERVICE_IND: + print('') + print('event_id : BLE_GATT_DISCOVER_SERVICE_IND, status = {}'.format(status)) + if status == 0: + start_handle = msg[2] + end_handle = msg[3] + short_uuid = msg[4] + print('start_handle = {:#06x}, end_handle = {:#06x}, short_uuid = {:#06x}'.format(start_handle, end_handle, short_uuid)) + if ble_client.discover_service_mode == 0: # discover service all + if ble_client.target_service['short_uuid'] == short_uuid: # Finds the characteristic value by the specified UUID after finding all services + ble_client.target_service['start_handle'] = start_handle + ble_client.target_service['end_handle'] = end_handle + ble_client.gatt_statue = gatt_status.BLE_GATT_DISCOVER_CHARACTERISTIC + print('execute the function discover_all_characteristic.') + ret = ble_client.discover_all_characteristic() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + else: + ble_client.target_service['start_handle'] = start_handle + ble_client.target_service['end_handle'] = end_handle + ble_client.gatt_statue = gatt_status.BLE_GATT_DISCOVER_CHARACTERISTIC + print('execute the function discover_all_characteristic.') + ret = ble_client.discover_all_characteristic() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + else: + print('ble discover service failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_DISCOVER_CHARACTERISTIC_DATA_IND: + print('') + print('event_id : BLE_GATT_DISCOVER_CHARACTERISTIC_DATA_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + pair_len = data[0] + print('pair_len={}, len={}, data:{}'.format(pair_len, data_len, data)) + if data_len > 0: + if ble_client.gatt_statue == gatt_status.BLE_GATT_DISCOVER_CHARACTERISTIC: + i = 0 + while i < (data_len - 1) / pair_len: + chara_dict = { + 'handle': (data[i * pair_len + 2] << 8) | data[i * pair_len + 1], + 'properties': data[i * pair_len + 3], + 'value_handle': (data[i * pair_len + 5] << 8) | data[i * pair_len + 4], + 'uuid_type': 0, + 'short_uuid': 0x0000, + 'long_uuid': bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + } + print('handle={:#06x}, properties={:#x}, value_handle={:#06x}'.format(chara_dict['handle'], chara_dict['properties'], chara_dict['value_handle'])) + if pair_len == ble_client.ble_short_uuid_pair_len: + chara_dict['uuid_type'] = 1 + chara_dict['short_uuid'] = (data[i * pair_len + 7] << 8) | data[i * pair_len + 6] + print('short_uuid:{:#06x}'.format(chara_dict['short_uuid'])) + elif pair_len == ble_client.ble_long_uuid_pair_len: + start_index = i * pair_len + 6 + end_index = start_index + 16 + chara_dict['uuid_type'] = 0 + chara_dict['long_uuid'] = data[start_index : end_index] + print('long_uuid:{}'.format(chara_dict['long_uuid'])) + i += 1 + if ble_client.characteristic_count < 5: + ble_client.characteristic_list.append(chara_dict) + ble_client.characteristic_count = len(ble_client.characteristic_list) + print('characteristic_list len = {}'.format(ble_client.characteristic_count)) + elif ble_client.gatt_statue == gatt_status.BLE_GATT_READ_CHARA_VALUE: + print('data_len = {}'.format(data_len)) + print('pay_load = {:02x},{:02x},{:02x},{:02x}'.format(data[0], data[1], data[2], data[3])) + else: + print('ble discover characteristic failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_DISCOVER_CHARA_DESC_IND: + print('') + print('event_id : BLE_GATT_DISCOVER_CHARA_DESC_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + fmt = data[0] + print('fmt={}, len={}, data:{}'.format(fmt, data_len, data)) + if data_len > 0: + i = 0 + if fmt == 1: # 16 bit uuid + while i < (data_len - 1) / 4: + descriptor_dict = { + 'handle': (data[i * 4 + 2] << 8) | data[i * 4 + 1], + 'short_uuid': (data[i * 4 + 4] << 8) | data[i * 4 + 3], + } + print('handle={:#06x}, uuid={:#06x}'.format(descriptor_dict['handle'], descriptor_dict['short_uuid'])) + i += 1 + if ble_client.chara_descriptor_count < 5: + ble_client.descriptor_list.append(descriptor_dict) + ble_client.chara_descriptor_count = len(ble_client.descriptor_list) + print('descriptor_list len = {}'.format(ble_client.chara_descriptor_count)) + if ble_client.characteristic_index == ble_client.characteristic_count: + print('execute the function read_characteristic_by_uuid.') + # ble_client.gatt_statue = gatt_status.BLE_GATT_WRITE_CHARA_VALUE + # ret = ble_client.write_characteristic() + # ret = ble_client.write_characteristic_no_rsp() + + ble_client.gatt_statue = gatt_status.BLE_GATT_READ_CHARA_VALUE + ret = ble_client.read_characteristic_by_uuid() + # ret = ble_client.read_characteristic_by_handle() + + # ble_client.gatt_statue = gatt_status.BLE_GATT_READ_CHARA_DESC + # ret = ble_client.read_characteristic_descriptor() + + # ble_client.gatt_statue = gatt_status.BLE_GATT_WRITE_CHARA_DESC + # ret = ble_client.write_characteristic_descriptor() + else: + print('execute the function discover_all_characteristic_descriptor.') + ret = ble_client.discover_all_characteristic_descriptor() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + else: + print('ble discover characteristic descriptor failed.') + ble_client.gatt_close() + break + elif event_id == event.BLE_GATT_CHARA_WRITE_WITH_RSP_IND: + print('') + print('event_id : BLE_GATT_CHARA_WRITE_WITH_RSP_IND, status = {}'.format(status)) + if status == 0: + if ble_client.gatt_statue == gatt_status.BLE_GATT_WRITE_CHARA_VALUE: + pass + elif ble_client.gatt_statue == gatt_status.BLE_GATT_WRITE_CHARA_DESC: + pass + else: + print('ble write characteristic with response failed.') + break + elif event_id == event.BLE_GATT_CHARA_WRITE_WITHOUT_RSP_IND: + print('') + print('event_id : BLE_GATT_CHARA_WRITE_WITHOUT_RSP_IND, status = {}'.format(status)) + if status == 0: + print('write characteristic value without response successful.') + else: + print('write characteristic value without response failed.') + break + elif event_id == event.BLE_GATT_CHARA_READ_IND: + print('') + # read characteristic value by handle + print('event_id : BLE_GATT_CHARA_READ_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('data_len = {}, data : {}'.format(data_len, data)) + if ble_client.gatt_statue == gatt_status.BLE_GATT_READ_CHARA_VALUE: + # print('read characteristic value by handle.') + pass + else: + print('ble read characteristic failed.') + break + elif event_id == event.BLE_GATT_CHARA_READ_BY_UUID_IND: + print('') + # read characteristic value by uuid + print('event_id : BLE_GATT_CHARA_READ_BY_UUID_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('data_len = {}, data : {}'.format(data_len, data)) + handle = (data[2] << 8) | data[1] + print('handle = {:#06x}'.format(handle)) + else: + print('ble read characteristic by uuid failed.') + break + elif event_id == event.BLE_GATT_CHARA_MULTI_READ_IND: + print('') + # read multiple characteristic value + print('event_id : BLE_GATT_CHARA_MULTI_READ_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('data_len = {}, data : {}'.format(data_len, data)) + else: + print('ble read multiple characteristic by uuid failed.') + break + elif event_id == event.BLE_GATT_DESC_WRITE_WITH_RSP_IND: + print('') + print('event_id : BLE_GATT_DESC_WRITE_WITH_RSP_IND, status = {}'.format(status)) + if status == 0: + if ble_client.gatt_statue == gatt_status.BLE_GATT_WRITE_CHARA_VALUE: + pass + elif ble_client.gatt_statue == gatt_status.BLE_GATT_WRITE_CHARA_DESC: + pass + else: + print('ble write characteristic descriptor failed.') + break + elif event_id == event.BLE_GATT_DESC_READ_IND: + print('') + # read characteristic descriptor + print('event_id : BLE_GATT_DESC_READ_IND, status = {}'.format(status)) + if status == 0: + data_len = msg[2] + data = msg[3] + print('data_len = {}, data : {}'.format(data_len, data)) + if ble_client.gatt_statue == gatt_status.BLE_GATT_READ_CHARA_DESC: + # print('read characteristic descriptor.') + pass + else: + print('ble read characteristic descriptor failed.') + break + elif event_id == event.BLE_GATT_ATT_ERROR_IND: + print('') + print('event_id : BLE_GATT_ATT_ERROR_IND, status = {}'.format(status)) + if status == 0: + errcode = msg[2] + print('errcode = {:#06x}'.format(errcode)) + if ble_client.gatt_statue == gatt_status.BLE_GATT_DISCOVER_INCLUDES: + ble_client.gatt_statue = gatt_status.BLE_GATT_DISCOVER_CHARACTERISTIC + print('execute the function discover_all_characteristic.') + ret = ble_client.discover_all_characteristic() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + elif ble_client.gatt_statue == gatt_status.BLE_GATT_DISCOVER_CHARACTERISTIC: + ble_client.gatt_statue = gatt_status.BLE_GATT_IDLE + print('execute the function discover_all_characteristic_descriptor.') + ret = ble_client.discover_all_characteristic_descriptor() + if ret != 0: + print('Execution result: Failed.') + ble_client.gatt_close() + break + else: + print('ble attribute error.') + ble_client.gatt_close() + break + else: + print('unknown event id : {}.'.format(event_id)) + + # ble_client.release() + + +event = EVENT(event_dict) +gatt_status = EVENT(gatt_status_dict) +msg_queue = Queue(50) +ble_client = BleClient() + + +def main(): + checknet.poweron_print_once() + print('create client event handler task.') + _thread.start_new_thread(ble_gatt_client_event_handler, ()) + # ble.setScanFilter(0) # Disables scan filter feature. + ret = ble_client.gatt_open() + if ret != 0: + return -1 + + count = 0 + while True: + utime.sleep(1) + count += 1 + cur_time = utime.localtime() + timestamp = "{:02d}:{:02d}:{:02d}".format(cur_time[3], cur_time[4], cur_time[5]) + if count % 5 == 0: + print('[{}] BLE Client running, count = {}......'.format(timestamp, count)) + print('') + if count > 130: # The count is set here for the program to exit itself after running for a while, which is convenient for testing and is actually processed according your actual needs + count = 0 + print('!!!!! stop BLE Client now !!!!!') + ble_status = ble_client.gatt_get_status() + if ble_status == 1: + ble_client.gatt_close() + ble_client.release() + break + else: + ble_status = ble_client.gatt_get_status() + if ble_status == 0: # stopped + print('BLE connection has been disconnected.') + ble_client.release() + break + +if __name__ == '__main__': + main() + +``` + +**Note**: + +Currently, only EC200U/EC600U/EG915U/EG912U/FCM360W series module supports `ble` feature. + +## Initialization Related Features + +### ble.gattStart + +```python +ble.gattStart() +``` + +Enables BLE GATT feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.gattStop + +```python +ble.gattStop() +``` + +Disables BLE GATT feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.getStatus + +```python +ble.getStatus() +``` + +Gets the BLE status. + +**Return Value:** + +- `0` - Disabled; `1` - Enabled ; `-1` - Failed to get the status. + +### ble.getPublicAddr + +```python +ble.getPublicAddr() +``` + +Gets the public address used by the BLE protocol stack. This interface can only be called after BLE has been initialized and started successfully. For example, you can call the interface after the event of event_id being 0 (indicating a successful start) is triggered in the callback. + +**Return Value:** + +- Returns a bytearray type BLE address (size: 6 bytes) for successful execution and returns `-1` for failed execution. + +**Example**: + +```python +>>> addr = ble.getPublicAddr() +>>> print(addr) +b'\xdb3\xf5\x1ek\xac' +>>> mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) +>>> print('mac = [{}]'.format(mac)) +mac = [ac:6b:1e:f5:33:db] +``` + +**Note**: + +If there is a default Bluetooth MAC address set at the factory, the MAC address got by this interface will be the same as the default Bluetooth MAC address. If there is no default setting, the address got by this interface will be a randomly generated static address after the Bluetooth is enabled. Thus, the address will not be the same every time the Bluetooth feature is enabled after the module is rebooted. + +## BLE Server Related Features + +### ble.serverInit + +```python +ble.serverInit(user_cb) +``` + +Initializes BLE Server and registers a callback function. + +**Parameter:** + +- `user_cb` - Function type. Callback function. The meaning of the callback function parameters: `args[0]` is fixed to represent event_id; `args[1]` is fixed to represent the status, `0` indicating successful execution and non-`0` indicating failed execution. The number of callback function parameters is not fixed at two, but depends on the first parameter `args[0]`. The following table lists the number of parameters and explanations for different event IDs. + +| event_id | Parameter Number | Description | +| :------: | :--------------: | ------------------------------------------------------------ | +| 0 | 2 | args[0]: event_id. Starts BT/BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 1 | 2 | args[0]: event_id. Stops BT/BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 16 | 4 | args[0]: event_id. Connects BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: addr. BT/BLE address in bytearray type. | +| 17 | 4 | args[0]: event_id. Disconnects BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: addr. BT/BLE address in bytearray type. | +| 18 | 7 | args[0]: event_id. BLE update connection parameter.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: max_interval. Maximum interval. Interval: 1.25 ms. Range: 6–3200. Time range: 7.5 ms–4 s.
args[4]: min_interval. Minimum interval. Interval: 1.25 ms. Range: 6–3200. Time range: 7.5 ms–4 s.
args[5]: latency. The time at which the slave ignored the connection status event. It should meet the following condition:(1+latecy)\*max_interval\*2\*1.25args[6]: timeout. Disconnect if there is no interaction during the timeout. Interval: 10 ms,Range: 10–3200 ms. Time range: 100 ms–32 s. | +| 20 | 4 | args[0]: event_id. BLE connection MTU.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: handle.
args[3]: MTU value. | +| 21 | 7 | args[0]: event_id. BLE server. When the BLE client writes a characteristic value or descriptor, the server gets the notice.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. The length of the data to be got.
args[3]: data. An array that stores the data got.
args[4]: attr_handle. Integer type. Attribute handle.
args[5]: short_uuid. Integer type.
args[6]: long_uuid. A 16-byte array that stores long UUID. | +| 22 | 7 | args[0]: event_id. When the BLE client reads a characteristic value or descriptor, the server gets the notice.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. The length of the data to be got.
args[3]: data. An array that stores the got data.
args[4]: attr_handle. Integer type, attribute handle.
args[5]: short_uuid. Integer type.
args[6]: long_uuid. A 16-byte array that stores long UUID. | +| 25 | 2 | args[0]: event_id. Server sends notification, and receives notice sent by the peer end.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 63 | 2 | args[0] :event_id. Completion of the SMP pairing process notification.
args[1] :status. The operation status. 0 - successful operation; other values - failed operation. | +| 64 | 5 | args[0] :event_id. user confirmation of the SMP pairing notification.
args[1] :status. The operation status. 0 - successful operation; other values - failed operation.
args[2] :connect_id.
args[3] :pair_mode. Pairing mode, Integer type.
0 - Pairing failure.
1 - Legacy Pairing: Just Works, no PIN code is required.
2 - Legacy Pairing: Passkey Entry output, display PIN code, not need to enter the PIN code.
3 - Legacy Pairing: Passkey Entry input, need to enter the PIN code.
4 - Legacy Pairing: OOB, not support.
5 - Secure Connections Pairing: Just Works, no PIN code is required.
6 - Secure Connections Pairing: Numeric Comparison,display PIN code, not need to enter the PIN code.
7 - Secure Connections Pairing: Passkey Entry output, display PIN code, not need to enter the PIN code.
8 - Secure Connections Pairing: Passkey Entry input, need to enter the PIN code.
9 - Secure Connections Pairing: OOB, not support.
args[4] :pin_code. PIN code, Integer type. | + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_callback(args): + event_id = args[0] + status = args[1] + print('[ble_callback]: event_id={}, status={}'.format(event_id, status)) + + if event_id == 0: # Start BLE + if status == 0: + print('[callback] BLE start success.') + else: + print('[callback] BLE start failed.') + elif event_id == 1: # Stop BLE + if status == 0: + print('[callback] ble stop successful.') + else: + print('[callback] ble stop failed.') + elif event_id == 16: # Connect BLE + if status == 0: + print('[callback] ble connect successful.') + connect_id = args[2] + addr = args[3] # a bytearray + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + else: + print('[callback] ble connect failed.') + elif event_id == 17: # Disconnect BLE + if status == 0: + print('[callback] ble disconnect successful.') + connect_id = args[2] + addr = args[3] # a bytearray + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + else: + print('[callback] ble disconnect failed.') + ble.gattStop() + return + elif event_id == 18: # BLE update connection parameter + if status == 0: + print('[callback] ble update parameter successful.') + connect_id = args[2] + max_interval = args[3] + min_interval = args[4] + latency = args[5] + timeout = args[6] + print('[callback] connect_id={},max_interval={},min_interval={},latency={},timeout={}'.format(connect_id, max_interval, min_interval, latency, timeout)) + else: + print('[callback] ble update parameter failed.') + ble.gattStop() + return + elif event_id == 20: # BLE connection MTU + if status == 0: + print('[callback] ble connect mtu successful.') + handle = args[2] + ble_mtu = args[3] + print('[callback] handle = {:#06x}, ble_mtu = {}'.format(handle, ble_mtu)) + else: + print('[callback] ble connect mtu failed.') + ble.gattStop() + return + elif event_id == 21: # Server:when the BLE client writes a characteristic value or descriptor, the server gets the notice. + if status == 0: + print('[callback] ble recv successful.') + data_len = args[2] + data = args[3] # a bytearray + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # a bytearray + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv failed.') + ble.gattStop() + return + elif event_id == 22: # Server:when the BLE client reads a characteristic value or descriptor, the server gets the notice. + if status == 0: + print('[callback] ble recv read successful.') + data_len = args[2] + data = args[3] # a bytearray + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # a bytearray + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv read failed.') + ble.gattStop() + return + elif event_id == 25: # Server sends notification, and receives notice sent by the peer end + if status == 0: + print('[callback] ble send data successful.') + else: + print('[callback] ble send data failed.') + else: + print('unknown event id.') + +ble.serverInit(ble_callback) +``` + +### ble.serverRelease + +```python +ble.serverRelease() +``` + +Releases BLE server resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.setLocalName + +```python +ble.setLocalName(code, name) +``` + +Sets the BLE name. + +**Parameter:** + +- `code`- Integer type. Encoding scheme. 0 - UTF8,1 - GBK. +- `name`- String type. Encoding scheme. BLE name. The maximum length is 29 bytes. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +>>> ble.setLocalName(0, 'QuecPython-BLE') +0 +``` + +**Note**: + +For BLE, when a device is advertising, if you need the scanning software to discover the name of the advertising device during scanning, it is necessary to include the Bluetooth name in the advertising data or include the device name in the scan response data. + +### ble.setAdvParam + +```python +ble.setAdvParam(min_adv,max_adv,adv_type,addr_type,channel,filter_policy,discov_mode,no_br_edr,enable_adv) +``` + +Sets advertising parameters. + +**Parameter:** + +- See the table below for parameter description: + +| Parameter | Type | Description | +| ------------- | ------------ | ------------------------------------------------------------ | +| min_adv | unsigned int | Minimum advertising interval. Range: 0x0020–0x4000. The calculation is as follows:
Time interval = min_adv \* 0.625. Unit: ms. | +| max_adv | unsigned int | Maximum advertising interval. Range: 0x0020–0x4000. The calculation is as follows:
Time interval = max_adv \* 0.625. Unit: ms. | +| adv_type | unsigned int | Advertising type. The value is as follows:
0 - Connectable undirected advertising (default)
1 - High duty cycle connectable directed advertising
2 - Scannable undirected advertising
3 - Non-connectable undirected advertising
4 - Low duty cycle connectable directed advertising | +| addr_type | unsigned int | Local address type. The value is as follows:
0 - Public address
1 - Random address | +| channel | unsigned int | Advertising channel. The value is as follows:
1 - Channel 37
2 - Channel 38
4 - Channel 39
7 - All three channels above are selected (default) | +| filter_policy | unsigned int | Advertising Filter Policy. The value is as follows:
0 - Allow scan request from any, allow connect request from any
1 - Allow scan request from white list only, allow connect request from any. (Not supported currently)
2 - Allow scan request from any, allow connect request from white list only. (Not supported currently)
3 - Allow scan request from white list only, allow connect request from white list only. (Not supported currently) | +| discov_mode | unsigned int | Discovery mode. Used by GAP protocol. The default value is 2.
1 - Limited discoverable mode
2 - General discoverable mode | +| no_br_edr | unsigned int | Disables BR/EDR. The default value is 1. Set it to 0 to enable BR/EDR. | +| enable_adv | unsigned int | Enables advertising. The default value is 1. Set it to 0 to disable advertising. | + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_set_param(): + min_adv = 0x300 + max_adv = 0x320 + adv_type = 0 # Connectable undirected advertising (default) + addr_type = 0 # Public address + channel = 0x07 + filter_strategy = 0 # Allow scan request from any, allow connect request from any + discov_mode = 2 + no_br_edr = 1 + enable_adv = 1 + ret = ble.setAdvParam(min_adv, max_adv, adv_type, addr_type, channel, filter_strategy, discov_mode, no_br_edr, enable_adv) + if ret != 0: + print('ble_gatt_set_param failed.') + return -1 + print('ble_gatt_set_param success.') + return 0 +``` + +### ble.setAdvData + +```python +ble.setAdvData(data) +``` + +Sets the content of the advertising data. + +**Parameter:** + +- `data`-Bytearray type. Advertising data, with a maximum length of 31 bytes. The content of the advertising data is in the format of `length+type+data`. A combination of multiple sets of data in this format can be included in a single advertising data. In the example below, there are two sets of data combinations: the first one is "0x02, 0x01, 0x05", where 0x02 indicates that there are two data following it, which are 0x01 and 0x05 respectively (0x01 representing the type and 0x05 representing the specific data); the second set is the BLE name data combination, with the length being the BLE name length plus 1, the type being 0x09, and the specific data being the corresponding encoding value of the name. For the specific meanings of the type values, please refer to the official Bluetooth protocol standard document. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_set_data(): + adv_data = [0x02, 0x01, 0x05] + ble_name = "Quectel_ble" + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvData(data) + if ret != 0: + print('ble_gatt_set_data failed.') + return -1 + print('ble_gatt_set_data success.') + return 0 +``` + +### ble.setAdvRspData + +```python +ble.setAdvRspData(data) +``` + +Sets the scan response data. + +**Parameter:** + +- `data`- Bytearray type. Scan response data with a maximum length of 31 bytes. The format for the scan response data is the same as that of the advertising data set by the `setAdvData` function. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_set_rsp_data(): + adv_data = [] + ble_name = "Quectel_ble" + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_rsp_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvRspData(data) + if ret != 0: + print('ble_gatt_set_rsp_data failed.') + return -1 + print('ble_gatt_set_rsp_data success.') + return 0 +``` + +**Note**: + +It is meaningful to set the scan response data only when the client device is in an active scan mode. + +### ble.addService + +```python +ble.addService(primary, server_id, uuid_type, uuid_s, uuid_l) +``` + +Adds a service. + +**Parameter:** + +- `primary`- Integer type. Service type. 1 indicates primary service and other values indicate non-primary service. +- `server_id`- Integer type. Server ID to identify a service. +- `uuid_type`- Integer type. The UUID type. 0 - long UUID (128 bit); 1 - short UUID (16 bit). +- `uuid_s`- Integer type. Short UUID with 2 bytes (16 bit). When `uuid_type` is set to 0, the value is 0. +- `uuid_l`- Bytearray type. Long UUID with 16 bytes (128bit). When `uuid_type` is set to 1, the value is bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_add_service(): + primary = 1 + server_id = 0x01 + uuid_type = 1 # Short UUID + uuid_s = 0x180F + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addService(primary, server_id, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_service failed.') + return -1 + print('ble_gatt_add_service success.') + return 0 +``` + +### ble.addChara + +```python +ble.addChara(server_id, chara_id, chara_prop, uuid_type, uuid_s, uuid_l) +``` + +Adds a characteristic in the service. + +**Parameter:** + +- `server_id`- Integer type. Server ID to identify a service. +- `chara_id`- Integer type. Characteristic ID. +- `chara_prop`-Integer type. Characteristic property. Hexadecimal number. You can specify multiple attributes at the same time by `OR`, and the specific meanings of the values are as shown in the following table: + +| Value | Description | +| ----- | ------------------------------------------------- | +| 0x01 | Advertising | +| 0x02 | Readable | +| 0x04 | Writable and does not require link-layer response | +| 0x08 | Writable | +| 0x10 | Notification | +| 0x20 | Indication | +| 0x40 | Authenticated signed writes | +| 0x80 | Extended property | + +- `uuid_type`-Integer type. The UUID type. 0 - long UUID (128 bit); 1 - short UUID (16 bit). +- `uuid_s`- Integer type. Short UUID with 2 bytes (16 bit). When `uuid_type` is set to 0, the value is 0. +- `uuid_l`- Bytearray type. Long UUID with 16 bytes (128bit). When `uuid_type` is set to 1, the value is bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_add_characteristic(): + server_id = 0x01 + chara_id = 0x01 + chara_prop = 0x02 | 0x10 | 0x20 # 0x02-Readable 0x10-Notification 0x20-Indication + uuid_type = 1 # Short UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addChara(server_id, chara_id, chara_prop, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_characteristic failed.') + return -1 + print('ble_gatt_add_characteristic success.') + return 0 +``` + +### ble.addCharaValue + +```python +ble.addCharaValue(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) +``` + +Adds a characteristic value in the characteristic. + +**Parameter:** + +- `server_id`- Integer type. Server ID to identify a service. +- `chara_id`- Integer type. Characteristic ID. +- `permission`- Integer type. Permission for characteristic value. 2 bytes. Hexadecimal number. You can specify multiple attributes at the same time by `OR`, and the specific meanings of the values are shown in the following table: + +| Value | Description | +| ------ | ----------------------------------------------------- | +| 0x0001 | Readable permission | +| 0x0002 | Writable permission | +| 0x0004 | Authentication permission for read | +| 0x0008 | Authorization permission for read | +| 0x0010 | Encryption permission for read | +| 0x0020 | Authorization and authentication permission for read | +| 0x0040 | Authentication permission for write | +| 0x0080 | Authorization permission for write | +| 0x0100 | Encryption permission for write | +| 0x0200 | Authorization and authentication permission for write | + +- `uuid_type`- Integer type. The UUID type. 0 - long UUID (128 bit); 1 - short UUID (16 bit). +- `uuid_s`- Integer type. Short UUID with 2 bytes (16 bit). When `uuid_type` is set to 0, the value is 0. +- `uuid_l`- Bytearray type. Long UUID with 16 bytes (128bit). When `uuid_type` is set to 1, the value is bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). +- `value`- Bytearray type. Characteristic value data. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_add_characteristic_value(): + data = [] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # Short UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + for i in range(0, 244): + data.append(0x00) + value = bytearray(data) + ret = ble.addCharaValue(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_value failed.') + return -1 + print('ble_gatt_add_characteristic_value success.') + return 0 +``` + +### ble.changeCharaValue + +```python +ble.changeCharaValue(server_id, chara_id, value) +``` + +Changes characteristic value. + +**Parameter:** + +- `server_id`- Integer type. Server ID to identify a service. +- `chara_id`- Integer type. Characteristic ID. + +- `value`- Bytearray type. Characteristic value data. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.addCharaDesc + +```python +ble.addCharaDesc(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) +``` + +Adds a characteristic description in the characteristic. Note that the characteristic description and the characteristic value share the same characteristic. + +**Parameter:** + +- `server_id`- Integer type. Server ID to identify a service. +- `chara_id`- Integer type. Characteristic ID. +- `permission`- Integer type. Permission for characteristic value. 2 bytes. Hexadecimal number. You can specify multiple attributes at the same time by `OR`, and the specific meanings of the values are as shown in the following table: + +| Value | Description | +| ------ | ----------------------------------------------------- | +| 0x0001 | Readable permission | +| 0x0002 | Writable permission | +| 0x0004 | Authentication permission for read | +| 0x0008 | Authorization permission for read | +| 0x0010 | Encryption permission for read | +| 0x0020 | Authorization and authentication permission for read | +| 0x0040 | Authentication permission for write | +| 0x0080 | Authorization permission for write | +| 0x0100 | Encryption permission for write | +| 0x0200 | Authorization and authentication permission for write | + +- `uuid_type`- Integer type. The UUID type. 0 - long UUID (128 bit); 1 - short UUID (16 bit). +- `uuid_s`- Integer type. Short UUID with 2 bytes (16 bit). When `uuid_type` is set to 0, the value is 0. +- `uuid_l`- Bytearray type. Long UUID with 16 bytes (128bit). When `uuid_type` is set to 1, the value is bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def ble_gatt_add_characteristic_desc(): + data = [0x00, 0x00] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # Short UUID + uuid_s = 0x2902 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + value = bytearray(data) + ret = ble.addCharaDesc(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_desc failed.') + return -1 + print('ble_gatt_add_characteristic_desc success.') + return 0 +``` + +### ble.addOrClearService + +```python +ble.addOrClearService(option, mode) +``` + +Adds all the service information that has been added to the module, or clears all the service information that has been added in the module. + +**Parameter:** + +- `option`- Integer type. Operation type. 0 - Clear all services; 1 - Add all services. +- `mode`- Integer type. Whether to keep the default system GAP and GATT service. 0 - Delete; 1 - Keep. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.sendNotification + +```python +ble.sendNotification(connect_id, attr_handle, value) +``` + +Sends notification. + +**Parameter:** + +- `connect_id`- Integer type. Connection ID. +- `attr_handle`- Integer type. Attribute handle. +- `value`- Bytearray type. The data to be sent. The maximum length is MTU. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.sendIndication + +```python +ble.sendIndication(connect_id, attr_handle, value) +``` + +Sends indication. + +**Parameter:** + +- `connect_id`- Integer type. Connection ID. +- `attr_handle`- Integer type. Attribute handle. +- `value`- Bytearray type. The data to be sent. The maximum length is MTU. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.advStart + +```python +ble.advStart() +``` + +Starts advertising. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.advStop + +```python +ble.advStop() +``` + +Stops advertising. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +## BLE Client Related Features + +### ble.clientInit + +```python +ble.clientInit(user_cb) +``` + +Initializes BLE Client and registers a callback function. + +**Parameter:** + +- `user_cb`- Function type. Callback function. The meaning of the callback function parameters: `args[0]` is fixed to represent event_id; `args[1]` is fixed to represent the status, `0` indicating successful execution and non-`0` indicating failed execution. The number of callback function parameters is not fixed at two, but depends on the first parameter `args[0]`. The following table lists the number of parameters and explanations for different event IDs. + +| event_id | Parameter Number | Description | +| :------: | :--------------: | ------------------------------------------------------------ | +| 0 | 2 | args[0]: event_id. Starts BT/BLE
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 1 | 2 | args[0]: event_id. Stops BT/BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 16 | 4 | args[0]: event_id. Connects BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: addr. BT/BLE address in bytearray type. | +| 17 | 4 | args[0]: event_id. Disconnects BLE.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: addr. BT/BLE address in bytearray type. | +| 18 | 7 | args[0]: event_id. BLE update connection parameter.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: connect_id.
args[3]: max_interval. Maximum interval. Interval: 1.25 ms. Range: 6–3200. Time range: 7.5 ms–4 s.
args[4]: min_interval. Minimum interval. Interval: 1.25 ms. Range: 6–3200. Time range: 7.5 ms–4 s.
args[5]: latency. The time at which the slave ignored the connection status event. It should meet the following condition:(1+latecy)\*max_interval\*2\*1.25args[6]: timeout. Disconnect if there is no interaction during the timeout. Interval: 10ms,Range: 10–3200 ms. Time range: 100 ms–32 s. | +| 19 | 9 | args[0]: event_id. BLE scan report.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: event_type.
args[3]: The name of the scanned device.
args[4]: Device address type.
args[5]: Device address in bytearray type.
args[6]: rssi. Signal strength.
args[7]: data_len. The length of the raw data scanned.
args[8]: data. The raw data scanned. | +| 20 | 4 | args[0]: event_id. BLE connection MTU.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: handle.
args[3]: MTU value. | +| 23 | 4 | args[0]: event_id. Client receives notification.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data containing handle and other data. The format and description of the raw data is described in the example at the beginning. | +| 24 | 4 | args[0]: event_id. Client receives indication.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data containing indication. The format and description of the raw data is described in the example at the beginning. | +| 26 | 2 | args[0]: event_id. Starts discover service.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 27 | 5 | args[0]: event_id. Discovers service.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: start_handle. The start handle of the service.
args[3]: end_handle. The end handle of the service.
args[4]: UUID, indicating the UUID of the service (Short UUID). | +| 28 | 4 | args[0]: event_id. Discovers characteristic.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data containing handle, attribute, UUID and other data. The format and description of the raw data is described in the example at the beginning. | +| 29 | 4 | args[0]: event_id. Discovers characteristic descriptor.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data containing handle, UUID and other data. The format and description of the raw data is described in the example at the beginning. | +| 30 | 2 | args[0]: event_id. Writes characteristic value with peer response.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 31 | 2 | args[0]: event_id. Writes characteristic value without peer response.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 32 | 4 | args[0]: event_id. Reads characteristic value by handle.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data. | +| 33 | 4 | args[0]: event_id. Reads characteristic value by UUID.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data. | +| 34 | 4 | args[0]: event_id. Reads multiple characteristic value.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data. | +| 35 | 2 | args[0]: event_id. Writes characteristic descriptor.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 36 | 4 | args[0]: event_id. Reads characteristic descriptor.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. Data length.
args[3]: data. Raw data. | +| 37 | 3 | args[0]: event_id. Attribute error.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: errcode. Error code. | +| 63 | 2 | args[0] :event_id. Completion of the SMP pairing process notification.
args[1] :status. The operation status. 0 - successful operation; other values - failed operation. | +| 64 | 5 | args[0] :event_id. user confirmation of the SMP pairing notification.
args[1] :status. The operation status. 0 - successful operation; other values - failed operation.
args[2] :connect_id.
args[3] :pair_mode. Pairing mode, Integer type.
0 - Pairing failure.
1 - Legacy Pairing: Just Works, no PIN code is required.
2 - Legacy Pairing: Passkey Entry output, display PIN code, not need to enter the PIN code.
3 - Legacy Pairing: Passkey Entry input, need to enter the PIN code.
4 - Legacy Pairing: OOB, not support.
5 - Secure Connections Pairing: Just Works, no PIN code is required.
6 - Secure Connections Pairing: Numeric Comparison,display PIN code, not need to enter the PIN code.
7 - Secure Connections Pairing: Passkey Entry output, display PIN code, not need to enter the PIN code.
8 - Secure Connections Pairing: Passkey Entry input, need to enter the PIN code.
9 - Secure Connections Pairing: OOB, not support.
args[4] :pin_code. PIN code, Integer type. | + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.clientRelease + +```python +ble.clientRelease() +``` + +Releases BLE client resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.setScanParam + +```python +ble.setScanParam(scan_mode, interval, scan_window, filter_policy, addr_type) +``` + +Sets the scan parameters. + +**Parameter:** + +- `scan_mode`- Integer type. Scan mode. `0` indicates passive scanning and `1` indicating active scanning. Default value: `1`. +- `interval`- Integer type. Scan interval. Range: 0x0004–0x4000. Time interval = `interval` \* 0.625. Unit: ms. +- `scan_window`- Integer type. Scanning time for a single scan. Range: 0x0004–0x4000. Scan time = `scan_window`\* 0.625. Unit: ms. +- `filter_policy`- Integer type. Scan filter policy. Default value: `0`. `0` - Allow all advertisement packets except directed advertising packets not addressed to this device. `1` - Allow only advertisement packets from devices where the advertiser’s address is in the Whitelist. and directed advertising packets which are not addressed for this device shall be ignored. `2` - Allow all undirected advertisement packets, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. `3` - Allow all advertisement packets from devices where the advertiser’s address is in the Whitelist, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. +- `addr_type`- Integer type. Local address type. 0 - Public address; 1 - Random address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Note**: + +The `scan_window` should not be greater than the `interval`. If they are equal, it indicates continuous scanning, and the BLE controller will run continuously, occupying system resources and preventing other tasks from being executed. Therefore, continuous scanning is not allowed. It is also not recommended to set the time interval too short, because more frequent scanning consumes more power. + +### ble.scanStart + +```python +ble.scanStart() +``` + +Starts scanning. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.scanStop + +```python +ble.scanStop() +``` + +Stops scanning. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.setScanFilter + +```python +ble.setScanFilter(act) +``` + +Enables or disables scan filtering. If enabled, only one advertising data packet from the same device will be reported during the scan; if disabled, all advertising data packets from the same device will be reported. + +**Parameter:** + +- `act`-Integer type. Controls whether to enable scan filtering. `0` - Disable; `1` - Enable. Default value: 1. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.connect + +```python +ble.connect(addr_type, addr) +``` + +Connects the device according to the specified device address. + +**Parameter:** + +- `addr_type`- Integer type. Address type. 0 - Public address; 1 - Random address. +- `addr`- Bytearray type. BLE address. Size: 6 bytes. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.cancelConnect + +```python +ble.cancelConnect(addr) +``` + +Cancels the connection that is being established. + +**Parameter:** + +- `addr`- Bytearray type. BLE address. Size: 6 bytes. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.disconnect + +```python +ble.disconnect(connect_id) +``` + +Disconnects the connection that has been established. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.discoverAllService + +```python +ble.discoverAllService(connect_id) +``` + +Discovers all services. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.discoverByUUID + +```python +ble.discoverByUUID(connect_id, uuid_type, uuid_s, uuid_l) +``` + +Discovers the services of specified UUID. + +**Parameter:** + +- `connect_id` - Integer type. The connection ID obtained when the connection was established. +- `uuid_type` - Integer type. UUID type. `0` - Long UUID (128 bit); `1` - Short UUID (16 bit) +- `uuid_s` - Integer type. Short UUID, 2 bytes (16 bit). When `uuid_type` is set to 0, the `uuid_s` is 0. +- `uuid_l` - Bytearray type. Long UUID, 16 bytes (128 bit). When `uuid_type` is set to 1, the `uuid_l` is bytearray ([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.discoverAllIncludes + +```python +ble.discoverAllIncludes(connect_id, start_handle, end_handle) +``` + +Discovers all includes. The `start_handle` and `end_handle` should be in the same service. + +**Parameter:** + +- `connect_id` - Integer type. The connection ID obtained when the connection was established. +- `start_handle`- Integer type. Start handle. Start discovering includes from this handle. +- `end_handle`- Integer type. End handle. Stop discovering includes from this handle. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.discoverAllChara + +```python +ble.discoverAllChara(connect_id, start_handle, end_handle) +``` + +Discovers all characteristics. The `start_handle` and `end_handle` should be in the same service. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `start_handle`- Integer type. Start handle. Start discovering characteristics from this handle. +- `end_handle`- Integer type. End handle. Stop discovering characteristics from this handle. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.discoverAllCharaDesc + +```python +ble.discoverAllCharaDesc(connect_id, start_handle, end_handle) +``` + +Discovers all characteristic descriptions. The `start_handle` and `end_handle` should be in the same service. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `start_handle`- Integer type. Start handle. Start discovering characteristic descriptions from this handle. +- `end_handle`- Integer type. End handle. This Stop discovering characteristic descriptions from this handle. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.readCharaByUUID + +```python +ble.readCharaByUUID(connect_id, start_handle, end_handle, uuid_type, uuid_s, uuid_l) +``` + +Reads the characteristic value of specified UUID. The `start_handle` and `end_handle` must contain a characteristic value handle. + +**Parameter:** + +- `connect_id`- Integer type. Connection ID. The connection ID obtained when the connection was established. +- `start_handle`- Integer type. Start handle. The `start_handle` and `end_handle` should be in the same service. +- `end_handle`- Integer type. End handle. The `start_handle` and `end_handle` should be in the same service. +- `uuid_type` - Integer type. UUID type. `0` - Long UUID (128 bit); `1` - Short UUID (16 bit) +- `uuid_s`- Integer type. Short UUID, 2 bytes (16 bit). When `uuid_type` is set to 0, the `uuid_s` is 0. +- `uuid_l`- Bytearray type. Long UUID, 16 bytes (128 bit). When `uuid_type` is set to 1, the `uuid_l` is bytearray ([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]). + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.readCharaByHandle + +```python +ble.readCharaByHandle(connect_id, handle, offset, is_long) +``` + +Reads the characteristic value of specified handle. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `handle`- Integer type. Characteristic value handle. +- `offset`- Integer type. Offset. +- `is_long`- Integer type. Long characteristic value flag. `0` indicates short characteristic value which can be finished reading at one time; `1` indicates long characteristic value which needs to be read by multiple times. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.readCharaDesc + +```python +ble.readCharaDesc(connect_id, handle, is_long) +``` + +Reads the characteristic description. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `handle`- Integer type. Characteristic value handle. +- `is_long`- Integer type. Long characteristic value flag. `0` indicates short characteristic value which can be finished reading at one time;`1` indicates long characteristic value which needs to be read by multiple times. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.writeChara + +```python +ble.writeChara(connect_id, handle, offset, is_long, data) +``` + +Writes the characteristic value with peer response. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `handle`- Integer type. Characteristic value handle. +- `offset`- Integer type. Offset. +- `is_long`- Integer type. Long characteristic value flag. `0` indicates short characteristic value which can be finished reading at one time; `1` indicates long characteristic value which needs to be read by multiple times. +- `data`- Bytearray type. Characteristic value data. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.writeCharaNoRsp + +```python +ble.writeCharaNoRsp(connect_id, handle, data) +``` + +Writes the characteristic value without peer response. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `handle`- Integer type. Characteristic value handle. +- `data`- Bytearray type. Characteristic value data. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.writeCharaDesc + +```python +ble.writeCharaDesc(connect_id, handle, data) +``` + +Writes the characteristic description. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. +- `handle`- Integer type. Characteristic description handle. +- `data`- Bytearray type. Characteristic description data. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### ble.exchangeMtu + +```python +ble.exchangeMtu(connect_id, mtu_size) +``` + +Send MTU exchange request. The MTU exchange request should be initiated by the client. + +**Parameter:** + +- `connect_id`-Integer type. The connection ID obtained when the connection was established. +- `mtu_size`-MTU size。 + +**Return Value:** + +* `0`- Successful execution; `-1`- Failed execution. + + + +## BLE SMP Related Features + +### ble.smpSetConfig + +```python +ble.smpSetConfig(io_cap, auth_req, passkey, timeout) +``` + +config the pairing capabilities. + +**Parameter:** + +* `io_cap`-Integer type. Device input and output capabilities. Default value is 3. + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| 0 | Device has the ability to display a 6 digit decimal number. | +| 1 | Device only has the ability to display Yes/No, cant not display PIN. | +| 2 | Device only has the ability to input PIN. | +| 3 | Device has no input or output capabilities. | +| 4 | Device has input or output capabilities, can display PIN and enter PIN. | + +- `auth_req`-Integer type. Authentication request parameters. Default value: 9. + +| | Bit0 | Bit1 | Bit2 | Bit3 | +| ---- | ----------------------- | -------- | --------------- | ----------------------------- | +| 0 | not bound after pairing | reserved | not enable MITM | use legacy pairing | +| 1 | bound after pairing | reserved | enable MITM | use secure connection pairing | + +- `passkey`-Integer type. The PIN code displayed during the pairing process. Default value: 123456. +- `timeout`-Integer type. Pairing timeout time, the unit is 100ms. Default value: 160. + +**Return Value:** + +* `0`- Successful execution; `-1`- Failed execution. + +**Pairing method selection instructions:** + +BLE smp pairing has two modes: `Legacy Pairing` and `Secure Connections Pairing`. There are specifically the following 4 pairing methods: + +* OOB + +* Just Works + +* Passkey Entry + +* Numeric Comparison (For LE Secure Connections Pairing) + +The specific pairing method to choose is decided by the two parties after exchanging their respective IO capabilities. It is basically divided into the following stages: + +Stage 1: The pairing parties will first confirm whether to use `Legacy Pairing` or `Secure Connections Pairing` mode for pairing. The principle is: only if both parties set the `Secure Connections Pairing` flag, this pairing mode will be used, otherwise` Legacy Pairing`. + +Stage 2: Determine whether OOB is supported. For the `Legacy Pairing` mode, the OOB method will be used only if both parties support OOB. For `Secure Connections Pairing` mode, if `Initiator` supports OOB, use OOB mode. + +Stage 3: Check MITM (Man-in-the-Middle). If neither party is configured with the MITM flag, the `Just Works` method is used to pair directly. Otherwise, the pairing method is selected based on the IO capabilities of both parties. + +Stage 4: Choose the pairing method based on the IO capabilities of both parties. + +For specific instructions on Stage 2 ~ Stage 4, please refer to the content of Chapter ***2.3.5.1 Selecting Key Generation Method*** in the official Bluetooth manual document "**BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part H]**". + +### ble.smpGetConfig + +```python +ble.smpGetConfig(io_cap, auth_req, passkey, timeout) +``` + +query the pairing capabilities. + +**Return Value:** + +`-1`- Failed execution; returns the following value when successful execution. + +* `io_cap`-Integer type. Device input and output capabilities. Default value is 3. + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| 0 | Device has the ability to display a 6 digit decimal number. | +| 1 | Device only has the ability to display Yes/No, cant not display PIN. | +| 2 | Device only has the ability to input PIN. | +| 3 | Device has no input or output capabilities. | +| 4 | Device has input or output capabilities, can display PIN and enter PIN. | + +- `auth_req`-Integer type. Authentication request parameters. Default value: 9. + +| | Bit0 | Bit1 | Bit2 | Bit3 | +| ---- | ----------------------- | -------- | --------------- | ----------------------------- | +| 0 | not bound after pairing | reserved | not enable MITM | use legacy pairing | +| 1 | bound after pairing | reserved | enable MITM | use secure connection pairing | + +- `passkey`-Integer type. The PIN code displayed during the pairing process. Default value: 123456. +- `timeout`-Integer type. Pairing timeout time, the unit is 100ms. Default value: 160. + +### ble.smpStartPair + +```python +ble.smpStartPair(connect_id) +``` + +Start the BLE SMP pairing process. SMP pairing is initiated by the client, and the server can notify the client to initiate SMP pairing requests. + +**Parameter:** + +- `connect_id`- Integer type. The connection ID obtained when the connection was established. + +**Return Value:** + +`0`- Successful execution; `-1`- Failed execution. + +### ble.smpUserConfirm + +```python +ble.smpUserConfirm(connect_id, pair_operation, pin) +``` + +Confirm pairing. Whether to accept the pairing request. + +**Parameter:** + +* `connect_id`-Integer type. The connection ID obtained when the connection was established. + +* `pair_operation`-Integer type. The operation type of the pairing. 0 - cancel pairing, 1 - accept pairing, not carry a PIN code(used in Just Work or Number Comparison mode), 2 - accept pairing, carry a PIN code(used in Passkey mode). + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| 0 | Cancel pairing, This operation is only possible during pairing, and it will cause the Bluetooth connection to be lost. | +| 1 | Accept pairing, not carry a PIN code(used in Just Works or Numeric Comparison mode). | +| 2 | Accept pairing, carry a PIN code(used in Passkey mode). | + +- `pin`- Integer type. PIN code. + +**Return Value:** + +`0`- Successful execution; `-1`- Failed execution. + +### ble.smpGetPairedDevInfo + +```python +ble.smpGetPairedDevInfo() +``` + +Get paired device information. + +**Return Value:** + +`0`- Successful execution; `-1`- Failed execution. + +- `addr_list`- List type, the list element is bytearray type. List of BLE addresses of paired devices. + +### ble.smpRemovePairedDev + +```python +ble.smpRemovePairedDev(addr) +``` + +Delete the specified paired device information. + +**Parameter:** + +- `addr`- bytearray type. BLE address of the device to be deleted. (size: 6 bytes) + +**Return Value:** + +`0`- Successful execution; `-1`- Failed execution. + +### ble.smpCleanPairedDev + +```python +ble.smpCleanPairedDev() +``` + +Delete all paired device information. + +**Return Value:** + +`0`- Successful execution; `-1`- Failed execution. + +> **Note**: The above BLE SMP-related interfaces must be executed with the BLE already initialized, otherwise they will return a failure. And BLE SMP functionality is currently only supported in EC200UEUAA model specific firmware. + diff --git a/docs/API_reference/en/btlib/bt.md b/docs/API_reference/en/btlib/bt.md new file mode 100644 index 0000000000000000000000000000000000000000..483536599349c388bda6f64103136e120daa2f26 --- /dev/null +++ b/docs/API_reference/en/btlib/bt.md @@ -0,0 +1,1556 @@ +# bt - Classic Bluetooth + +The `bt` module provides Classic Bluetooth related features, including HFP, A2DP, AVRCP and SPP. + +**Example**: + +```python +#HFP demo program + +""" +This example demonstrates a feature for automatically answering calls through HFP. +Platform: EC600UCN_LB Uranium development board. +After running this program, search for the device name on phone A and click to connect. Then, make a call from phone B to phone A. When phone A starts ringing and vibrating, the device will automatically answer the call. +""" +import bt +import utime +import _thread +from queue import Queue +from machine import Pin + +# If an external PA is connected to the corresponding playback channel and pin control is required to turn on the PA, follow the steps below +# The specific GPIO used depends on the actual pin used. +gpio11 = Pin(Pin.GPIO11, Pin.OUT, Pin.PULL_DISABLE, 0) +gpio11.write(1) + +BT_NAME = 'QuecPython-hfp' + +BT_EVENT = { + 'BT_START_STATUS_IND': 0, # bt/ble start + 'BT_STOP_STATUS_IND': 1, # bt/ble stop + 'BT_HFP_CONNECT_IND': 40, # bt hfp connected + 'BT_HFP_DISCONNECT_IND': 41, # bt hfp disconnected + 'BT_HFP_CALL_IND': 42, # bt hfp call state + 'BT_HFP_CALL_SETUP_IND': 43, # bt hfp call setup state + 'BT_HFP_NETWORK_IND': 44, # bt hfp network state + 'BT_HFP_NETWORK_SIGNAL_IND': 45, # bt hfp network signal + 'BT_HFP_BATTERY_IND': 46, # bt hfp battery level + 'BT_HFP_CALLHELD_IND': 47, # bt hfp callheld state + 'BT_HFP_AUDIO_IND': 48, # bt hfp audio state + 'BT_HFP_VOLUME_IND': 49, # bt hfp volume type + 'BT_HFP_NETWORK_TYPE': 50, # bt hfp network type + 'BT_HFP_RING_IND': 51, # bt hfp ring indication + 'BT_HFP_CODEC_IND': 52, # bt hfp codec type +} + +HFP_CONN_STATUS = 0 +HFP_CONN_STATUS_DICT = { + 'HFP_DISCONNECTED': 0, + 'HFP_CONNECTING': 1, + 'HFP_CONNECTED': 2, + 'HFP_DISCONNECTING': 3, +} +HFP_CALL_STATUS = 0 +HFP_CALL_STATUS_DICT = { + 'HFP_NO_CALL_IN_PROGRESS': 0, + 'HFP_CALL_IN_PROGRESS': 1, +} + +BT_IS_RUN = 0 + +msg_queue = Queue(30) + + +def get_key_by_value(val, d): + for key, value in d.items(): + if val == value: + return key + return None + +def bt_callback(args): + global msg_queue + msg_queue.put(args) + +def bt_event_proc_task(): + global msg_queue + global BT_IS_RUN + global BT_EVENT + global HFP_CONN_STATUS + global HFP_CONN_STATUS_DICT + global HFP_CALL_STATUS + global HFP_CALL_STATUS_DICT + + while True: + print('wait msg...') + msg = msg_queue.get() # It will be blocked here when there is no message. + event_id = msg[0] + status = msg[1] + + if event_id == BT_EVENT['BT_START_STATUS_IND']: + print('event: BT_START_STATUS_IND') + if status == 0: + print('BT start successfully.') + BT_IS_RUN = 1 + bt_status = bt.getStatus() + if bt_status == 1: + print('BT status is 1, normal status.') + else: + print('BT status is {}, abnormal status.'.format(bt_status)) + bt.stop() + break + + retval = bt.getLocalName() + if retval != -1: + print('The current BT name is : {}'.format(retval[1])) + else: + print('Failed to get BT name.') + bt.stop() + break + + print('Set BT name to {}'.format(BT_NAME)) + retval = bt.setLocalName(0, BT_NAME) + if retval != -1: + print('BT name set successfully.') + else: + print('BT name set failed.') + bt.stop() + break + + retval = bt.getLocalName() + if retval != -1: + print('The new BT name is : {}'.format(retval[1])) + else: + print('Failed to get new BT name.') + bt.stop() + break + + # Sets the Bluetooth visible mode to discoverable and connectable + retval = bt.setVisibleMode(3) + if retval == 0: + mode = bt.getVisibleMode() + if mode == 3: + print('BT visible mode set successfully.') + else: + print('BT visible mode set failed.') + bt.stop() + break + else: + print('BT visible mode set failed.') + bt.stop() + break + else: + print('BT start failed.') + bt.stop() + break + elif event_id == BT_EVENT['BT_STOP_STATUS_IND']: + print('event: BT_STOP_STATUS_IND') + if status == 0: + BT_IS_RUN = 0 + print('BT stop successfully.') + else: + print('BT stop failed.') + break + elif event_id == BT_EVENT['BT_HFP_CONNECT_IND']: + HFP_CONN_STATUS = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_CONNECT_IND, {}, hfp_conn_status:{}, mac:{}'.format(status, get_key_by_value(msg[2], HFP_CONN_STATUS_DICT), mac)) + if status != 0: + print('BT HFP connect failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_DISCONNECT_IND']: + HFP_CONN_STATUS = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_DISCONNECT_IND, {}, hfp_conn_status:{}, mac:{}'.format(status, get_key_by_value(msg[2], HFP_CONN_STATUS_DICT), mac)) + if status != 0: + print('BT HFP disconnect failed.') + bt.stop() + elif event_id == BT_EVENT['BT_HFP_CALL_IND']: + call_sta = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_CALL_IND, {}, hfp_call_status:{}, mac:{}'.format(status, get_key_by_value(msg[2], HFP_CALL_STATUS_DICT), mac)) + if status != 0: + print('BT HFP call failed.') + bt.stop() + continue + + if call_sta == HFP_CALL_STATUS_DICT['HFP_NO_CALL_IN_PROGRESS']: + if HFP_CALL_STATUS == HFP_CALL_STATUS_DICT['HFP_CALL_IN_PROGRESS']: + HFP_CALL_STATUS = call_sta + if HFP_CONN_STATUS == HFP_CONN_STATUS_DICT['HFP_CONNECTED']: + print('call ended, ready to disconnect hfp.') + retval = bt.hfpDisconnect(addr) + if retval == 0: + HFP_CONN_STATUS = HFP_CONN_STATUS_DICT['HFP_DISCONNECTING'] + else: + print('Failed to disconnect hfp connection.') + bt.stop() + continue + else: + if HFP_CALL_STATUS == HFP_CALL_STATUS_DICT['HFP_NO_CALL_IN_PROGRESS']: + HFP_CALL_STATUS = call_sta + print('set audio output channel to 2.') + bt.setChannel(2) + print('set volume to 7.') + retval = bt.hfpSetVolume(addr, 7) + if retval != 0: + print('set volume failed.') + elif event_id == BT_EVENT['BT_HFP_CALL_SETUP_IND']: + call_setup_status = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_CALL_SETUP_IND, {}, hfp_call_setup_status:{}, mac:{}'.format(status, call_setup_status, mac)) + if status != 0: + print('BT HFP call setup failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_CALLHELD_IND']: + callheld_status = msg[2] + addr = msg[3] #MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_CALLHELD_IND, {}, callheld_status:{}, mac:{}'.format(status, callheld_status, mac)) + if status != 0: + print('BT HFP callheld failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_NETWORK_IND']: + network_status = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_NETWORK_IND, {}, network_status:{}, mac:{}'.format(status, network_status, mac)) + if status != 0: + print('BT HFP network status failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_NETWORK_SIGNAL_IND']: + network_signal = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_NETWORK_SIGNAL_IND, {}, signal:{}, mac:{}'.format(status, network_signal, mac)) + if status != 0: + print('BT HFP network signal failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_BATTERY_IND']: + battery_level = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_BATTERY_IND, {}, battery_level:{}, mac:{}'.format(status, battery_level, mac)) + if status != 0: + print('BT HFP battery level failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_AUDIO_IND']: + audio_status = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_AUDIO_IND, {}, audio_status:{}, mac:{}'.format(status, audio_status, mac)) + if status != 0: + print('BT HFP audio failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_VOLUME_IND']: + volume_type = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_VOLUME_IND, {}, volume_type:{}, mac:{}'.format(status, volume_type, mac)) + if status != 0: + print('BT HFP volume failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_NETWORK_TYPE']: + service_type = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_NETWORK_TYPE, {}, service_type:{}, mac:{}'.format(status, service_type, mac)) + if status != 0: + print('BT HFP network service type failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_RING_IND']: + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_RING_IND, {}, mac:{}'.format(status, mac)) + if status != 0: + print('BT HFP ring failed.') + bt.stop() + continue + retval = bt.hfpAnswerCall(addr) + if retval == 0: + print('The call was answered successfully.') + else: + print('Failed to answer the call.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_HFP_CODEC_IND']: + codec_type = msg[2] + addr = msg[3] # MAC address of BT host + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('BT_HFP_CODEC_IND, {}, codec_type:{}, mac:{}'.format(status, codec_type, mac)) + if status != 0: + print('BT HFP codec failed.') + bt.stop() + continue + print('Ready to release hfp.') + bt.hfpRelease() + bt.release() + + +def main(): + global BT_IS_RUN + + _thread.start_new_thread(bt_event_proc_task, ()) + + retval = bt.init(bt_callback) + if retval == 0: + print('BT init successful.') + else: + print('BT init failed.') + return -1 + retval = bt.hfpInit() + if retval == 0: + print('HFP init successful.') + else: + print('HFP init failed.') + return -1 + retval = bt.start() + if retval == 0: + print('BT start successful.') + else: + print('BT start failed.') + retval = bt.hfpRelease() + if retval == 0: + print('HFP release successful.') + else: + print('HFP release failed.') + retval = bt.release() + if retval == 0: + print('BT release successful.') + else: + print('BT release failed.') + return -1 + + count = 0 + while True: + utime.sleep(1) + count += 1 + cur_time = utime.localtime() + timestamp = "{:02d}:{:02d}:{:02d}".format(cur_time[3], cur_time[4], cur_time[5]) + + if count % 5 == 0: + if BT_IS_RUN == 1: + print('[{}] BT HFP is running, count = {}......'.format(timestamp, count)) + print('') + else: + print('BT HFP has stopped running, ready to exit.') + break + + +if __name__ == '__main__': + main() + +``` + +```python +#A2DP/AVRCP demo program + +""" +This example demonstrates a simple Bluetooth music playback control feature through A2DP/AVRCP. +Once you run the example code, search for the device name on your phone and connect to it. Open your music playback software, then return to the demo program interface to follow the prompt menu to input the corresponding command to control your music playback. You can play, pause, switch to the previous or next song, and adjust the volume. +""" +import bt +import utime +import _thread +from queue import Queue +from machine import Pin + +BT_STATUS_DICT = { + 'BT_NOT_RUNNING': 0, + 'BT_IS_RUNNING': 1 +} + +A2DP_AVRCP_CONNECT_STATUS = { + 'DISCONNECTED': 0, + 'CONNECTING': 1, + 'CONNECTED': 2, + 'DISCONNECTING': 3 +} + +host_addr = 0 +msg_queue = Queue(10) + +# If an external PA is connected to the corresponding playback channel and pin control is required to turn on the PA, follow the steps below +# The specific GPIO used depends on the actual pin used. +gpio11 = Pin(Pin.GPIO11, Pin.OUT, Pin.PULL_DISABLE, 0) +gpio11.write(1) + + +def cmd_proc(cmd): + cmds = ('1', '2', '3', '4', '5') + vols = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11') + + if cmd in cmds: + if cmd == '5': + while True: + tmp = input('Please input volume: ') + if len(tmp) != 1: + vol = tmp.split('Please input volume: ')[1] + else: + vol = tmp + if vol in vols: + return cmd, int(vol) + else: + print('Volume should be in [0,11], try again.') + else: + return cmd, 0 + else: + print('Command {} is not supported!'.format(cmd)) + return -1 + +def avrcp_play(args): + return bt.avrcpStart() + +def avrcp_pause(args): + return bt.avrcpPause() + +def avrcp_prev(args): + return bt.avrcpPrev() + +def avrcp_next(args): + return bt.avrcpNext() + +def avrcp_set_volume(vol): + return bt.avrcpSetVolume(vol) + +def bt_callback(args): + pass + +def bt_a2dp_avrcp_proc_task(): + global msg_queue + + cmd_handler = { + '1': avrcp_play, + '2': avrcp_pause, + '3': avrcp_prev, + '4': avrcp_next, + '5': avrcp_set_volume, + } + while True: + # print('wait msg...') + msg = msg_queue.get() + print('recv msg: {}'.format(msg)) + cmd_handler.get(msg[0])(msg[1]) + + +def main(): + global host_addr + global msg_queue + + _thread.start_new_thread(bt_a2dp_avrcp_proc_task, ()) + bt.init(bt_callback) + bt.setChannel(2) + retval = bt.a2dpavrcpInit() + if retval == 0: + print('BT A2DP/AVRCP initialization succeeded.') + else: + print('BT A2DP/AVRCP initialization failed.') + return -1 + + retval = bt.start() + if retval != 0: + print('BT start failed.') + return -1 + + utime.sleep_ms(1500) + + old_name = bt.getLocalName() + if old_name == -1: + print('Get BT name error.') + return -1 + print('The current BT name is {}'.format(old_name[1])) + new_name = 'QuecPython-a2dp' + print('Set new BT name to {}'.format(new_name)) + retval = bt.setLocalName(0, new_name) + if retval == -1: + print('Set BT name failed.') + return -1 + cur_name = bt.getLocalName() + if cur_name == -1: + print('Get new BT name error.') + return -1 + else: + if cur_name[1] == new_name: + print('BT name changed successfully.') + else: + print('BT name changed failed.') + + visible_mode = bt.getVisibleMode() + if visible_mode != -1: + print('The current BT visible mode is {}'.format(visible_mode)) + else: + print('Get BT visible mode error.') + return -1 + + print('Set BT visible mode to 3.') + retval = bt.setVisibleMode(3) + if retval == -1: + print('Set BT visible mode error.') + return -1 + + print('BT reconnect check start......') + bt.reconnect_set(25, 2) + bt.reconnect() + + count = 0 + while True: + count += 1 + if count % 5 == 0: + print('waiting to be connected...') + if count >= 10000: + count = 0 + a2dp_status = bt.a2dpGetConnStatus() + avrcp_status = bt.avrcpGetConnStatus() + if a2dp_status == A2DP_AVRCP_CONNECT_STATUS['CONNECTED'] and avrcp_status == A2DP_AVRCP_CONNECT_STATUS['CONNECTED']: + print('========== BT connected! =========') + addr = bt.a2dpGetAddr() + if addr != -1: + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('The BT address on the host side: {}'.format(mac)) + host_addr = addr + else: + print('Get BT addr error.') + return -1 + print('Please open the music player software on your phone first.') + print('Please enter the following options to select a function:') + print('========================================================') + print('1 : play') + print('2 : pause') + print('3 : prev') + print('4 : next') + print('5 : set volume') + print('6 : exit') + print('========================================================') + while True: + tmp = input('> ') + if len(tmp) != 1: + cmd = tmp.split('> ')[1] + else: + cmd = tmp + if cmd == '6': + break + retval = cmd_proc(cmd) + if retval != -1: + msg_queue.put(retval) + break + else: + utime.sleep_ms(1000) + print('Ready to disconnect a2dp.') + retval = bt.a2dpDisconnect(host_addr) + if retval == 0: + print('a2dp connection disconnected successfully') + else: + print('Disconnect a2dp error.') + print('Ready to stop BT.') + retval = bt.stop() + if retval == 0: + print('BT has stopped.') + else: + print('BT stop error.') + bt.a2dpavrcpRelease() + bt.release() + + +if __name__ == '__main__': + main() +``` + +```python +#SPP demo program + +""" +This example demonstrates how to transmit data between a mobile phone and a device through SPP. To use this example: +1. Install a Bluetooth serial port APP, such as BlueSPP, on your Android phone and open the APP before running the program. +2. Modify the target device's Bluetooth name in the program by changing the value of DST_DEVICE_INFO['dev_name'] to the name of the phone you want to connect to. +3. Run the program, which will search for nearby devices until the target device is found and connect to the target device through SPP. +4. Check your phone for a Bluetooth pairing request and click "Pair" if prompted. +5. Once the pairing is successful, you can use the Bluetooth serial port interface to send data to the device. The device will respond with "I have received the data you sent" after receiving the data. +6. To end the program, click "Disconnect" in the mobile APP. +""" +import bt +import utime +import _thread +from queue import Queue + + +BT_NAME = 'QuecPython-SPP' + +BT_EVENT = { + 'BT_START_STATUS_IND': 0, # bt/ble start + 'BT_STOP_STATUS_IND': 1, # bt/ble stop + 'BT_SPP_INQUIRY_IND': 6, # bt spp inquiry ind + 'BT_SPP_INQUIRY_END_IND': 7, # bt spp inquiry end ind + 'BT_SPP_RECV_DATA_IND': 14, # bt spp recv data ind + 'BT_SPP_CONNECT_IND': 61, # bt spp connect ind + 'BT_SPP_DISCONNECT_IND': 62, # bt spp disconnect ind +} + +DST_DEVICE_INFO = { + 'dev_name': 'HUAWEI Mate40 Pro', # The Bluetooth name of the device you want to connect to + 'bt_addr': None +} + +BT_IS_RUN = 0 +msg_queue = Queue(30) + + +def bt_callback(args): + global msg_queue + msg_queue.put(args) + + +def bt_event_proc_task(): + global msg_queue + global BT_IS_RUN + global DST_DEVICE_INFO + + while True: + print('wait msg...') + msg = msg_queue.get() # It will be blocked here when there is no message. + event_id = msg[0] + status = msg[1] + + if event_id == BT_EVENT['BT_START_STATUS_IND']: + print('event: BT_START_STATUS_IND') + if status == 0: + print('BT start successfully.') + BT_IS_RUN = 1 + + print('Set BT name to {}'.format(BT_NAME)) + retval = bt.setLocalName(0, BT_NAME) + if retval != -1: + print('BT name set successfully.') + else: + print('BT name set failed.') + bt.stop() + continue + + retval = bt.setVisibleMode(3) + if retval == 0: + mode = bt.getVisibleMode() + if mode == 3: + print('BT visible mode set successfully.') + else: + print('BT visible mode set failed.') + bt.stop() + continue + else: + print('BT visible mode set failed.') + bt.stop() + continue + + retval = bt.startInquiry(15) + if retval != 0: + print('Inquiry error.') + bt.stop() + continue + else: + print('BT start failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_STOP_STATUS_IND']: + print('event: BT_STOP_STATUS_IND') + if status == 0: + BT_IS_RUN = 0 + print('BT stop successfully.') + else: + print('BT stop failed.') + + retval = bt.sppRelease() + if retval == 0: + print('SPP release successfully.') + else: + print('SPP release failed.') + retval = bt.release() + if retval == 0: + print('BT release successfully.') + else: + print('BT release failed.') + break + elif event_id == BT_EVENT['BT_SPP_INQUIRY_IND']: + print('event: BT_SPP_INQUIRY_IND') + if status == 0: + rssi = msg[2] + name = msg[4] + addr = msg[5] + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('name: {}, addr: {}, rssi: {}'.format(name, mac, rssi)) + + if name == DST_DEVICE_INFO['dev_name']: + print('The target device is found, device name {}'.format(name)) + DST_DEVICE_INFO['bt_addr'] = addr + retval = bt.cancelInquiry() + if retval != 0: + print('cancel inquiry failed.') + continue + else: + print('BT inquiry failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_SPP_INQUIRY_END_IND']: + print('event: BT_SPP_INQUIRY_END_IND') + if status == 0: + print('BT inquiry has ended.') + inquiry_sta = msg[2] + if inquiry_sta == 0: + if DST_DEVICE_INFO['bt_addr'] is not None: + print('Ready to connect to the target device : {}'.format(DST_DEVICE_INFO['dev_name'])) + retval = bt.sppConnect(DST_DEVICE_INFO['bt_addr']) + if retval != 0: + print('SPP connect failed.') + bt.stop() + continue + else: + print('Not found device [{}], continue to inquiry.'.format(DST_DEVICE_INFO['dev_name'])) + bt.cancelInquiry() + bt.startInquiry(15) + else: + print('Inquiry end failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_SPP_RECV_DATA_IND']: + print('event: BT_SPP_RECV_DATA_IND') + if status == 0: + datalen = msg[2] + data = msg[3] + print('recv {} bytes data: {}'.format(datalen, data)) + send_data = 'I have received the data you sent.' + print('send data: {}'.format(send_data)) + retval = bt.sppSend(send_data) + if retval != 0: + print('send data faied.') + else: + print('Recv data failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_SPP_CONNECT_IND']: + print('event: BT_SPP_CONNECT_IND') + if status == 0: + conn_sta = msg[2] + addr = msg[3] + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('SPP connect successful, conn_sta = {}, addr {}'.format(conn_sta, mac)) + else: + print('Connect failed.') + bt.stop() + continue + elif event_id == BT_EVENT['BT_SPP_DISCONNECT_IND']: + print('event: BT_SPP_DISCONNECT_IND') + conn_sta = msg[2] + addr = msg[3] + mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) + print('SPP disconnect successful, conn_sta = {}, addr {}'.format(conn_sta, mac)) + bt.stop() + continue + + +def main(): + global BT_IS_RUN + + _thread.start_new_thread(bt_event_proc_task, ()) + retval = bt.init(bt_callback) + if retval == 0: + print('BT init successful.') + else: + print('BT init failed.') + return -1 + retval = bt.sppInit() + if retval == 0: + print('SPP init successful.') + else: + print('SPP init failed.') + return -1 + retval = bt.start() + if retval == 0: + print('BT start successful.') + else: + print('BT start failed.') + retval = bt.sppRelease() + if retval == 0: + print('SPP release successful.') + else: + print('SPP release failed.') + return -1 + + count = 0 + while True: + utime.sleep(1) + count += 1 + cur_time = utime.localtime() + timestamp = "{:02d}:{:02d}:{:02d}".format(cur_time[3], cur_time[4], cur_time[5]) + + if count % 5 == 0: + if BT_IS_RUN == 1: + print('[{}] BT SPP is running, count = {}......'.format(timestamp, count)) + print('') + else: + print('BT SPP has stopped running, ready to exit.') + break + + +if __name__ == '__main__': + main() +``` + +**Note**: + +Currently, only EC200U/EC600U/EG915U/EG912U series module supports `bt` feature. + +## Initialization Related Features + +### bt.init + +```python +bt.init(user_cb) +``` + +Initializes the Bluetooth and registers a callback function. + +**Parameter:** + +- `user_cb`- Function type. Callback function. The meaning of the callback function parameters: `args[0]` is fixed to represent event_id; `args[1]` is fixed to represent the status, `0` indicating successful execution and non-`0` indicating failed execution. The number of callback function parameters is not fixed at two, but depends on the first parameter `args[0]`. The following table lists the number of parameters and explanations for different event IDs. + +| event_id | Parameter Number | Description | +| :------: | :--------------: | ------------------------------------------------------------ | +| 0 | 2 | args[0]: event_id. BT/BLE start event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 1 | 2 | args[0]: event_id. BT/BLE stop event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation. | +| 6 | 6 | args[0]: event_id. BT inquiry event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: rssi. Signal strength.
args[3]: device_class.
args[4]: device_name. Device name. String type.
args[5]: addr. The MAC address of the discovered Bluetooth device. | +| 7 | 3 | args[0]: event_id. BT inquiry end event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: end_status. 0 - End normally, 8 - End forcefully. | +| 14 | 4 | args[0]: event_id. BT SPP receive event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: data_len. The length of the received data.
args[3]: data. The received data in bytearray type. | +| 40 | 4 | args[0]: event_id. BT HFP connect event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_connect_status. HFP connection status.
0 - Disconnected
1 - Connecting
2 - Connected
3 - Disconnecting
args[3]: addr. The address of the BT master in bytearray type. | +| 41 | 4 | args[0]: event_id. BT HFP disconnect event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_connect_status. HFP connection status.
0 - Disconnected
1 - Connecting
2 - Connected
3 - Disconnecting
args[3]: addr. The address of the BT master in bytearray type. | +| 42 | 4 | args[0]: event_id. BT HFP call status event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_call_status. HFP call status.
0 - There are currently no calls in progress
1 - There is currently at least one call in progress
args[3]: addr. The address of the BT master in bytearray type. | +| 43 | 4 | args[0]: event_id. BT HFP call setup status event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_call_setup_status. HFP call setup status.
0 - There are no call to be connected
1 - There is an incoming call that has not yet been connected
2 - There is an outgoing call that has not yet been connected
3 - The other end of the Bluetooth connection for an outgoing call is ringing
args[3]: addr. The address of the BT master in bytearray type. | +| 44 | 4 | args[0]: event_id. BT HFP network status event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_network_status. AG network status.
0 - The network is not available
1 - The network is normal
args[3]: addr. The address of the BT master in bytearray type. | +| 45 | 4 | args[0]: event_id. BT HFP network signal event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_network_signal. AG signal. Range: 0–5.
args[3]: addr. The address of the BT master in bytearray type. | +| 46 | 4 | args[0]: event_id. BT HFP battery level event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_battery_level. The AG battery level. Range: 0–5.
args[3]: addr. The address of the BT master in bytearray type. | +| 47 | 4 | args[0]: event_id. BT HFP call held status event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_call_held_status. HFP call held status.
0 - There is no call on hold.
1 - The call is held and either paused or there is an active call/hold call switching.
2 - The call is held and there is no active call
args[3]: addr. The address of the BT master in bytearray type. | +| 48 | 4 | args[0]: event_id. BT HFP audio status event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_audio_status. Audio connection status.
0 - Disconnected
1 - Connecting
2 - Connected
3 - Disconnecting
args[3]: addr. The address of the BT master in bytearray type. | +| 49 | 4 | args[0]: event_id. BT HFP volume type event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_volume_type.
0 - The volume type is speaker
1 - The volume type is microphone
args[3]: addr. The address of the BT master in bytearray type. | +| 50 | 4 | args[0]: event_id. BT HFP service type event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_service_type. The current AG network service mode.
0 - Normal network mode
1 - Roaming mode
args[3]: addr. The address of the BT master in bytearray type. | +| 51 | 4 | args[0]: event_id. BT HFP ring event, that is, ringing event on incoming call.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: Reserved parameter.
args[3]: addr. The address of the BT master in bytearray type. | +| | | args[0]: event_id. BT HFP codec type event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: hfp_codec_type. Which codec mode is currently in use.
1 - CVDS, 8 kHz sample rate
2 - mSBC, 16 kHz sample rate
args[3]: addr. The address of the BT master in bytearray type. | +| 61 | 4 | args[0]: event_id. BT SPP connect event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: spp_connect_status. SPP connection status.
0 - Disconnected
1 - Connecting
2 - Connected
3 - Disconnecting
args[3]: addr. The MAC address of the peer device in bytearray type. | +| 62 | 4 | args[0]: event_id. BT SPP disconnect event.
args[1]: status. The operation status. 0 - successful operation; other values - failed operation.
args[2]: spp_connect_status. SPP connection status.
0 - Disconnected
1 - Connecting
2 - Connected
3 - Disconnecting
args[3]: addr. The MAC address of the peer device in bytearray type. | + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +def bt_callback(args): + event_id = args[0] # The first parameter is fixed to represent event ID. + status = args[1] # The second parameter is fixed to represent status, indicating whether the execution result of an operation is successful or failed. + ...... +``` + +### bt.release + +```python +bt.release() +``` + +Releases Bluetooth resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.start + +```python +bt.start() +``` + +Enables Bluetooth feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.stop + +```python +bt.stop() +``` + +Disables Bluetooth feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.getStatus + +```python +bt.getStatus() +``` + +Gets the Bluetooth status. + +**Return Value:** + +- Returns Bluetooth status in integer type. `0`-Stopped, `1`- Working normally, `-1`- Failed execution. + +### bt.getLocalAddr + +```python +bt.getLocalAddr() +``` + +Gets the Bluetooth address. + +**Return Value:** + +- Returns a Bluetooth address (6 bytes) in bytearray type for successful execution or `-1` for failed execution. + +**Example**: + +```python +>>> addr = bt.getLocalAddr() +>>> print(addr) +b'\xc7\xa13\xf8\xbf\x1a' +>>> mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) +>>> print('mac = [{}]'.format(mac)) +mac = [1a:bf:f8:33:a1:c7] +``` + +**Note**: + +This interface needs to be called after Bluetooth has been initialized and successfully started, such as after receiving an event with `event_id` set to 0 in the callback, that is, after the start is successful. + +### bt.setLocalName + +```python +bt.setLocalName(code, name) +``` + +Sets the Bluetooth name. + +**Parameter:** + +- `code`- Integer type. Encoding scheme. 0 - UTF8,1 - GBK. +- `name`- String type. The Bluetooth name. Maximum length: 22 bytes. + +**Return Value:** + +- Returns a Bluetooth address (6 bytes) in bytearray type for successful execution or `-1` for failed execution. + +**Example**: + +```python +>>> bt.setLocalName(0, 'QuecPython-BT') +0 +``` + +### bt.getLocalName + +```python +bt.getLocalName() +``` + +Gets the Bluetooth name. + +**Return Value:** + +- Returns a tuple `(code, name)` containing the name encoding scheme and the Bluetooth name for successful execution, or `-1` for failed execution. + +**Example**: + +```python +>>> bt.getLocalName() +(0, 'QuecPython-BT') +``` + +### bt.setVisibleMode + +```python +bt.setVisibleMode(mode) +``` + +Sets the Bluetooth visible mode, which means that it configures whether the module can be discovered or connected as a slave when scanning. + +**Parameter:** + +- `mode`- Integer type. Visible mode. The specific meanings of the values are shown in the following table: + +| Value | Description | +| ----- | ----------------------------- | +| 0 | Undiscoverable, unconnectable | +| 1 | Discoverable, unconnectable | +| 2 | Undiscoverable, connectable | +| 3 | Discoverable, connectable | + +**Return Value:** + +- Returns Bluetooth address (6 bytes) in bytearray type for successful execution, or `-1` for failed execution. + +**Example**: + +```python +>>> bt.setVisibleMode(3) +0 +``` + +### bt.getVisibleMode + +```python +bt.getVisibleMode() +``` + +Gets the Bluetooth visible mode. + +**Return Value:** + +- Returns the current visible mode value of the Bluetooth for successful execution, or `-1` for failed execution. + +**Example**: + +```python +>>> bt.getVisibleMode() +3 +``` + +### bt.startInquiry + +```python +bt.startInquiry(mode) +``` + +Starts searching for nearby Bluetooth devices. + +**Parameter:** + +- `mode`-Search mode. Indicates which type of device to query, currently set to 15 to search for all. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +bt.startInquiry(15) +``` + +### bt.cancelInquiry + +```python +bt.cancelInquiry() +``` + +Cancels the searching. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.setChannel + +```python +bt.setChannel(channel) +``` + +Sets the audio output channel used for answering phone calls or playing audio over Bluetooth. + +**Parameter:** + +- `channel`- Integer type. Audio channel. 0 - Earpiece,1 - Headphone,2 - Speaker. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.reconnect_set + +```python +bt.reconnect_set(max_count, period) +``` + +Sets the maximum number of reconnection attempts and the time interval between two consecutive reconnection attempts when the module and Bluetooth device are disconnected due to distance. + +**Parameter:** + +- `max_count`- Integer type. The maximum number of reconnection attempts. `0` indicates disabling automatic reconnection. +- `period`- Integer type. The time interval between two consecutive reconnection attempts. Unit: second. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +```python +bt.reconnect_set(25, 2)#Sets the maximum number of reconnection attempts to 25, with a time interval of 2 seconds between each attempt. +``` + +### bt.reconnect + +```python +bt.reconnect() +``` + +Actively reconnects to the last paired device, such as a mobile phone. This function should be called when the module reboots and reinitializes the Bluetooth connection, or when the Bluetooth is turned off and then turned back on again without rebooting the module. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +**Example**: + +Refer to the A2DP demo program. + +## HFP Related Features + +Provides Bluetooth call related features. + +### bt.hfpInit + +```python +bt.hfpInit() +``` + +Initializes HFP feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpRelease + +```python +bt.hfpRelease() +``` + +Releases HFP resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpConnect + +```python +bt.hfpConnect(addr) +``` + +Connects to AG and establishes an HFP connection. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes‘ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpDisonnect + +```python +bt.hfpDisonnect(addr) +``` + +Disconnects the HFP connection. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpSetVolume + +```python +bt.hfpSetVolume(addr, vol) +``` + +Sets the volume during Bluetooth calls. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes‘ AG Bluetooth address. +- `vol`- Integer type. Call volume. Range: 1–15. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpRejectAfterAnswer + +```python +bt.hfpRejectAfterAnswer(addr) +``` + +Hangs up the answered call. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpRejectCall + +```python +bt.hfpRejectCall(addr) +``` + +Rejects a call. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpAnswerCall + +```python +bt.hfpAnswerCall(addr) +``` + +Answers a call. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpEnableVR + +```python +bt.hfpEnableVR(addr) +``` + +Enables voice assistant. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpDisableVR + +```python +bt.hfpDisableVR(addr) +``` + +Disables voice assistant. + +**Parameter:** + +- `addr`-Bytearray type. 6-bytes’ AG Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.hfpDisableVR + +```python +bt.hfpDisableVR(addr, cmd) +``` + +Controls three-way calling. + +**Parameter:** + +- `addr`- Bytearray type. 6-bytes’ AG Bluetooth address. +- `cmd`- Integer type. Control command. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +## A2DP/AVRCP Related Features + +Provides Bluetooth music related features. + +### bt.a2dpavrcpInit + +```python +bt.a2dpavrcpInit() +``` + +Initializes the A2DP and AVRCP features. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.a2dpavrcpRelease + +```python +bt.a2dpavrcpRelease() +``` + +Releases the A2DP and AVRCP resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.a2dpDisconnect + +```python +bt.a2dpDisconnect(addr) +``` + +Disconnects the A2DP connection. + +**Parameter:** + +- `addr`- Bytearray type. 6 bytes' Bluetooth address of the A2DP host. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.a2dpGetAddr + +```python +bt.a2dpGetAddr() +``` + +Gets the Bluetooth address of the A2DP host. + +**Return Value:** + +- Returns a Bluetooth address of the A2DP host (6 bytes) in bytearray type for successful execution or `-1` for failed execution. + +### bt.a2dpGetConnStatus + +```python +bt.a2dpGetConnStatus() +``` + +Gets the A2DP connection status. + +**Return Value:** + +- Returns the A2DP connection status. The specific meanings of the values are shown in the following table: + +| Value | Type | Description | +| ----- | ---- | ---------------- | +| -1 | int | Failed execution | +| 0 | int | Disconnected | +| 1 | int | Connecting | +| 2 | int | Connected | +| 3 | int | Disconnecting | + +### bt.avrcpStart + +```python +bt.avrcpStart() +``` + +Controls the host to start playing. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.avrcpPause + +```python +bt.avrcpPause() +``` + +Controls the host to stop playing. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.avrcpPrev + +```python +bt.avrcpPrev() +``` + +Controls the host to play the previous one. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.avrcpNext + +```python +bt.avrcpNext() +``` + +Controls the host to play the next one. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.avrcpSetVolume + +```python +bt.avrcpSetVolume(vol) +``` + +Sets the host's playback volume. + +**Parameter:** + +- `vol`- Integer type. Playback volume. Range: 0–11. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.avrcpGetVolume + +```python +bt.avrcpGetVolume() +``` + +Gets the host's playback volume. + +**Return Value:** + +- Returns the volume value in integer type for successful execution or `-1` for failed execution. + +### bt.avrcpGetPlayStatus + +```python +bt.avrcpGetPlayStatus() +``` + +Gets the host's playback status. + +**Return Value:** + +- Returns the playback status. The specific meanings of the values are shown in the following table: + +| Value | Type | Description | +| ----- | ---- | ----------------------------- | +| -1 | int | Failed execution | +| 0 | int | No playback | +| 1 | int | Play | +| 2 | int | Pause | +| 3 | int | Switching to the previous one | +| 4 | int | Switching to the next one | + +### bt.avrcpGetConnStatus + +```python +bt.avrcpGetConnStatus() +``` + +Gets the host connection status through the AVRCP protocol. + +**Return Value:** + +- Returns the connection status. The specific meanings of the values are shown in the following table: + +| Value | Type | Description | +| ----- | ---- | ---------------- | +| -1 | int | Failed execution | +| 0 | int | Disconnected | +| 1 | int | Connecting | +| 2 | int | Connected | +| 3 | int | Disconnecting | + +## SPP Related Features + +Provides Bluetooth transmission related features. + +### bt.sppInit + +```python +bt.sppInit() +``` + +Initializes SPP feature. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.sppRelease + +```python +bt.sppRelease() +``` + +Releases SPP resources. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.sppConnect + +```python +bt.sppConnect(addr) +``` + +Establishes an SPP connection. + +**Parameter:** + +- `addr`- Bytearray type. 6 bytes' Bluetooth address. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.sppDisconnect + +```python +bt.sppDisconnect() +``` + +Disconnects the SPP connection. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +### bt.sppSend + +```python +bt.sppSend(data) +``` + +Sends data through SPP. + +**Parameter:** + +- `data`- Bytearray type. The data to be sent. + +**Return Value:** + +- `0`- Successful execution; `-1`- Failed execution. + +> **Note**: The maximum single transmission size is 4008 bytes. It is recommended to send in 667-byte segments. A return value of -1 usually indicates that the buffer is full. In such cases, a longer delay should be used for transmission. \ No newline at end of file diff --git a/docs/API_reference/en/cloudlib/README.md b/docs/API_reference/en/cloudlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..93d02cd770aa2175c23fbdda4f9459d03c838bd2 --- /dev/null +++ b/docs/API_reference/en/cloudlib/README.md @@ -0,0 +1,10 @@ +# QuecPython IoT Connection + +> The QuecPython IoT platform library includes AWS and Azure library. + + +## QuecPython IoT Connection Library List + +- [Aws - AWS IoT Core Connection](./aws.md) +- [Azure - Azure IoT Connection](./azure.md) +- [Aws S3 – AWS S3 Storage Client](./aws_s3.md) \ No newline at end of file diff --git a/docs/API_reference/en/cloudlib/aws.md b/docs/API_reference/en/cloudlib/aws.md new file mode 100644 index 0000000000000000000000000000000000000000..d1bae4034f2afacf1ae813d85544b7f7cb4f5e3d --- /dev/null +++ b/docs/API_reference/en/cloudlib/aws.md @@ -0,0 +1,235 @@ +# Aws - AWS IoT Core Connection + +A client for connecting to AWS IoT Core, managing MQTT connections, and handling device shadows. + +## Constructor + +### `Aws` +```python +class Aws(client_id,server,port,keep_alive,ssl,ssl_params) +``` +**Parameters:** + +- `client_id` (str) - The unique identifier for the IoT Thing. +- `server` (str) - The AWS IoT Core endpoint. +- `port` (int) - The MQTT port (default 8883 for TLS, 1883 for non-TLS). +- `keep_alive` (int) - The keep-alive interval in seconds (default: 60). +- `ssl` (bool) - Whether to use SSL/TLS (default: False. If True, encription is enabled, so we have to provide ssl_params). +- `ssl_params` (dict) - SSL parameters for secure connection. + +**Example** + +```python +>>> # Create Aws object +>>> import aws +>>> aws = aws.Aws(client_id, server, port, keep_alive=60,ssl=True,ssl_params={"cert": +certificate_content,"key": private_content}) +``` + +## **MQTT Communication** + +Uses umqtt library methods to establish connection and communication with cloud. + +### `aws.connect` + +```python +connect() +``` +This method establishes a connection to AWS IoT Core. + +**Return Value:** + +None + +### `aws.disconnect` + +```python +disconnect() +``` +This method disconnects from AWS IoT Core. + +**Return Value:** + +None + +### `aws.subscribe` + +```python +subscribe(topic) +``` +Method for mqtt subscribing to a topic. + +**Parameters:** + +- `topic` (str) - The MQTT topic to subscribe to. + +**Return Value:** + +None + +### `aws.publish` + +```python +publish(topic, payload) +``` +Method for mqtt publishing to a topic. + +**Parameters:** + +- `topic` (str) - The MQTT topic to publish to. +- `payload` (dict) - The message payload. + +**Return Value:** + +None + +## **Shadow Device Management** + +### `aws.create_shadow` + +```python +create_shadow(shadow_name="", state="") +``` +**Parameters:** + +- `shadow_name` (str) - The name of the shadow (optional). +- `state` (dict) - The initial state of the shadow (optional). + +**Return Value:** + +None + +### `aws.update_shadow` + +```python +update_shadow(shadow_name="", state="") +``` +**Parameters:** + +- `shadow_name` (str) - The name of the shadow. +- `state` (dict) - The new state of the shadow. + +**Return Value:** + + None + +### `aws.get_shadow` + +```python +get_shadow(shadow_name="") +``` +**Parameters:** + +- `shadow_name` (str) - The name of the shadow. + +**Return Value:** + +The current shadow state. + +### `aws.delete_shadow` + +```python +delete_shadow(shadow_name="") +``` +**Parameters:** + +- `shadow_name` (str) - The name of the shadow. + +**Return Value:** + +None + +### `aws.connect_shadow` + +```python +connect_shadow(shadow_name="", topics=None) +``` +**Parameters:** + +- `shadow_name` (str) - The name of the shadow (optional). +- `topics` (list) - List of MQTT topics related to the shadow (optional). + +**Return Value:** + +None + +### `aws.set_callback` + +```python +set_callback(topic_name, callback) +``` +**Parameters:** + +- `topic_name` (str) - The MQTT topic for which the callback is set. +- `callback` (function) - The function to be executed when a message is received. Prototype: + + callback_function(msg) + - Callback function parameter: + + - `msg`: dictionary type message. Already converted from JSON string to dictionary format. + +**Return Value:** + +None + +## **Python Example** +```python +import usr.aws as aws +import modem +import ujson +import sim # Check if PIN verification is needed for your SIM card +import net + +# AWS IoT credentials +certificate_content = """ +-----BEGIN CERTIFICATE----- + +-----END CERTIFICATE----- +""" + +private_content = """ +-----BEGIN RSA PRIVATE KEY----- + +-----END RSA PRIVATE KEY----- +""" + +client_id = 'qpthing' +server = 'abgka7vzgjoa0-ats.iot.eu-west-3.amazonaws.com' +port = 8883 + +def aws_callback(data): + print("HELLO from 1234 topic callback") + +def shadow_callback_get(data): + print("HELLO from get accepted callback") + +def shadow_callback_update(data): + print("HELLO from update accepted callback") + +def shadow_callback_delta(data): + print("HELLO from update delta callback") + +# Create AWS object +aws_obj = aws.Aws(client_id, server, port, keep_alive=60, ssl=True, + ssl_params={"cert": certificate_content, "key": private_content}) +print("Created AWS object") + +# Connect to AWS IoT +aws_obj.connect() +print("Connected to AWS IoT") + +# Subscribe and publish +aws_obj.set_callback("1234", aws_callback) +aws_obj.subscribe("1234") +aws_obj.publish("7777", "Hello from QuecPython") +aws_obj.start() + +# Shadow operations +aws_obj.create_shadow() +aws_obj.connect_shadow() +aws_obj.set_callback("$aws/things/qpthing/shadow/get/accepted", shadow_callback_get) +aws_obj.set_callback("$aws/things/qpthing/shadow/update/accepted", shadow_callback_update) +aws_obj.set_callback("$aws/things/qpthing/shadow/update/delta", shadow_callback_delta) +aws_obj.get_shadow() +aws_obj.update_shadow(state={"state": {"reported": {"welcome": "change reported"}}}) +``` diff --git a/docs/API_reference/en/cloudlib/aws_s3.md b/docs/API_reference/en/cloudlib/aws_s3.md new file mode 100644 index 0000000000000000000000000000000000000000..35fa653631b1a5e122f2949dc156b81f54d2fd3d --- /dev/null +++ b/docs/API_reference/en/cloudlib/aws_s3.md @@ -0,0 +1,128 @@ +# Aws S3 – AWS S3 Storage Client + +## Overview + +The `S3Client` class provides a convenient interface for interacting with AWS S3 storage. It enables operations such as file uploads, downloads, and deletions, while ensuring secure communication through HTTP SigV4 authentication. + +## Constructor + +### `S3Client` +```python +class S3Client(region=None, access_key=None, secret_key=None, bucket=None, config_path="config.json", download_path="") +``` + +**Parameters:** + +- **region** *(str, optional)*: Specifies the AWS region where the S3 bucket resides. +- **access_key** *(str, optional)*: AWS Access Key ID for authentication. +- **secret_key** *(str, optional)*: AWS Secret Access Key for authentication. +- **bucket** *(str, optional)*: Name of the S3 bucket to interact with. +- **config_path** *(str, optional)*: Path to a JSON configuration file. Defaults to `"config.json"`. +- **download_path** *(str, optional)*: Local directory for storing downloaded files. Defaults to an empty string. + +**Example:** + +- Using Explicit Parameters + +```python +from s3client import S3Client + +client = S3Client( + region="eu-west-3", + access_key="AKIA...", + secret_key="A2HAXbc...", + bucket="my-bucket", + download_path="s3_downloads/" +) +``` + +- Using a Configuration File + +```python +from s3client import S3Client + +client = S3Client(config_path="usr/config.json") +``` + +## S3 Communication + +The `S3Client` uses HTTP SigV4 signed requests to perform operations such as uploading, downloading, and deleting files from AWS S3 storage. + +### `upload_file` + +```python +upload_file(filepath, object_key, content_type='application/octet-stream') +``` + +Uploads a local file to the specified AWS S3 bucket. + +**Parameters:** + +- **filepath** *(str)*: Local path to the file you want to upload. +- **object_key** *(str)*: The key (path) under which to store the file in the S3 bucket. +- **content_type** *(str, optional)*: The MIME type of the file (default: `application/octet-stream`). + +**Return Value:** + +- A **response object** containing all information returned by the server, such as response status codes, response headers, and response bodies. + +- **None** if an exception occurs. + +### `download_to_file` + +```python +download_to_file(object_key) +``` + +Downloads a file from the S3 bucket and saves it locally in the `download_path` defined in the configuration or constructor. + +**Parameters:** + +- **object_key** *(str)*: The key (path) of the file you want to download from the S3 bucket. + +**Return Value:** + +- A **response object** containing all information returned by the server, such as response status codes, response headers, and response bodies. + +- **None** if an exception occurs. + +### `delete_object` + +```python +delete_object(object_key) +``` + +Deletes a file (object) from the S3 bucket. + +**Parameters:** + +- **object_key** *(str)*: The key (path) of the file you want to delete from the S3 bucket. + +**Return Value:** + +- A **response object** containing all information returned by the server, such as response status codes, response headers, and response bodies. + +- **None** if an exception occurs. + +## Example code + +```python +from s3client import S3Client + +s3_client = S3Client( + region="eu-west-3", + access_key="YOUR_ACCESS_KEY", + secret_key="YOUR_SECRET_KEY", + bucket="your-bucket-name", + download_path="s3_downloads/" +) + +# Upload a file +s3_client.upload_file(filepath='usr/hello.txt', object_key='test-folder/hello.txt',content_type='text/str') + +# Download a file +s3_client.download_to_file(object_key='test-folder/hello.txt') + +# Delete a file +s3_client.delete_file(object_key='test-folder/hello.txt') +``` \ No newline at end of file diff --git a/docs/API_reference/en/cloudlib/azure.md b/docs/API_reference/en/cloudlib/azure.md new file mode 100644 index 0000000000000000000000000000000000000000..14e4fc728a52c037f035bed24ba94fcec20ba1ec --- /dev/null +++ b/docs/API_reference/en/cloudlib/azure.md @@ -0,0 +1,297 @@ +# Azure - Azure IoT Core Connection + +A client for connecting to Azure IoT Hub, managing MQTT connections, device twins, direct methods, and authentication using SAS tokens and x.509 cerfificates. + +## Constructor + +### `Azure` +```python +class Azure(client_id, server, port, keep_alive=60, user=None, password=None, ssl=False, ssl_params=None) +``` +**Parameters:** + +- `client_id` (str) – Unique identifier for the device. +- `server` (str) – Azure IoT Hub hostname (e.g. `your-hub.azure-devices.net`). +- `port` (int) – MQTT port (usually 8883 for TLS). +- `keep_alive` (int) – Keep-alive interval in seconds (default: 60). +- `user` (str) – MQTT username (format: `hostname/deviceId/?api-version=2020-09-30`). +- `password` (str) – SAS token for authentication. +- `ssl` (bool) – Whether to use SSL/TLS (default: False). +- `ssl_params` (dict) – SSL parameters for secure connection. + +**Example** +```python +>>> import azure +>>> az = azure.Azure(client_id, server, port, keep_alive=60, user=username, password=sas_token, ssl=True, ssl_params={"cert": cert, "key": key}) +``` + +--- + +## Authentication + +### `azure.generate_sas_token` +```python +generate_sas_token(uri, key, policy_name, expiry=3600) +``` +Generates a Shared Access Signature (SAS) token. + +**Parameters:** + +- `uri` - Uniform Resource Identifier (URI) that specifies the target device in the Azure IoT Hub. It should follow the format: `"{}/devices/{}".format(server, client_id)`, where `server` is the IoT Hub hostname and `client_id` is the unique device identifier. For example: `"your-hub.azure-devices.net/devices/myDeviceId"`. +- `key` - Shared access key. +- `policy_name` - name of the policy you are using. If you dont use any then the policy_name value is None. + +**Return Value:** + +A valid SAS token string. + + +## MQTT Communication + +### `azure.connect` +```python +connect() +``` +Establishes a connection to Azure IoT Hub. + +**Return Value:** + +None + +### `azure.disconnect` +```python +disconnect() +``` +Disconnects from the IoT Hub server. + +**Return Value:** + +None + +### `azure.subscribe` +```python +subscribe(topic, qos=0) +``` +Subscribes to a given MQTT topic. + +**Parameters:** + +- `topic` (str) - Subscribe topic. Azure IoT Hub has reserved topics for subscribing and publishing. +- `qos` (str) - QoS 0 or 1. IoT Hub supports up to QoS 1 and will downgrade QoS 2 subscriptions to QoS 1. + +**Return Value:** + +None + +### `azure.publish` +```python +publish(topic, payload, qos=0) +``` +Publishes a message to the specified topic. + +**Parameters:** + +- `topic` (str) - Publish topic. +- `qos` (str) - QoS levels 0 or 1. + +**Return Value:** + +None + +### `azure.set_callback` +```python +set_callback(topic_name, callback) +``` +Sets a callback for incoming messages on a topic. + +**Parameters:** + +- `topic_name` (str) - name of the topic you want to set callback for +- `callback` (function) - The function to be executed when a message is received. Prototype: + + callback_function(msg) + - Callback function parameter: + + - `msg`: dictionary type message. Already converted from JSON string to dictionary format. + +**Return Value:** + +None + +### `azure.loop` +```python +loop() +``` +Handles incoming MQTT messages (non-blocking loop). + +**Return Value:** + +None + +### `azure.start` +```python +start() +``` +Starts the MQTT client's internal loop. + +**Return Value:** + +None + +--- + +## Device Twins Management + +### `azure.retrieve_twin` +```python +retrieve_twin(request_id=None, qos=0) +``` +Retrieves the current device twin from Azure IoT Hub. It will print twin json file. + +**Parameters:** + +- `request_id` (str) - unique identifier for tracking the request. +- `qos` (str) - level 0 or 1. + +**Return Value:** + +None. + +### `azure.update_twin` +```python +update_twin(payload, request_id=None, qos=0) +``` +Sends a reported properties update on this topic: $iothub/twin/PATCH/properties/reported/?$rid={request_id}. + +**Parameters:** + +- `payload`- json payload. +- `request_id` (str) - unique identifier for tracking the request. +- `qos` (str) - level 0 or 1. + +**Return Value:** + +None + +### `azure.subscribe_to_desired_updates` + +```python +subscribe_to_desired_updates(qos=0) +``` +Subscribes to desired property updates from the cloud. The device should subscribe to receive real-time updates when the Desired Properties are changed from the cloud to this topic: $iothub/twin/PATCH/properties/desired/# + +**Parameters:** + +- `qos` (str) - level 0 or 1. + +**Return Value:** + +None + +--- +## Direct Methods + +### `azure.init_direct_method_handler` +```python +init_direct_method_handler(method_handler) +``` +Initializes a direct method handler for incoming method calls. + +**Parameters:** + +- `method_handler` - callback function which will be invoked after recieving direct method message. + +**Return Value:** + +None + +### `azure.send_method_response` +```python +send_method_response(status, message, request_id) +``` +Sends a response to a direct method invocation. When you recieve direct method message, you have to respond in pre-defined time period. + +**Parameters:** + +- `status` - 200 if method is recognized; 400 if method is not recognized. +- `message` - response string. +- `request_id` - unique identifier. + +**Return Value:** + +None + +--- + +## Example code + +*Using SAS token authentication. + +```python +import usr.azure as azure +import modem +import ujson +from usr.config import CERT,PRIVATE_KEY,SHARED_ACCESS_KEY, PASSWORD + + +# device name +client_id = 'device_name' +# server address +server = 'hub_name.azure-devices.net' +# port MQTT +port = 8883 + +username = '{}/{}/?api-version=2021-04-12'.format(server, client_id) + +uri = "{}/devices/{}".format(server, client_id) +SharedAccessKey = SHARED_ACCESS_KEY + + +# create azure obj +azure_obj = azure.Azure(client_id, server, port, keep_alive=60, user=username, password=PASSWORD, ssl=True, ssl_params={"cert": +CERT, "key": PRIVATE_KEY}) +print("create azure obj") + +#generate token +token = azure_obj.generate_sas_token(uri, SharedAccessKey, None) +azure_obj.mqtt_client.password = token + +# connect mqtt server +print("azure connect start") +azure_obj.connect() +print("azure connect end") + +''' +direct methods example +''' +#direct method handler +def handle_method(method_name, msg, request_id): + if method_name == "turn_on_the_light": + print("Light on!") + azure_obj.send_method_response(200, "Light on", request_id) + else: + azure_obj.send_method_response(404, "Method not found", request_id) + +#initializing direct method handler +azure_obj.init_direct_method_handler(handle_method) + +''' +device twins example +''' +#getting the twin json payload +azure_obj.retrieve_twin() + +#new payload to be added +payload = { + "status": "active", + "temperature": 24.5 +} + +#updating twin json payload +azure_obj.update_twin(payload) + +#subscribing to recieve updates on desired field in device twin +azure_obj.subscribe_to_desired_updates() + +azure_obj.start() +``` \ No newline at end of file diff --git a/docs/API_reference/en/componentlib/README.md b/docs/API_reference/en/componentlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3b15d5646c8f9eddc452e6abad388e58dbf0ca8 --- /dev/null +++ b/docs/API_reference/en/componentlib/README.md @@ -0,0 +1,9 @@ +# QuecPython open source component + +> The QuecPython Component Library includes all functional components developed using QuecPython scripts + +This article describes the modules in the QuecPython component library. + +## QuecPython open source component library list + +- [uasyncio - coroutine](./uasyncio.md) \ No newline at end of file diff --git a/docs/API_reference/en/componentlib/uasyncio.md b/docs/API_reference/en/componentlib/uasyncio.md new file mode 100644 index 0000000000000000000000000000000000000000..ca168ca850eadcd94a601394fbe5a1c5569b987c --- /dev/null +++ b/docs/API_reference/en/componentlib/uasyncio.md @@ -0,0 +1,256 @@ +# uasyncio – Asynchronous I/O Scheduler + +`uasyncio` is an asynchronous I/O library in MicroPython, also a lightweight subset of `asyncio` . It provides abstractions similar to coroutines and event loops in the standard library for running multiple coroutines concurrently and managing the execution and suspension of coroutines. `uasyncio` , with a small code size and low memory footprint, is suitable for embedded systems and resource–constrained devices. It provides a set of APIs and tools to create and manage coroutines, network and protocol–related classes that support asynchronous I/O. + +## uasyncio library +For EC200U Series Module, might need to download the `uasyncio` library from [here](https://github.com/QuecPython/uasyncio) + + +## Create Coroutine + + + +### uasyncio.create_task + +Creates an asynchronous task to run the given coroutine. + +```python +uasyncio.create_task(coro) +``` + +**Parameter** + +* `coro` – The coroutine object to be run. + +**Example** + +```python +import usr.uasyncio as asyncio +async def my_coroutine(): + print("Running my_coroutine") + +task = asyncio.create_task(my_coroutine()) +``` + + + +## Run Coroutine + +### uasyncio.run + +Runs a coroutine until it completes. This is the main way to start the event loop. + +```python +uasyncio.run(coro) +``` + +**Parameter** + +* `coro` – The coroutine object to be run. + +**Example** + +```python +import usr.uasyncio as asyncio + +async def my_coroutine(): + print("Running my_coroutine") + +asyncio.run(my_coroutine()) +``` + +## Cancel Task in Coroutine + +### task.cancel + +Cancels tasks. + +```python +task.cancel() +``` + +**Example** + +```python +from usr import uasyncio as asyncio +async def bar(n): + print('Start cancellable bar()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def do_cancel(task): + await asyncio.sleep(5) + print('About to cancel bar') + # Cancel the task. + task.cancel() + +def main(): + task = asyncio.wait_for(bar(10), 7) + asyncio.create_task(do_cancel(task)) + asyncio.sleep(1) + +asyncio.run(main()) +``` + + + +## Sleep Coroutine + +### uasyncio.sleep + +Sleeps for `delay` seconds. Other tasks can run in the meanwhile. + +```python +uasyncio.sleep(delay) +``` + +**Parameter** + +* `delay` – Integer (or float) type. The time in seconds that the current task or coroutine will block. + + + +### uasyncio.sleep_ms + +Sleeps for `delay` milliseconds. Other tasks can run in the meanwhile. + +```python +uasyncio.sleep_ms(delay) +``` + +**Parameter** + +* `t` – Integer (or float) type. The time in milliseconds that the current task or coroutine will block. + + + +## Cancel Task in Coroutine when Timeout + +### uasyncio.wait_for + +Waits for a coroutine to complete with a timeout in seconds. If the timeout elapses before the task is completed, the task is canceled and an exception will occur. + +```python +uasyncio.wait_for(coro, timeout) +``` + +**Parameter** + +* `coro` – Coroutine type. The coroutine object. +* `timeout` – Integer (or float) type. The timeout in seconds. + +**Example** + +```python +from usr import uasyncio as asyncio + + +async def bar(x): + count = 0 + while True: + count += 1 + print('Instance: {} count: {}'.format(x, count)) + await asyncio.sleep(2) # Pause 1s + print("sleep count instance = {} count = {}".format(x, count)) + + +async def main(): + """Set the coroutine wait task""" + task = asyncio.wait_for(bar(10), 7) + """Start the coroutine. The coroutine displayed above indicates that if the task does not exit within 7 seconds, the coroutine is closed and an exception will occur.""" + asyncio.run(task) + await asyncio.sleep(10) + +asyncio.run(main()) +``` + + + +### uasyncio.wait_for_ms + +Waits for a coroutine to complete within a timeout in milliseconds. If the timeout elapses before the task is completed, the task is canceled and an exception will occur. + +```python +uasyncio.wait_for_ms(coro, timeout) +``` + +**Parameter** + +* `coro` – Coroutine type. The coroutine object. + +* `timeout` – Integer (or float) type. The timeout in milliseconds. + + + +## Run Coroutine Concurrently + +### uasyncio.gather + +Runs the given coroutines and collects the results. When all coroutines are completed, the function returns a result list. If `return_exceptions` is True, the raised exception will be returned as a result rather than raised immediately. + +```python +uasyncio.gather(*coros, return_exceptions=False) +``` + +**Parameter** + +* `coros` – Coroutine type. Single or multiple coroutine objects. + +* `return_exceptions` – Boolean type. Whether to return exceptions as the result. + + True: Return exceptions as the result. + + False: Not return exceptions as the result. (Default) + +**Example** + +```python +from usr import uasyncio as asyncio + + +async def barking(n): + print('Start barking') + for _ in range(6): + await asyncio.sleep(1) + print('Done barking.') + return 2 * n + +async def foo(n): + print('Start timeout coro foo()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def bar(n): + print('Start cancellable bar()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def do_cancel(task): + await asyncio.sleep(5) + print('About to cancel bar') + task.cancel() + +async def main(): + tasks = [asyncio.create_task(bar(70))] + tasks.append(barking(21)) + tasks.append(asyncio.wait_for(foo(10), 7)) + asyncio.create_task(do_cancel(tasks[0])) + res = None + try: + # When all coroutines are completed, if return_exceptions is True, the raised exception will be returned as a result rather than raised immediately. + res = await asyncio.gather(*tasks, return_exceptions=True) + except asyncio.TimeoutError: # These only happen if return_exceptions is False + print('Timeout') # With the default times, cancellation occurs first + except asyncio.CancelledError: + print('Cancelled') + print('Result: ', res) + +asyncio.run(main()) +``` + diff --git a/docs/API_reference/en/config.json b/docs/API_reference/en/config.json new file mode 100644 index 0000000000000000000000000000000000000000..933c575ef36d27cfc9e3330ce796bb0a5a42dcc2 --- /dev/null +++ b/docs/API_reference/en/config.json @@ -0,0 +1,19 @@ +{ + "import": "config_en", + "name": "API_Reference Manual", + "navbar": { + "items": [ + { + "label": "Version", + "position": "right", + "type": "list", + "items": [ + { + "url": "/API_reference/en/", + "label": "V1.0(latest)" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/docs/API_reference/en/errcode/README.md b/docs/API_reference/en/errcode/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4134e8d5c99ba39eecc6121f448467024d5df32 --- /dev/null +++ b/docs/API_reference/en/errcode/README.md @@ -0,0 +1,115 @@ +# QuecPython Error Code Summary + +**This section introduces all error code constants in QuecPython.** + +| Error Code Constant | Error Code | Description | +| ----------------------- | ---------- | ----------------------------------------------- | +| QUEC_PY_FAIL | -1 | Generic failure codes | +| QUEC_PY_OK | 0 | Quec_py value indicating success (no error) | +| QUEC_PY_EPERM | 1 | Operation not permitted | +| QUEC_PY_ENOENT | 2 | No such file or directory | +| QUEC_PY_ESRCH | 3 | No such process | +| QUEC_PY_EINTR | 4 | Interrupted system call | +| QUEC_PY_EIO | 5 | I/O error | +| QUEC_PY_ENXIO | 6 | No such device or address | +| QUEC_PY_E2BIG | 7 | Argument list too long | +| QUEC_PY_ENOEXEC | 8 | Exec format error | +| QUEC_PY_EBADF | 9 | Bad file number | +| QUEC_PY_ECHILD | 10 | No child processes | +| QUEC_PY_EAGAIN | 11 | Try again | +| QUEC_PY_ENOMEM | 12 | Out of memory | +| QUEC_PY_EACCES | 13 | Permission denied | +| QUEC_PY_EFAULT | 14 | Bad address | +| QUEC_PY_ENOTBLK | 15 | Block device required | +| QUEC_PY_EBUSY | 16 | Device or resource busy | +| QUEC_PY_EEXIST | 17 | File exists | +| QUEC_PY_EXDEV | 18 | Cross-device link | +| QUEC_PY_ENODEV | 19 | No such device | +| QUEC_PY_ENOTDIR | 20 | Not a directory | +| QUEC_PY_EISDIR | 21 | Is a directory | +| QUEC_PY_EINVAL | 22 | Invalid argument | +| QUEC_PY_ENFILE | 23 | File table overflow | +| QUEC_PY_EMFILE | 24 | Too many open files | +| QUEC_PY_ENOTTY | 25 | Not a typewriter | +| QUEC_PY_ETXTBSY | 26 | Text file busy | +| QUEC_PY_EFBIG | 27 | File too large | +| QUEC_PY_ENOSPC | 28 | No space left on device | +| QUEC_PY_ESPIPE | 29 | Illegal seek | +| QUEC_PY_EROFS | 30 | Read-only file system | +| QUEC_PY_EMLINK | 31 | Too many links | +| QUEC_PY_EPIPE | 32 | Broken pipe | +| QUEC_PY_EDOM | 33 | Math argument out of domain of func | +| QUEC_PY_ERANGE | 34 | Math result not representable | +| QUEC_PY_EDEADLK | 35 | Resource deadlock would occur | +| QUEC_PY_ENAMETOOLONG | 36 | File name too long | +| QUEC_PY_ENOLCK | 37 | No record locks available | +| QUEC_PY_ENOSYS | 38 | Function not implemented | +| QUEC_PY_ENOTEMPTY | 39 | Directory not empty | +| QUEC_PY_ELOOP | 40 | Too many symbolic links encountered | +| QUEC_PY_EWOULDBLOCK | 41 | Operation would block | +| QUEC_PY_ENOMSG | 42 | No message of desired type | +| QUEC_PY_EIDRM | 43 | Identifier removed | +| QUEC_PY_ECHRNG | 44 | Channel number out of range | +| QUEC_PY_EL2NSYNC | 45 | Level 2 not synchronized | +| QUEC_PY_EL3HLT | 46 | Level 3 halted | +| QUEC_PY_EL3RST | 47 | Level 3 reset | +| QUEC_PY_ELNRNG | 48 | Link number out of range | +| QUEC_PY_EUNATCH | 49 | Protocol driver not attached | +| QUEC_PY_ENOCSI | 50 | No CSI structure available | +| QUEC_PY_EL2HLT | 51 | Level 2 halted | +| QUEC_PY_EBADE | 52 | Invalid exchange | +| QUEC_PY_EBADR | 53 | Invalid request descriptor | +| QUEC_PY_EXFULL | 54 | Exchange full | +| QUEC_PY_ENOANO | 55 | No anode | +| QUEC_PY_EBADRQC | 56 | Invalid request code | +| QUEC_PY_EBADSLT | 57 | Invalid slot | +| QUEC_PY_EDEADLOCK | 58 | Deadlock | +| QUEC_PY_EBFONT | 59 | Bad font file format | +| QUEC_PY_ENOSTR | 60 | Device not a stream | +| QUEC_PY_ENODATA | 61 | No data available | +| QUEC_PY_ETIME | 62 | Timer expired | +| QUEC_PY_ENOSR | 63 | Out of streams resources | +| QUEC_PY_ENONET | 64 | Machine is not on the network | +| QUEC_PY_ENOPKG | 65 | Package not installed | +| QUEC_PY_EREMOTE | 66 | Object is remote | +| QUEC_PY_ENOLINK | 67 | Link has been severed | +| QUEC_PY_EADV | 68 | Advertise error | +| QUEC_PY_ESRMNT | 69 | Srmount error | +| QUEC_PY_ECOMM | 70 | Communication error on send | +| QUEC_PY_EPROTO | 71 | Protocol error | +| QUEC_PY_EMULTIHOP | 72 | Multihop attempted | +| QUEC_PY_EDOTDOT | 73 | RFS specific error | +| QUEC_PY_EBADMSG | 74 | Not a data message | +| QUEC_PY_EOVERFLOW | 75 | Value too large for defined data type | +| QUEC_PY_ENOTUNIQ | 76 | Name not unique on network | +| QUEC_PY_EBADFD | 77 | File descriptor in bad state | +| QUEC_PY_EREMCHG | 78 | Remote address changed | +| QUEC_PY_ELIBACC | 79 | Can not access a needed shared library | +| QUEC_PY_ELIBBAD | 80 | Accessing a corrupted shared library | +| QUEC_PY_ELIBSCN | 81 | .lib section in a.out corrupted | +| QUEC_PY_ELIBMAX | 82 | Attempting to link in too many shared libraries | +| QUEC_PY_ELIBEXEC | 83 | Cannot exec a shared library directly | +| QUEC_PY_EILSEQ | 84 | Illegal byte sequence | +| QUEC_PY_ERESTART | 85 | Interrupted system call should be restarted | +| QUEC_PY_ESTRPIPE | 86 | Streams pipe error | +| QUEC_PY_EUSERS | 87 | Too many users | +| QUEC_PY_ENOTSOCK | 88 | Socket operation on non-socket | +| QUEC_PY_EDESTADDRREQ | 89 | Destination address required | +| QUEC_PY_EMSGSIZE | 90 | Message too long | +| QUEC_PY_EPROTOTYPE | 91 | Protocol wrong type for socket | +| QUEC_PY_ENOPROTOOPT | 92 | Protocol not available | +| QUEC_PY_EPROTONOSUPPORT | 93 | Protocol not supported | +| QUEC_PY_ESOCKTNOSUPPORT | 94 | Socket type not supported | +| QUEC_PY_EOPNOTSUPP | 95 | Operation not supported on transport endpoint | +| QUEC_PY_EAFNOSUPPORT | 97 | Address family not supported by protocol | +| QUEC_PY_EADDRINUSE | 98 | Address already in use | +| QUEC_PY_ECONNABORTED | 103 | Software caused connection abort | +| QUEC_PY_ECONNRESET | 104 | Connection reset by peer | +| QUEC_PY_ENOBUFS | 105 | No buffer space available | +| QUEC_PY_EISCONN | 106 | Transport endpoint is already connected | +| QUEC_PY_ENOTCONN | 107 | Transport endpoint is not connected | +| QUEC_PY_ETIMEDOUT | 110 | Connection timed out | +| QUEC_PY_ECONNREFUSED | 111 | Connection refused | +| QUEC_PY_EHOSTUNREACH | 113 | No route to host | +| QUEC_PY_EALREADY | 114 | Operation already in progress | +| QUEC_PY_EINPROGRESS | 115 | Operation now in progress | \ No newline at end of file diff --git a/docs/API_reference/en/gnsslib/README.md b/docs/API_reference/en/gnsslib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..34c287ad81246701db925ad96f28da904a038828 --- /dev/null +++ b/docs/API_reference/en/gnsslib/README.md @@ -0,0 +1,13 @@ +# QuecPython locate the application + +> QuecPython Positioning application includes all positioning related functional modules + +This article describes the modules in the QuecPython locating application library. + +## QuecPython locates the list of application libraries + +- [gnss - external GNSS](./gnss.md) +- [quecgnss - built-in GNSS](./quecgnss.md) +- [wifilocator-WIFI location](./wifilocator.md) +- [wifiScan-WiFi scan](./wifiScan.md) + diff --git a/docs/API_reference/en/gnsslib/cellLocator.md b/docs/API_reference/en/gnsslib/cellLocator.md new file mode 100644 index 0000000000000000000000000000000000000000..345c7d4baa25ef4e0dd5c32207c7c78164fea68d --- /dev/null +++ b/docs/API_reference/en/gnsslib/cellLocator.md @@ -0,0 +1,61 @@ +# cellLocator - Base Station Location + +This module provides base station location feature and gets the latitude and longitude coordinate information of QuecPython modules. + + + +>Currently, only EC600S/EC600N/EC800N/EC200U/EC600U/EG912U/EG915U/EC600E/EC800E series module supports this feature. + + + +## Get Location + +### `cellLocator.getLocation` + +```python +cellLocator.getLocation(serverAddr, port, token, timeout [, profileIdx]) +``` + +This method gets the module's latitude and longitude coordinate information. + +**Parameter:** + +* `serverAddr` - String type. Server domain name with a length less than 255 bytes. For domain name, please contact Quectel technical support. +* `port` - Integer type. Server port. Currently only port 80 is supported. +* `token` - String type. A 16-character key, and application is required. +* `timeout` - Integer type. Timeout. Range: 1–300. Unit: s. Default value: 300. +* `profileIdx` - Integer type. PDP context ID. Range: 1–3. It is an optional parameter and the default is the one that has been successfully dialed. Setting other values may require a dedicated APN and password.
+ +**Return Value:** + +Returns the longitude and latitude coordinate information in tuple format: `(longtitude, latitude, accuracy)`. `(0.0, 0.0, 0)` indicates invalid coordinate information. + +`longtitude`: Longitude. + +`latitude`: Latitude. + +`accuracy`: Accuracy. Unit: meter. + +The error codes are described as follows: + +`1` – Failed initialization + +`2` – The server address is too long (more than 255 bytes) + +`3` – Key length error (It must be 16 bytes) + +`4` – The timeout is out of range. The supported range is 1–300 + +`5` – The specified PDP is not connected to the network + +`6` – Obtaining location error + +**Example:** + +```python +>>> import cellLocator +>>> cellLocator.getLocation("www.example.com", 80, "xxxxxxxxxxxxxxxx", 8, 1) +(117.1138, 31.82279, 550) +# The "www.example.com" refers to the domain name, please contact Quectel technical support +# The key "xxxxxxxxxxxxxxxx" indicates token. Contact Quectel Technical Support to apply it. +``` diff --git a/docs/API_reference/en/gnsslib/gnss.md b/docs/API_reference/en/gnsslib/gnss.md new file mode 100644 index 0000000000000000000000000000000000000000..5737b0340542851471747fd93675031119775b24 --- /dev/null +++ b/docs/API_reference/en/gnsslib/gnss.md @@ -0,0 +1,394 @@ +# gnss - External GNSS Resolver + +For L76K module or GNSS modules with similar data type, you can get information such as whether the positioning is successful, the latitude and longitude, UTC time, the positioning mode, the number of satellites used for positioning, the number of visible satellites, the azimuth angle of positioning, the ground speed and the geodetic height. Currently, for L76K module, the data got through the interface provided by this module is read from the GNGGA, GNRMC and GPGSV sentences in the original GNSS data package read through the UART. + +> Note: Currently, only EC600S/EC600N/EC800N/EC200U/EC600U/EC600M/EC800M series module supports this method. + +## Create GNSS Object + +### `gnss.GnssGetData` + +```python +gnss.GnssGetData(uartn,baudrate,databits,parity,stopbits,flowctl) +``` + +Creates a GNSS object to get the GNSS data. Parameters are the type of UARTs for mounting the GNSS module and communication parameters. + +**Parameter** + +* `uartn` - Integer type. + uartn + `0`-uart0 - DEBUG PORT + `1`-uart1 – BT PORT + `2`-uart2 – MAIN PORT + `3`-uart3 – USB CDC PORT + +* `baudrate` - Integer type. Baud rate. Some common baud rates are supported, like `4800`, `9600`, `19200`, `38400`, `57600`, `115200` and `230400`. + +* `databits` - Integer type. Data bit. Range: [5–8]. ECX00U series module only supports 8 data bits. + +* `parity` - Integer type. Parity check. + + `0` – NONE + + `1` – EVEN + + `2` – ODD + +* `stopbits` - Integer type. Stop bit. Range: [1–2]. + +* `flowctl` - Integer type. Hardware control flow. + + `0` – FC_NONE + + `1` – FC_HW + +**Return Value**
A GNSS object + +**Example** + +```python +from gnss import GnssGetData +gnss = GnssGetData(1, 9600, 8, 0, 1, 0) +``` + +## Read and Analyze GNSS Data + +### `gnss.read_gnss_data` + +```python +gnss.read_gnss_data(max_retry=1, debug=0) +``` + +Reads the GNSS data through the UART and returns the length of the GNSS data. + +**Parameter** + +* `max_retry` – Integer type. It is an optional parameter. When the GNSS data is invalid, this parameter indicates the maximum times of automatic data-reading. Exit when the data length is 0, that is, no data has been read. Default value: 1. +* `debug` – Integer type. It is an optional parameter indicating that whether the debugging information is output in the progress of reading and analyzing the GNSS data. 0 – Not output. 1 – Output. Default value: 0. + +**Return Value** + +Integer type. Length of the GNSS data read through the UART. Unit: byte. + +**Example** + +```python +#========================================================================= +gnss.read_gnss_data() # Uses the dafault settings and reads GNSS data only once. The detailed debugging information is not output. +4224 # Reads data and analyzes GNGGA, GNRMC and GPGSV sentences successfully. Returns the length of the original data read. +#========================================================================= +gnss.read_gnss_data() # Uses the dafault settings and reads GNSS data only once. The detailed debugging information is not output. +GNGGA data is invalid. # Reads data successfully. The GNGGA sentences got is invalid. +GNRMC data is invalid. # Reads data successfully. The GNRMC sentences got is invalid. +648 # Returns the length of the original data read. +#========================================================================= +gnss.read_gnss_data(max_retry=3) # Sets the maximum times of automatic data-reading to 3 +Not find GPGSV data or GPGSV data is invalid. # For the first time, no GPGSV sentence is found or invaild. +continue read. # Continues to read the next package of data. +Not find GNGGA data. # For the second time, no GNGGA sentence is found. +Not find GNRMC data. # For the second time, no GNRMC sentence is found. +continue read. # Continues to read the next package of data +Not find GNGGA data. # For the third time, no GNGGA sentence is found. +Not find GNRMC data. # For the third time, no GNRMC sentence is found. +continue read. # Exits. Fails to read data and continues to read but it has reached the maximum times of automatic data-reading. +128 +#========================================================================= +gnss.read_gnss_data(debug=1) # Sets to output the detailed information in the progress of reading and analyzing data. +GGA data : ['GNGGA', '021224.000', '3149.27680', 'N', '11706.93369', 'E', '1', '19', '0.9', '168.2', 'M', '-5.0', 'M', '', '*52'] # Outputs GNGGA sentence that was matched and simply processed from the original GNSS data. +RMC data : ['GNRMC', '021224.000', 'A', '3149.27680', 'N', '11706.93369', 'E', '0.00', '153.28', '110122', '', '', 'A', 'V*02'] # Outputs GNRMC sentence that was matched and simply processed from the original GNSS data. +total_sen_num = 3, total_sat_num = 12 # Outputs the total number of a complete set of GPGSV sentences and number of visible satellites. +# The following is the specific GPGSV sentences matched. +[0] : ['$GPGSV', '3', '1', '12', '10', '79', '210', '35', '12', '40', '070', '43', '21', '08', '305', '31', '23', '46', '158', '43', '0*6E'] +[1] : ['$GPGSV', '3', '2', '12', '24', '', '', '26', '25', '54', '125', '42', '31', '', '', '21', '32', '50', '324', '34', '0*64'] +[2] : ['$GPGSV', '3', '3', '12', '193', '61', '104', '44', '194', '58', '117', '42', '195', '05', '162', '35', '199', '', '', '32', '0*54'] +4224 +``` + +## Get Original GNSS Data + +### `gnss.getOriginalData` + +```python +gnss.getOriginalData() +``` + +This interface gets the original GNSS data read through the UART. You can get the original GNSS data through this interface for data processing or confirmation. The original GNSS data will be returned after `gnss.read_gnss_data(max_retry=1, debug=0)` is called. + +**Return Value** + +String type. The original GNSS data read from the UART. + +**Example** + +```python +data = gnss.getOriginalData() +print(data) +# Only part of the original GNSS data is listed due to the limited space. +00,A,3149.28094,N,11706.93869,E,0.00,153.28,110122,,,A,V*04 +$GNVTG,153.28,T,,M,0.00,N,0.00,K,A*2E +$GNZDA,021555.000,11,01,2022,00,00*4D +$GPTXT,01,01,01,ANTENNA OK*35 +$GNGGA,021556.000,3149.28095,N,11706.93869,E,1,24,0.6,166.5,M,-5.0,M,,*5E +$GNGLL,3149.28095,N,11706.93869,E,021556.000,A,A*47 +$GNGSA,A,3,10,12,21,23,24,25,32,193,194,195,199,,1.0,0.6,0.8,1*35 +$GNGSA,A,3,01,04,07,09,14,21,22,24,38,39,42,45,1.0,0.6,0.8,4*36 +... +$GNGGA,021600.000,3149.28096,N,11706.93877,E,1,25,0.6,166.4,M,-5.0,M,,*52 +$GNGLL,3149.28096,N,11706.93877,E,021600.000,A,A*4B +$GNGSA,A,3,10,12,21,23,24,25,31,32,193,194,195,199,1.0,0.6,0.8,1*37 +$GNGSA,A,3,01,04,07,09,$GNGGA,021601.000,3149.28096,N,11706.93878,E,1,25,0.6,166.4,M,-5.0,M,,*5C +$GNGLL,3149.2809 +``` + +## Check Validity of GNSS Data + +### `gnss.checkDataValidity` + +```python +gnss.checkDataValidity() +``` + +This interface checks the validity of GNGGA, GNRMC and GPGSV sentences in the GNSS data package read. The GNSS module provides an interface for reading GNGGA, GNRMC and GPGSV sentences in the original GNSS data package through the UART. + +**Return Value** + +A tuple ` (gga_valid, rmc_valid, gsv_valid)`. + +`gga_valid` - Whether the GNGGA sentence is read and has been analyzed successfully. 0 – The GNGGA sentence is not read or the data is invalid. 1 – The GNGGA sentence is valid. + +`rmc_valid` - Whether the GNRMC sentence is read and has been analyzed successfully. 0 – The GNRMC sentence is not read or the data is invalid. 1 – The GNRMC sentence is valid. + +`gsv_valid` - Whether the GPGSV sentence is read and has been analyzed successfully. 0 – The GPGSV sentence is not read or the data is invalid. 1 – The GPGSV sentence is valid. + +If you only want to get the positioning result, that is whether the GNGGA sentence is valid, you can set `gga_valid` as 1 or check whether the positioning is successful through *gnss.isFix()* . The GNRMC sentence is analyzed to get the ground speed and the GPGSV sentence is analyzed to get the number of visible satellites and the corresponding azimuth angles of these satellites. Therefore, `rmc_valid` and `gsv_valid` can be omitted. + +**Example** + +```python +gnss.checkDataValidity() +(1, 1, 1) # It indicates the GNGGA, GNRMC and GPGSV sentence all has been read and analyzed successfully. +``` + +## Check Whether Positioning Is Successful + +### `gnss.isFix` + +```python +gnss.isFix() +``` + +Checks whether the valid GNSS data is read through the specified UART. + +**Return Value** + +`1` – Successful execution + +`0` – Failed execution + +**Example** + +``` +gnss.isFix() +1 +``` + +## Get UTC Time + +### `gnss.getUtcTime` + +```python +gnss.getUtcTime() +``` + +Gets UTC time in the GNSS data. + +**Return Value** + +UTC time in string type – Successful execution + +`-1` – Failed execution + +**Example** + +```python +gnss.getUtcTime() +'06:22:05.000' # hh:mm:ss.sss +``` + +## Get Positioning Mode + +### `gnss.getLocationMode` + +```python +gnss.getLocationMode() +``` + +Gets the positioning mode in the GNSS data. + +**Return Value** + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| -1 | Failed execution. No data is read through the UART or the data read through the UART is invalid. | +| 0 | Unavailable or invalid positioning data | +| 1 | Valid positioning. Positioning mode: GPS or SPS mode. | +| 2 | Valid positioning. Positioning mode: DGPS or DSPS mode. | +| 6 | Estimation (dead reckoning) mode | + +**Example** + +```python +gnss.getLocationMode() +1 +``` + +## Get Number of Satellites in Use + +### `gnss.getUsedSateCnt` + +```python +gnss.getUsedSateCnt() +``` + +Gets the number of satellites in use in the GNSS data. + +**Return Value** + +The number of satellites in use in integer type – Successful execution + + `-1` – Failed execution + +**Example** + +``` +gnss.getUsedSateCnt() +24 +``` + +## Get Latitude and Longitude Information + +### `gnss.getLocation` + +```python +gnss.getLocation() +``` + +Gets the latitude and longitude information in the GNSS data. + +**Return Value** + +Latitude and longitude information `(longitude, lon_direction, latitude, lat_direction)` – Successful execution + + `-1` – Failed execution + +`longitude` - Longitude in float type. + +`lon_direction` - Longitude direction in string type. E – east longitude. W – west longitude. + +`latitude` - Latitude in float type. + +`lat_direction` - Latitude direction in string type. N – north latitude. S – south latitude. + +**Example** + +```python +gnss.getLocation() +(117.1156448333333, 'E', 31.82134916666667, 'N') +``` + +## Get Number of Visible Satellites + +### **`gnss.getViewedSateCnt`** + +```python +gnss.getViewedSateCnt() +``` + +Gets the number of visible satellites in the GNSS data. + +**Return Value** + +The number of visible satellites in integer type – Successful execution + + `-1` – Failed execution + +**Example** + +```python +gnss.getViewedSateCnt() +12 +``` + +## Get Visible Azimuth Angles of GNSS Satellites + +### **`gnss.getCourse`** + +```python +gnss.getCourse() +``` + +Gets the visible azimuth angles of GNSS satellites in the GNSS data. + +**Return Value** + +All visible azimuth angles of GNSS satellites. Range: `0–359`. Take due north as the reference plane. The form of return value is a dictionary in which the key indicates the satellite ID and the value indicates the azimuth angle. Please note that the value may be an integer or empty, which depends on whether there is a value for the azimuth angle in the GPGSV sentences in the original GNSS data. + + `-1` – Failed execution + +The format of the return value is as follows: + +`{key:value, ..., key:value}` + +**Example** + +```python + gnss.getCourse() +{'10': 204, '195': 162, '12': 68, '193': 105, '32': 326, '199': 162, '25': 122, '31': 247, '24': 52, '194': 116, '21': 304, '23': 159} +``` + +## Get Altitude + +### **`gnss.getGeodeticHeight`** + +```python +gnss.getGeodeticHeight() +``` + +Gets the altitude in the GNSS data. + +**Return Value** + +Altitude in float type. Unit: meter. – Successful execution + + `-1` – Failed execution + +**Example** + +```python +gnss.getGeodeticHeight() +166.5 +``` + +## Get Ground Speed + +### `gnss.getSpeed` + +```python +gnss.getSpeed() +``` + +Gets the ground speed in the GNSS data. + +**Return Value** + +Ground speed in float type. Unit: km/h. – Successful execution + + `-1` – Failed execution + +**Example** + +```python +gnss.getSpeed() +0.0 +``` diff --git a/docs/API_reference/en/gnsslib/quecgnss.md b/docs/API_reference/en/gnsslib/quecgnss.md new file mode 100644 index 0000000000000000000000000000000000000000..48f2db63a95c4378ac1ec3f73b3ca846ecba2445 --- /dev/null +++ b/docs/API_reference/en/gnsslib/quecgnss.md @@ -0,0 +1,549 @@ +# quecgnss - Internal GNSS Resolver + +This feature provides the APIs of the built-in GNSS feature. + +> QuecPython modules list that support built-in GNSS:
+> ECX00U AA/LA series
+> EG91XU AA series
+> EC800M GA/GB/GC/GD series
EG810M GA series
EC800G GA series
+> BG95M1/M3 model + +**Example** + +```python +import quecgnss + + +def main(): + quecgnss.configSet(0,1)#Set the positioning constellation to GPS + Beidou. + quecgnss.configSet(2,1)#Turn on AGPS + quecgnss.configSet(4,1)#Turn on the backup power supply + ret = quecgnss.init() + if ret == 0: + print('GNSS init ok.') + else: + print('GNSS init failed.') + return -1 + data = quecgnss.read(4096) + print(data[1].decode()) + + quecgnss.gnssEnable(0) + + +if __name__ == '__main__': + main() + + +#=================================================================================================== +#Execution Result +167,169,170,,,,,,,,1.773,1.013,1.455*15 +$GPGSV,2,1,8,3,23,303,34,16,32,219,28,22,74,98,26,25,16,43,25*77 +$GPGSV,2,2,8,26,70,236,28,31,59,12,38,32,55,127,34,4,5,,21*49 +$BDGSV,2,1,8,163,51,192,32,166,70,11,31,167,52,197,32,169,59,334,31*61 +$BDGSV,2,2,8,170,40,205,31,161,5,,31,164,5,,27,165,5,,29*59 +$GNRMC,022326.000,A,3149.324624,N,11706.921702,E,0.000,261.541,180222,,E,A*38 +$GNGGA,022326.000,3149.324624,N,11706.921702,E,1,12,1.013,-8.580,M,0,M,,*47 +$GNGLL,3149.324624,N,11706.921702,E,022326.000,A,A*44 +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.773,1.013,1.455*1C +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.773,1.013,1.455*15 +$GPGSV,2,1,8,3,23,303,34,16,32,219,27,22,74,98,26,25,16,43,25*78 +$GPGSV,2,2,8,26,70,236,28,31,59,12,37,32,55,127,34,4,5,,20*47 +$BDGSV,2,1,8,163,51,192,32,166,70,11,31,167,52,197,32,169,59,334,31*61 +$BDGSV,2,2,8,170,40,205,31,161,5,,31,164,5,,27,165,5,,29*59 +$GNRMC,022327.000,A,3149.324611,N,11706.921713,E,0.000,261.541,180222,,E,A*3F +$GNGGA,022327.000,3149.324611,N,11706.921713,E,1,12,1.013,-8.577,M,0,M,,*48 +$GNGLL,3149.324611,N,11706.921713,E,022327.000,A,A*43 +...... # Omit some data due to large data quantity. +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.837,1.120,1.456*11 +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.837,1.120,1.456*18 +$GPGSV,2,1,8,3,23,302,27,16,32,220,26,22,73,101,27,25,16,43,27*45 +$GPGSV,2,2,8,26,70,237,28,31,59,13,33,32,54,128,28,4,5,,24*44 +$BDGSV,2,1,8,163,51,192,33,166,71,11,35,167,52,198,33,169,59,334,34*6E +$BDGSV,2,2,8,170,40,205,32,161,5,,33,164,5,,28,165,5,,30*5F +$GNRMC,022507.000,A,3149.324768,N,11706.922344,E,0.000,261.541,180222,,E,A*31 +$GNGGA,022507.000,3149.324768,N,11706.922344,E,1,12,1.120,-8.794,M,0,M,,*48 +$GNGLL,3149.324768,N,11706.922344,E,022507.000,A,A*4D +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.837,1.120,1.455*12 +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.837,1.120,1.455*1B +$GPGSV,2,1,8,3,23,302,26,16,32,220,26,22,73,101,27,25,16,43,26*45 +$GPGSV,2,2,8,26,70,237,28,31,59,13,32,32,54,128,28,4,5,,24*45 +$BDGSV,2,1,8,163,51,192,24,166,71,11,35,167,52,198,33,169,59,334,34*68 +$BDGSV,2,2,8,170,40,205,31,161,5,,33,164,5,,28,165,5,,30*5C +$GNRMC,022508.000,A,3149.324754,N,11706.922338,E,0.002,261.541,180222,,E,A*38 +$GNGGA,022508.000,3149.324754,N,11706.922338,E,1,12,1.120,-8.750,M,0,M,,*4B +$GNGLL,3149.324754,N,11706.922338,E,022508.000,A,A*46 +$GNGSA,A,3,31,3 +``` + +## Overview of GNSS Positioning Data + +```python +NMEA Port Data Classification:: + $GPGGA Global Positioning System Fix Data + $GPGSA GNSS DOP and Active Satellites + $GPGSV GNSS Satellites in View + $GPRMC Recommended Minimum Specific GNSS Data + $GPVTG Course Over Ground and Ground Speed + $GPDTM Datum Reference + $GPGNS GNSS Fix Data +NMEA Sentence Parsing: +The basic format of the GSV sentence is as follows: + + $GPGSV,(1),(2),(3),(4),(5),(6),(7),...,(4),(5),(6),(7)*hh(CR)(LF) + + Field 1: Total number of GSV sentences. + + Field 2: Sequence number of the current GSV sentence. + + Field 3: Total number of satellites in view (00–12, leading zeros are transmitted). + + Field 4: Satellite PRN number (01–32, leading zeros are transmitted). + + Field 5: Elevation of the satellite (00–90 degrees, leading zeros are transmitted). + + Field 6: Azimuth of the satellite (000–359 degrees, leading zeros are transmitted). + + Field 7: Signal-to-noise ratio (00–99 dB; left blank if the satellite is not being tracked) — also referred to as the C/N0 value. + +The basic format of the GGA sentence is as follows: + + $GPGGA,(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)*hh(CR)(LF) + + Field 1: UTC time, hhmmss.sss (hours, minutes, seconds format). + + Field 2: Latitude ddmm.mmmm (degrees and minutes format, leading zeros transmitted). + + Field 3: Latitude hemisphere — N (North) or S (South). + + Field 4: Longitude dddmm.mmmm (degrees and minutes format, leading zeros transmitted). + + Field 5: Longitude hemisphere — E (East) or W (West). + + Field 6: GPS status — 0 = Invalid, 1 = GPS fix, 2 = DGPS fix, 3 = Invalid PPS, 6 = Estimated. + + Field 7: Number of satellites used (00–12, leading zeros transmitted). + + Field 8: HDOP (Horizontal Dilution of Precision), range 0.5–99.9. + + Field 9: Altitude (-9999.9 to 99999.9). + + Field 10: Altitude unit, meters. + + Field 11: Height of geoid (ellipsoid relative to mean sea level). + + Field 12: Height unit of geoid separation, meters. + +The basic format of the GSA sentence is as follows: + + $GPGSA,(1),(2),(3),(3),,,,,,,,,,(3),(4),(5),(6),(7)*hh(CR)(LF) + + Field 1: Mode — A = Automatic 2D/3D, M = Manual 2D/3D. + + Field 2: Fix type — 1 = No fix, 2 = 2D fix, 3 = 3D fix. + + Field 3: PRN codes — Satellite PRN number(s) being used in the current fix (00; leading zeros transmitted, up to 12 satellites). + + Field 4: PDOP (Position Dilution of Precision), range 0.0–500.0. + + Field 5: HDOP (Horizontal Dilution of Precision), range 0.0–500.0. + + Field 6: VDOP (Vertical Dilution of Precision), range 0.0–500.0. + + Field 7: Satellite system ID. + +The basic format of the VTG sentence is as follows: + + $GPVTG,(1),(2),(3),(4),(5),(6),(7),(8),(9)*hh(CR)(LF) + + Field 1: Course over ground (000–359, leading zeros transmitted). + + Field 2: Reference — T = True North. + + Field 3: Course over ground (000–359, leading zeros transmitted). + + Field 4: Reference — M = Magnetic North. + + Field 5: Horizontal speed (0.00, leading zeros transmitted). + + Field 6: Unit — N = Knots. + + Field 7: Horizontal speed (0.00, leading zeros transmitted). + + Field 8: Unit — K = Kilometers per hour (km/h). + + Field 9: Mode indicator — E = Estimated, A = Autonomous (non-DGPS). + +The basic format of the RMC sentence is as follows: + + $GPRMC,(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13)*hh(CR)(LF) + + Field 1: UTC time, hhmmss.sss format. + + Field 2: Status — A = Valid (fix), V = Invalid (no fix). + + Field 3: Latitude ddmm.mmmm (degrees and minutes format, leading zeros transmitted). + + Field 4: Latitude hemisphere — N (North) or S (South). + + Field 5: Longitude dddmm.mmmm (degrees and minutes format, leading zeros transmitted). + + Field 6: Longitude hemisphere — E (East) or W (West). + + Field 7: Speed over ground, in knots. + + Field 8: Course over ground, in degrees. + + Field 9: UTC date, DDMMYY format. + + Field 10: Magnetic variation (000–180 degrees, leading zeros transmitted). + + Field 11: Magnetic variation direction — E (East) or W (West). + + Field 12: Mode indicator — E = Estimated, A = Autonomous (non-DGPS). + + Field 13: Navigation status — V = Navigation status not provided. + +The basic format of the DTM sentence is as follows: + + $GNDTM,<1>,<2>,<3>,<4>,<5>,<6>,<7>,<8>*<9>(CR)(LF) + + <1>Local datum code — W84, P90. + + <2>Datum subcode — blank. + + <3>Latitude offset. + + <4>Latitude hemisphere — N (North) or S (South). + + <5>Longitude offset. + + <6>Longitude hemisphere — E (East) or W (West). + + <7>Altitude offset. + + <8>Reference datum code — W84. + + <9>Checksum. + +The basic format of the GNS sentence is as follows: + + $GNGNS,<1>,<2>,<3>,<4>,<5>,<6>,<7>,<8>.<9>,<10>,<11>,<12>,<13>,*<14>(CR)(LF) + + <1> UTC time: Fix time hhmmss.ss — 000000.00 ~ 235959.99 + + <2> Latitude: ddmm.mmmmm — 0000.00000 ~ 8959.9999 + + <3> Latitude hemisphere: N = North, S = South + + <4> Longitude: dddmm.mmmmm — 0000.00000 ~ 17959.99999 + + <5> Longitude hemisphere: E = East, W = West + + <6> Mode indicator: N = No fix; A = Autonomous; D = Differential; P = Precise; R = RTK Fixed; F = RTK Float; E = Estimated; M = Manual input; S = Simulator + + <7> Satellites used: Number of satellites used in fix, 00–99 + + <8> HDOP: Horizontal Dilution of Precision, 0.5–99.9 + + <9> Altitude: Unit = meters + + <10> Geoid separation: Height of geoid relative to WGS84 ellipsoid + + <11> Differential data age: blank if prefix is “GN” + + <12> Reference station ID: blank if prefix is “GN” + + <13> Navigation status: C = Caution, S = Safe, U = Unsafe, V = Invalid + + <14> Checksum +``` + + + +## Initialize GNSS + +### **`quecgnss.init`** + +```python +quecgnss.init() +``` + +Initializes the built-in GNSS feature. + +**Return Value** +`0` - Successful execution + +`-1` - Failed execution + +## Get GNSS Working Status + +### **`quecgnss.get_state`** + +```python +quecgnss.get_state() +``` + +Gets the current working status of the built-in GNSS feature. + +**Return Value** + +| Value | Type | Description | +| ----- | ---- | ------------------------------------------------------------ | +| 0 | int | GNSS feature is disabled. | +| 1 | int | GNSS firmware is being updated. | +| 2 | int | GNSS is positioning. In this mode, the module can read the GNSS location data. After obtaining the location data, the user needs to analyze the corresponding sentence to determine whether the location data is effective. For example, if the status of GNRMC sentences is A or V, A indicates valid positioning and V indicates invalid positioning. | + +## Enable or Disable GNSS + +### `quecgnss.gnssEnable` + +```python +quecgnss.gnssEnable(opt) +``` + +Enables or disables GNSS feature. If you use the built-in GNSS feature for the first time after powering the module on, you need not call this function to enable GNSS feature, but call *quecgnss.init()* directly. *quecgnss.init()* will automatically enable the GNSS feature when GNSS feature is initialized. + +**Parameter** + +`opt` - Integer type. Enable or disable GNSS. + + `0` - Disable the GNSS feature. + + `1` - Enable the GNSS feature. + +**Return Value** + + `0` - Successful execution + + `-1` - Failed execution + +## Get GNSS Location Data + +### `quecgnss.read` + +```python +quecgnss.read(size) +``` + +Gets GNSS location data. + +**Parameter** + +`size` - Integer type. Size of the data to be read. Unit: byte. + +**Return Value** + +A tuple `(size, data)` - Successful execution + +`size` - Size of the data read. +`data` - GNSS location data. + +-1 - Failed execution + +## GNSS/LTE Priority Settings + +> Currently, this function is only supported by BG95M1/M3 models. + +### `quecgnss.setPriority` + +```python +quecgnss.setPriority(Priority) +``` + +On some modules, GNSS and LTE share RF resources. This interface is used to control the priority of RF resource usage between GNSS and LTE. + +**Parameter** + +`Priority`, integer type, sets the priority value between GNSS and LTE. + +Correspondence of priority levels for GNSS/LTE on different platforms: + +| Priority | BG95M1/M3 | +| ------ | -------- | +| 0 | GNSS>LTE | +| 1 | LTE>GNSS | + +**Return Value** + + `0` - Successful execution + + `-1` - Failed execution + +## Get GNSS/LTE Priority + +> Currently, this function is only supported by BG95M1/M3 models. + +### `quecgnss.getPriority` + +```python +quecgnss.getPriority() +``` + +On some modules, GNSS and LTE share RF resources. This interface is used to read the priority of RF resource usage between GNSS and LTE. + +**Return Value** + +Returns an integer representing the GNSS/LTE priority. + +Correspondence of GNSS/LTE priority across different platforms: + +| Priority | BG95M1/M3 | +| ------ | -------- | +| 0 | GNSS>LTE | +| 1 | LTE>GNSS | + +## Built-in GNSS Configuration Parameter Settings + +> Currently, this function is supported only by the EC800M GA/GB/GC/GD series, EG810M GA series, and ECX00U AA/LA series. + +### `quecgnss.configSet` + +```python +quecgnss.configSet(config_type, config_value) +``` + +Sets GNSS parameters, including satellite system, NMEA sentence types, whether to use AGNSS, APFLASH, etc. + +**Parameter Description** + +* `config_type`,int,The types of GNSS configuration options to be set are as follows: + +| Value | Description | +| ---- | ---------------------- | +| 0 | Configure the satellite system to be used | +| 1 | Configure the types of NMEA sentences to output | +| 2 | Configure whether to enable AGPS | +| 3 | Configure whether to enable APFLASH | +| 4 | Configure whether to enable GNSS backup power | + +* `config_value`,int,The values of GNSS configuration options and their meanings are as follows: + +Satellite System(config_type = 0): + +| Value | Description | +| ----- | ----------------------- | +| 0 | GPS | +| 1 | GPS + BeiDou | +| 3 | GPS + GLONASS + Galileo | +| 4 | GPS + GLONASS | +| 5 | GPS + BeiDou + Galileo | +| 6 | GPS + Galileo | +| 7 | BeiDou | + +NMEA Sentence Types (config_type = 1): This field is represented as a bitmap. Options to be enabled should be set to 1. +For example, to output GGA + RMC + GSV + GSA + VTG, the bitmap should be `011111`, which corresponds to a decimal value of 31. + +| Value | Description | +| ----- | --------------------- | +| 0 | Disable all (000000). | +| 1 | GGA(000001) | +| 2 | RMC(000010) | +| 4 | GSV(000100) | +| 8 | GSA(001000) | +| 16 | VTG(010000) | +| 32 | GLL(100000) | +| 63 | All outputs (111111). | + +Enable AGPS (config_type = 2): When enabled, GNSS will download ephemeris data from the network and attempt to use it at startup to accelerate positioning. + +| Value | Description | +| ----- | ----------- | +| 0 | Disable | +| 1 | Enable | + +Enable APFLASH (config_type = 3): When enabled, GNSS will store ephemeris data on the Quecpython module and attempt to use it at startup to accelerate positioning. + +| Value | Description | +| ----- | ----------- | +| 0 | Disable | +| 1 | Enable | + +Enable Backup Power (config_type = 4): When enabled and backup power is properly connected, the GNSS chip can autonomously store ephemeris data. + +>Backup power is supported on the EC800M GB/GD series. + +| Value | Description | +| ---- | ----------- | +| 0 | Disable | +| 1 | Enable | + +**Return Value** + +int: 0 indicates success; any other value indicates failure. + +## Read Built-in GNSS Configuration Parameters + +> Currently, this function is supported only by the EC800M GA/GB/GC/GD series, EG810M GA series, and ECX00U AA/LA series. + +### `quecgnss.configGet` + +```python +quecgnss.configGet(config_type) +``` + +Reads GNSS parameters, including satellite system, NMEA sentence types, whether AGNSS is used, APFLASH, etc. + +**Parameter Description** + +* `config_type`,int,The types of GNSS configuration options to be read are as follows: + +| Value | Description | +| ---- | ---------------------- | +| 0 | Configure the satellite system to be used | +| 1 | Configure the types of NMEA sentences to output | +| 2 | Configure whether to enable AGPS | +| 3 | Configure whether to enable APFLASH | +| 4 | Configure whether to enable GNSS backup power | + +**Return Value** + +int,Meanings are as follows (–1 indicates failure). + +Satellite System(config_type = 0): + +| Value | Description | +| ----- | ----------------------- | +| 0 | GPS | +| 1 | GPS + BeiDou | +| 3 | GPS + GLONASS + Galileo | +| 4 | GPS + GLONASS | +| 5 | GPS + BeiDou + Galileo | +| 6 | GPS + Galileo | +| 7 | BeiDou | + +NMEA Sentence Types (config_type = 1): This field is represented as a bitmap. Options that are enabled are set to 1. +For example, if GGA + RMC + GSV + GSA + VTG are output, the returned value is 31, which corresponds to the bitmap 011111 in binary. + +| Value | Description | +| ----- | --------------------- | +| 0 | Disable all (000000). | +| 1 | GGA(000001) | +| 2 | RMC(000010) | +| 4 | GSV(000100) | +| 8 | GSA(001000) | +| 16 | VTG(010000) | +| 32 | GLL(100000) | +| 63 | All outputs (111111). | + +Enable AGPS (config_type = 2): When enabled, GNSS will download ephemeris data from the network and attempt to use it at startup to accelerate positioning. + +| Value | Description | +| ----- | ----------- | +| 0 | Disable | +| 1 | Enable | + +Enable APFLASH (config_type = 3): When enabled, GNSS will store ephemeris data on the Quecpython module and attempt to use it at startup to accelerate positioning. + +| Value | Description | +| ----- | ----------- | +| 0 | Disable | +| 1 | Enable | + +Enable Backup Power (config_type = 4): When enabled and backup power is properly connected, the GNSS chip can autonomously store ephemeris data. + +>Backup power is supported on the EC800M GB/GD series. + +| Value | Description | +| ---- | ----------- | +| 0 | Disable | +| 1 | Enable | \ No newline at end of file diff --git a/docs/API_reference/en/gnsslib/wifiScan.md b/docs/API_reference/en/gnsslib/wifiScan.md new file mode 100644 index 0000000000000000000000000000000000000000..6435a790251be8ea3cff1e37f7525001799351a5 --- /dev/null +++ b/docs/API_reference/en/gnsslib/wifiScan.md @@ -0,0 +1,226 @@ +# wifiScan - Wi-Fi Scan + +`wifiScan` provides both synchronous and asynchronous modes to scan the Wi-Fi hotspot information around the module. + + + +> The following modules support the `wifiScan` feature. +> +> EC100Y/EC200N/EC600N/EC600S/EC600M/EC800M/EC800N/EG912N/EG915N/EG810M/EC600G/EC800G/EC200U/EC600U/EG912U/EG915U series module. +> +> In EC600M series module: EC600MCN_LA/EC600MCN_LE/EC600MEU_LA support the `wifiScan` feature. +> +> In EC800M series module: EC800MCN_GA/EC800MCN_LA/EC800MCN_LE/EC800MCN_LF/EG810MCN_GA support the `wifiScan` feature. +> +> In EC600U series module: EC600UCN_LB/EC600UEU_AB support the `wifiScan` feature. +> +> In E200U series module: EC200UAU_AA/EC200UAU_AB/EC200UCN_AA/EC200UCN_LA/EC200UCN_LB/EC200UEU_AA/EC200UEU_AB support the `wifiScan` feature. +> +> In EG912U series module: EG912UGL_AA support the `wifiScan` feature. +> +> In EG915U series module: EG915UEU_AB/EG915ULA_AB support the `wifiScan` feature. + + + +## Enable/Disable Wi-Fi Scan + +### `wifiScan.control` + +```python +wifiScan.control(option) +``` + +Enables or disables Wi-Fi scan. + +**Parameter** + +* `option` - Integer type. Wi-Fi scan control option. + + `0` - Disable Wi-Fi scan + + `1` - Enable Wi-Fi scan + +**Return Value** + +`0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> import wifiScan +>>> wifiScan.control(1) # Enable Wi-Fi scan. +0 +>>> wifiScan.control(0) # Disable Wi-Fi scan. +0 +``` + + + +### `wifiScan.getState` + +```python +wifiScan.getState() +``` + +Gets the current status of Wi-Fi scan. + +**Return Value** + +`True` - The Wi-Fi scan is enabled. + +`False` - The Wi-Fi scan is disabled. + + + +## Set and Get the Scan Parameters of Wi-Fi Scan + +### `wifiScan.setCfgParam` + +```python +wifiScan.setCfgParam(timeout, round, maxNums[, priority]) +``` + +Sets the scan parameters of Wi-Fi scan. + +**Parameter** + +* `timeout` - Integer type. Timeout. When a timeout is triggered, the system automatically reports the detected hot spots. If the specified number of hot spots is detected before the timeout, the system stops scanning and returns the scanning result. Range: 4–60. Unit: s. + +* `round` - Integer type. Number of scan rounds. When the number of scan rounds is reached, the scan ends and the scan result is returned. Range: 1–3. Unit: time. + +* `maxNums` - Integer type. The maximum number of scanned hotspots. When the number of scanned hotspots reaches the upper limit, the scan ends and the scan result is returned. Range: 4–30. + +* `priority` - Integer type. Priority of businesses. + + `0` - Network business first. Wi-Fi scan will be interrupted when a data service is initiated. + + `1` - Wi-Fi scan first. When a data service is initiated, the RRC connection is not set up. To ensure that the Wi-Fi scan is performed properly, the RRC connection is set up only after the scan is complete. + +**Return Value** + +`0` - Successful execution + +`-1` - Failed execution + + + +> EC200U/EC600U/EG912U/EG915U/EC600G/EC800G series module does not support `priority`, so `priority` can be omitted. + + + +### `wifiScan.getCfgParam` + +```python +wifiScan.getCfgParam() +``` + +Gets the scan parameters of Wi-Fi scan. + +**Return Value** + +A tuple `(timeout, round, maxNums, priority)` - Successful execution + +` -1` - Failed execution + +See `(timeout, round, maxNums, priority)` in `wifiScan.setCfgParam` for details. + + + +## Register Callback Function + +### `wifiScan.setCallback` + +```python +wifiScan.setCallback(fun) +``` + +Registers the callback function. When asynchronous scanning is used, you need to register the callback function, and the scan result is returned to the user through the callback function. + +**Parameter** + +* `fun` - Callback function name. The callback function format and parameters are described below. + +```python +def wifiscanCallback(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ----- | ------------------------------------------------------------ | +| args | Tuple | `(nums, [(mac, rssi),...,(mac, rssi)])`
`nums` - Integer type. The number of scanned Wi-Fi hotspots.
`mac` - String type. MAC address of the Wi-Fi hotspots.
`rssi` - Integer type. Signal strength of the Wi-Fi hotspots. | + +**Return Value** + +`0` - Successful execution + +`-1` - Failed execution + + + +## Start Scanning + +### `wifiScan.asyncStart` + +```python +wifiScan.asyncStart() +``` + +Starts scanning in Wi-Fi scan asynchronous mode. The scan result is returned through the registered callback function. + +**Return Value** + +`0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +import wifiScan + +def wifiscanCallback(args): + print('wifi list:{}'.format(args)) +wifiScan.setCallback(wifiscanCallback) + +wifiScan.control(1) +wifiScan.asyncStart() + +''' +Execution result +wifi list:(2, [('F0:B4:29:86:95:C7', -79),('44:00:4D:D5:26:E0', -92)]) +''' +``` + + + +### `wifiScan.start` + +```python +wifiScan.start() +``` + +Starts scanning in Wi-Fi scan synchronous mode. The scan result is returned after the scan is complete. Because the interface is synchronous, the program will be blocked in the interface when the scan does not end. + +**Return Value** + +A tuple `(wifiNums, [(mac, rssi), ... , (mac, rssi)])` - Successful execution + +`-1` - Failed execution + + + +| Parameter | Type | Description | +| --------- | ------- | -------------------------------------- | +| wifiNums | Integer | The number of scanned Wi-Fi hotspots. | +| mac | String | MAC address of the Wi-Fi hotspots. | +| rssi | Integer | Signal strength of the Wi-Fi hotspots. | + +**Example** + +```python +>>> wifiScan.start() +(7, [('34:CE:00:09:E5:A8', -30), ('30:FC:68:E2:2D:F7', -44), ('12:CA:41:D4:B2:50', -54), ('D0:DB:B7:90:2D:07', -58), ('00:03:7F:12:CB:CB', -61), ('60:38:E0:C2:84:D9', -62), ('08:4F:0A:05:22:8F', -63)]) +``` + diff --git a/docs/API_reference/en/gnsslib/wifilocator.md b/docs/API_reference/en/gnsslib/wifilocator.md new file mode 100644 index 0000000000000000000000000000000000000000..56dd3857327e62653ac8790338175bda5793735f --- /dev/null +++ b/docs/API_reference/en/gnsslib/wifilocator.md @@ -0,0 +1,70 @@ +# class wifilocator - Wi-Fi Positioning + +This module provides the class of Wi-Fi positioning and gets the module longitude and latitude coordinate. + + + +> Currently, only EC600S/EC600N/EC800N/EC200U/EC600U/EG912U/EG915U series module supports this feature. + + + +**Example:** + +```python +import wifilocator +# Creates a wifilocator object +wifiloc = wifilocator.wifilocator("xxxxxxxxxxxxxxxx") +# Gets the module coordinate +wifiloc.getwifilocator() +(117.1152877807617, 31.82142066955567, 100) +# The secret key "xxxxxxxxxxxxxxxx" used above refers to token. You can apply for a secret key from Quectel. +``` + + + +## Constructors + +### `wifilocator.wifilocator` + +```python +class wifilocator.wifilocator(token) +``` + +Creates a wifilocator object and configures the suite token of Wi-Fi positioning. Creates a wifilocator object and uses a specified token to configure the Wi-Fi positioning suite. + +**Parameter:** + +- `token` - String type. Secret key. It consists of 16 bit characters and you can apply for it from Quectel. + + + +## Get the Coordinate + +### wifilocator.getwifilocator + +```python +wifilocator.getwifilocator() +``` + +This method gets the module longitude and latitude coordinate. + +**Return Value:** + +If successful, it returns the module longitude and latitude coordinate. Tuple format: `(longtitude, latitude, accuracy)`; + +`longtitude` : longitude. + +`latitude` : latitude. + +`accuracy` : accuracy. Unit: meter. + +If failed, it returns the error code. The error code description is as follows: + +`1` – Network error. Please confirm whether the dial is normal. + +`2` – Secret key length error. The length must be 16 bytes. + +`3` – Error in getting coordinates. + + + diff --git a/docs/API_reference/en/iotlib/README.md b/docs/API_reference/en/iotlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..12fbec29b9e88a805f7deab597385512490a9a6d --- /dev/null +++ b/docs/API_reference/en/iotlib/README.md @@ -0,0 +1,15 @@ +# QuecPython cellular communication + +> QuecPython Cellular Communication Library includes all cellular communication related functional components + +This article describes the modules in the QuecPython cellular communication library. + +## QuecPython cellular communication library list + +- [dataCall - Dialing](./dataCall.md) +- [sim-SIM card function](./sim.md) +- [sms - sms function](./sms.md) +- [voiceCall - Phone function](./voiceCall.md) +- [net - Network related functions](./net.md) +- [checkNet - Network readiness check](./checkNet.md) +- [ussd - USSD function](./ussd.md) \ No newline at end of file diff --git a/docs/API_reference/en/iotlib/checkNet.md b/docs/API_reference/en/iotlib/checkNet.md new file mode 100644 index 0000000000000000000000000000000000000000..2529c881d197933a7c02289b112979f42c0bf0e2 --- /dev/null +++ b/docs/API_reference/en/iotlib/checkNet.md @@ -0,0 +1,91 @@ +# checkNet - Network Detection + +The `checkNet` module provides methods to detect whether the QuecPython module's network is ready, while also providing troubleshooting methods and steps for network exceptions. + + + +## Wait for the Network to be Ready + +### `checkNet.waitNetworkReady` + +```python +checkNet.waitNetworkReady(timeout) +``` + +Waits for the module's network to be ready. This method checks the SIM card status, module network registration status, and PDP context activation status in order. If PDP context activation is detected successfully within the specified timeout period, it will return a result immediately. Otherwise, it will continue waiting until the timeout is reached. + +**Parameter:** + +* `timeout` - Integer type. Timeout. Range: 1–3600. Unit: s. Default value: `60`. + +**Return Value:** + +Returns a tuple in `(stage, state)` format: + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| stage | Integer | The status currently being checked:
1 - Checking SIM card status;
2 - Checking network registration status;
3 - Checking PDP context activation status. | +| state | Integer | The stage value indicates different status:
When stage = 1, it indicates the SIM card status. Range: 0–21. For details of each status value, refer to the return value of the `sim.getStatus()` method;
When stage = 2, it indicates the network registration status. Range: 0–11. For details of each status value, refer to the return value of the `net.getState()` method;
When stage = 3, it indicates the PDP Context activation status. 0 indicates failed activation and 1 indicates successful activation. | + +If the network is ready, `(3,1)` will be returned. Otherwise, refer to the following table to troubleshoot and locate the problem: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
stage + state + Description +
10It indicates that there is no card inserted or that the card slot is loose, please check and confirm.
Other valuesPlease refer to the official WiKi documentation for SIM card status values to confirm the current status of the SIM card.
2-1It indicates that within the timeout period, the API for getting the module's network registration status fails continuously. Please give feedback to our FAE if the SIM card is normal and can be recognized by the module.
0 or 2It indicates that the module has not been successfully registered to the network within the timeout period. Please follow the steps below to troubleshoot:
(1) First, confirm whether the SIM card status is normal through the sim.getState() interface of the SIM module. If the return value is 1, the status is normal;
(2) If the SIM card status is normal, check the current signal strength through the net.csqQueryPoll() interface of the net module. If the signal strength is weak, the failed network registration in a short period of time may be caused by weak signal strength. You can increase the timeout period or move to a location with better signal strength and retry.
(3) If the SIM card status is normal and the signal strength is good, confirm if the SIM card is overdue or out of data traffic.
(4) If the SIM card is not overdue or out of data traffic, confirm if the card used is an IoT card and if there is a machine-card binding for the SIM card.
(5) If the problem still cannot be solved after the above steps, please contact Quectel Technical Support for assistance. Please provide relevant SIM card information, such as the operator, type, IMSI, etc., and if necessary, please send the SIM card to us for troubleshooting.
Other valuesPlease refer to the official Wiki documentation for the net.getState() interface to confirm the reason for the network registration failure.
30It indicates that the PDP Context has not been activated successfully within the timeout period. Please follow the steps below to troubleshoot:
(1)Get the SIM card status through the sim.getState() interface of the SIM module. If the return value is 1, the status is normal.
(2) Get the network registration status through the net.getState() interface of the net module. If the return value is 1, the status is normal.
(3) Manually call the dataCall.activate(profileID) interface to activate it and see if it can be activated successfully.
(4) If manual activation is successful but automatic activation fails, please contact Quectel Technical Support for assistance.
1It is a normal return, indicating that the network is ready, and network-related business operations can be carried out.
+ + + + + + + + + +**Example:** + +```python +import checkNet + +if __name__ == '__main__': + stage, state = checkNet.waitNetworkReady(30) + if stage == 3 and state == 1: + print('Network connection successful.') + else: + print('Network connection failed, stage={}, state={}'.format(stage, state)) +``` + diff --git a/docs/API_reference/en/iotlib/dataCall.md b/docs/API_reference/en/iotlib/dataCall.md new file mode 100644 index 0000000000000000000000000000000000000000..60004215752bfecb0dc4e55f1f7c8ff0e02509b7 --- /dev/null +++ b/docs/API_reference/en/iotlib/dataCall.md @@ -0,0 +1,442 @@ +# dataCall - Data Call + +Establishing a cellular network channel refers to the activation of PDP context, and after a successful activation, the PDN gateway of the core network will assign an IP address to the QuecPython module. + +The `dataCall` module contains features of configuring, obtaining , activating and deactivating PDP context, and feature of obtaining the module's IP information. After burning the QuecPython firmware into the module, it will automatically establish a cellular network channel upon startup. If you have configured the APN, the module will use the configured APN information for establishment; otherwise, it will use the default APN. + + + +> When using a SIM card from a different operator, you should configure the APN information of the corresponding operator. Failure to configure or incorrect configuration may result in the module's failure to register to the network, failure to establish the network channel, inability to obtain an IP address, and failure to access the Internet. For information on configuring the APN, refer to the `dataCall.setPDPContext` method. + + + +**Example:** + +```python +import dataCall +from misc import Power + +# The APN information that the user needs to configure. Modify it according to the actual situation +usrConfig = {'apn': '3gnet', 'username': '', 'password': ''} + +# Obtains the information of the first APN, confirming whether the currently used APN is the one specified by the user +pdpCtx = dataCall.getPDPContext(1) +if pdpCtx != -1: + if pdpCtx[1] != pdpConfig['apn']: + # If it is not the APN that the user needs, configure it as follows + ret = dataCall.setPDPContext(1, 0, pdpConfig['apn'], pdpConfig['username'], pdpConfig['password'], 0) + if ret == 0: + print('APN configuration succeeded.') + # After restarting, establish the channel according to the configured information + Power.powerRestart() + else: + print('APN configuration failed.') + else: + print('APN has already been configured.') +else: + print('Failed to obtain PDP Context.') +``` + + + +## APN Configuration and Retrieval + +### `dataCall.setPDPContext` + +``` +dataCall.setPDPContext(profileID, ipType, apn, username, password, authType) +``` + +Configures the relevant information of the PDP context, and saves the configuration information when power is off. When establishing the channel, use the parameters configured by this method to activate the PDP context. + +**Parameter:** + +* `profileID` - Integer type. PDP context ID. Range: 1–3. It is usually set to `1`. +* `ipType` - Integer type. IP protocol type. See the table below for possible values: + +| Value | Description | +| ----- | ------------- | +| 0 | IPv4 | +| 1 | IPv6 | +| 2 | IPv4 and IPv6 | + +- `apn` - String type. Access Point Name. It can be null, in which case it should be written as `''`. Range: 0–64. Unit: byte. + +- `username` - String type. Username. It can be null, in which case it should be written as `''`. Range: 0–64. Unit: byte. + +- `password` - String type. Password. It can be null, in which case it should be written as `''`. Range: 0–64. Unit: byte. + +- `authType` - Integer type. APN authentication method. See the table below for possible values: + +| Value | Description | +| ----- | ------------ | +| 0 | None | +| 1 | PAP | +| 2 | CHAP | +| 3 | PAP and CHAP | + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + + + +> For BG95 series modules, the range of `profileID` is 1–2 in the NB network mode. +> +> Only BG95 series modules support the value 3 of `authType` .When setting the `username` and `password` as non-empty strings, and the `authType` is `0`, it will automatically change to `2`. When setting the `username` and `password` as empty strings, and the `authType` is `non-zero`, it will automatically change to `0`. +> +> As the first route of the LTE network is established during the registration phase, when changing the `ipType` of the first route, a cfun0/1 operation or a restart is required for it to take effect. +> +> The BC32 series needs to be configured with cfun=0, and only the first line is supported. +> +> The BC32 series `apn `, `username`, and `password` range from 0 to 36 bytes. +> +> The BG95 series `apn ` range from 0 to 63 bytes, and when the `authType` is 0, it is not allowed for the `username` and `password` to be empty strings. +> +> Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32 series module. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.setPDPContext(1, 0, '3gnet', '', '', 0) +0 +``` + + + +### `dataCall.getPDPContext` + +```python +dataCall.getPDPContext(profileID) +``` + +Gets the relevant information of the PDP context for the specified `profileID`. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + + +**Return Value:** + +Returns `-1` for failed execution and returns a tuple containing PDP context information for successful execution. The format of the tuple is as follows: + +`(ipType, apn, username, password, authType)` + +See the parameter of `dataCall.setPDPContext` method for the tuple parameter. + + + +>Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32 series module. + + + +**Example: ** + +```python +>>> import dataCall +>>> dataCall.getPDPContext(1) +(0, '3gnet', '', '', 0) +``` + + + +## Establish the Cellular Network Channel Automatically at Startup + +### `dataCall.setAutoActivate` + +```python +dataCall.setAutoActivate(profileID, enable) +``` + +Sets whether the PDP context for the specified `profileID` is automatically activated during startup. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + +- `enable` - Integer type. Controls whether the module automatically activates the PDP context during startup. `0` indicates disable and `1` indicates enable. + + + +>If you have not called `dataCall.setAutoActivate` and `dataCall.setAutoConnect` method, then the PDP context whose `profileID` is 1 is automatically activated and reconnected at startup by default; otherwise, it is executed according to your configuration. +> +>The BC32 series supports only the first line activation and does not support multiple dialing. +> +>Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32 series module. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.setAutoActivate(1, 0) # Disables the PDP context automatic activation feature for the PDP context whose profileID is 1. +>>> dataCall.setAutoActivate(1, 1) # Enables the PDP context automatic activation feature for the PDP context whose profileID is 1. +``` + + + +## Automatic Reconnection + +### `dataCall.setAutoConnect` + +```python +dataCall.setAutoConnect(profileID, enable) +``` + +Enables or disables the automatic reconnection feature for the specified `profileID`. Automatic reconnection feature refers to the behavior of the module to automatically reconnect when the module disconnects from the network due to abnormal network conditions, poor signal, or other exceptional scenarios, and the network conditions return to normal. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + +- `enable` - Integer type. Controls whether to enable automatic reconnection. `0` indicates disable and `1` indicates enable. + + + +> If you have not called `dataCall.setAutoActivate` and `dataCall.setAutoConnect` method, then the PDP context whose `profileID` is 1 is automatically activated and reconnected at startup by default; otherwise, it is executed according to your configuration. +> +> BC32 series 2G network does not support the reconnection function. +> +> Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95 series module. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.setAutoConnect(1, 0) # Disables automatic reconnection feature for the PDP context whose profileID is 1 +>>> dataCall.setAutoConnect(1, 1) # Enables automatic reconnection feature for the PDP context whose profileID is 1 +``` + + + +## DNS Configuration + +### `dataCall.setDNSServer` + +```python +dataCall.setDNSServer(profileID, simID, priDNS, secDNS) +``` + +Sets the DNS server address. After establishing the cellular network channel successfully, the module will automatically obtain the DNS server address, and generally it is unnecessary to reconfigure it. If the DNS server address automatically obtained by the module is unavailable, you can reconfigure it with this method. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + +- `simID` - Integer type. SIM card slot number. `0` indicates SIM0; `1` indicates SIM1. Currently only `0` is supported. + +- `priDNS` - String type. Primary DNS server address. + +- `secDNS` - String type. Secondary DNS server address. + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + + + +>Modules that support this method: +> +>EC600N/EC800N/EG912N/EG915N/EC200A/EC200U/EC600U/EG912U/EG915U series module. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.setDNSServer(1, 0, "8.8.8.8", "114.114.114.114") +0 +``` + + + +## Register Callback Function + +### `dataCall.setCallback` + +```python +dataCall.setCallback(fun) +``` + +Registers a callback function. When the network status changes, such as when the network is disconnected or the reconnection is successful, this callback function will be triggered to inform the user of the network status. + +**Parameter:** + +* `fun` - The name of the callback function. The format and parameters of the callback function is described as follows: + +```python +def netCallback(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| args[0] | Integer | PDP context ID, indicating which PDP network state has changed | +| args[1] | Integer | Network status. 0 means the network is disconnected and 1 means the network is connected | + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + + + +> Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95 series module. +> + + + +**Example:** + +```python +import dataCall + +def netCallback(args): + pdp = args[0] + datacallState = args[1] + if datacallState == 0: + print('### network {} disconnected.'.format(pdp)) + elif datacallState == 1: + print('### network {} connected.'.format(pdp)) + +dataCall.setCallback(netCallback) +``` + + + +## Activation and Deactivation + +### `dataCall.activate` + +``` +dataCall.activate(profileID) +``` + +Activates the PDP context specified by `profileID`. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + + + +> The PDP context is automatically activated by the module at startup, so you don't have to activate it manually. If you have disabled the automatic PDP context activation feature, you need to call this method to activate the PDP context. +> +> The BC32 series supports only the first line activation and does not support multiple dialing. +> +> Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32 series module. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.setPDPContext(1, 0, '3gnet', '', '', 0) # Before activation, you should first configure the APN. Here the first APN is configured +0 +>>> dataCall.activate(1) # Activate the first APN +0 +``` + + + +### `dataCall.deactivate` + +``` +dataCall.deactivate(profileID) +``` + +Deactivates the PDP context specified by `profileID`. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + + + +> Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95 series module. + + + +## Cellular Network Channel Establishment Information + +### `dataCall.getInfo` + +```python +dataCall.getInfo(profileID, ipType) +``` + +Gets cellular network channel establishment information, including establishment status, IP address, DNS server address, etc. + +**Parameter:** + +- `profileID` - Integer value. PDP context ID. Range: 1–3. +- `ipType` - Integer type. IP protocol type. The value range is as follows: + +| Value | Description | +| ----- | ------------- | +| 0 | IPv4 | +| 1 | IPv6 | +| 2 | IPv4 and IPv6 | + +**Return Value:** + +Returns `-1` for failed execution and returns a tuple containing establishment information for successful execution. See the following description: + +`ipType` can be set to 0 or 1. The return value format is as follows: + +`(profileID, ipType, [state, reconnect, addr, priDNS, secDNS])` + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| profileID | Integer | PDP context ID | +| ipType | Integer | IP protocol type, with the following values:
0 indicates IPv4
1 indicates IPv6
2 indicates IPv4 and IPv6 | +| state | Integer | Establishment status of IPv4 or IPv6:
0 indicates that the establishment has not been performed or has failed
1 indicates successful establishment | +| reconnect | Integer | Reconnection flag. It is a reserved parameter and is not currently used. | +| addr | String | The address of IPv4 or IPv6, depending on the input value of `ipType`.
If `ipType` is 0, `addr` is IPv4
If `ipType` is 1, `addr` is IPv6 | +| priDNS | String | Primary DNS server address | +| secDNS | String | Secondary DNS server address | + +If `ipType` is set to 2, the return value format is as follows: + +`(profileID, ipType, [state, reconnect, ipv4Addr, priDNS, secDNS], [state, reconnect, ipv6Addr, priDNS, secDNS])` + +In the returned tuple, the first list contains IPv4 channel establishment information, and the second list contains IPv6 channel establishment information. + + + +>The return value `(1, 0, [0, 0, '0.0.0.0', '0.0.0.0', '0.0.0.0'])` indicates that the establishment has not been performed or has failed. +> +>The BC32 series supports only the first line activation and does not support multiple dialing, as well as the retrieval of DNS server addresses for IPv6 dial-ups. +> +>Modules that support this method: EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32 series module. +> +>Since it should be compatible with the old version of `dataCall.getInfo`, the maximum value of the actual `profileID` is greater than 3, and the actual `profileID` that can be queried shall prevail. + + + +**Example:** + +```python +>>> import dataCall +>>> dataCall.getInfo(1, 0) +(1, 0, [1, 0, '10.91.44.177', '58.242.2.2', '218.104.78.2']) +``` + + diff --git a/docs/API_reference/en/iotlib/net.md b/docs/API_reference/en/iotlib/net.md new file mode 100644 index 0000000000000000000000000000000000000000..20be678706b9cd4dbe3cfb55687cde0481c90802 --- /dev/null +++ b/docs/API_reference/en/iotlib/net.md @@ -0,0 +1,1053 @@ +# net - Networks + +This feature is related to the network and provides interfaces of configuring and querying the information of the network mode, such as getting the network registration status and setting the network searching mode. + +>Note: It is recommended that you should configure the APN information of the corresponding operator when using SIM cards of different operators. If the APN information is not configured or the configuration is incorrect, the module may not register on the network. See `dataCall.setPDPContext` for methods of how to configure the APN information. + + + +## Get Signal Strength + +### `net.csqQueryPoll` + +```python +net.csqQueryPoll() +``` + +This method gets the signal strength. + +**Return Value:** + + Value of CSQ signal strength - Successful execution + +`-1` - Failed execution + +`99` - Error + +>Note: Range of the value of signal strength: 0–31. The higher the value, the better the signal strength. + + + +**Example:** + +```python +>>> import net +>>> net.csqQueryPoll() +31 +``` + + + +## Get Cell Information + +### `net.getCellInfo` + +```python +net.getCellInfo() +``` + +This method gets the information of neighbour cells. + +**Return Value:** + + List of the information of three network modes `(GSM, UMTS, LTE)` - Successful execution. + +`-1` - Failed execution. + +An empty list - The information of the corresponding network mode is empty. + +`([(flag, cid, mcc, mnc, lac, arfcn, bsic, rssi)], [(flag, cid, licd, mcc, mnc, lac, uarfcn, psc, rssi)], [(flag, cid, mcc, mnc, pci, tac, earfcn, rssi, rsrq),...])` + +* Descriptions of `GSM` network mode + +| Parameter | Description | +| --------- | ------------------------------------------------------------ | +| `flag` | Cell type. Range: 0–3. 0: Current serving cell. 1: Neighbour cell. 2: Intra-frequency neighbour cell. 3: Inter-frequency neighbour cell. | +| `cid` | Cell ID in GSM network. 0 indicates empty. Range: 0–65535. | +| `mcc` | Mobile Country Code. Range: 0–999.
Note: For EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95 series module, the value needs to be converted to hexadecimal. For example, Decimal number 1120 is 0x460 in hexadecimal in which 460 indicates MCC460. For other series modules, this value is in decimal format. | +| `mnc` | Mobile Network Code. Range: 0–99.
Note: For EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95 series module, the value needs to be converted to hexadecimal. | +| `lac` | Location Area Code. Range: 1–65535. | +| `arfcn` | Absolute Radio Frequency Channel Number. Range: 0–65535. | +| `bsic` | Base Station Identification Code. Range: 0–63. | +| `rssi` | In GSM network, this value indicates Rx level and describes the received signal strength. 99 indicates unknown or undetectable.
RSSI = RXLEV - 111. Unit: dBm. Range of RXLEV: 0–63. Range of RSSI: -111 to -48 dBm. | + +* Descriptions of `UMTS` network mode + +| Parameter | Description | +| --------- | ------------------------------------------------------------ | +| `flag` | Cell type. Range: 0–3. 0: Current serving cell. 1: Neighbour cell. 2: Intra-frequency neighbour cell. 3: Inter-frequency neighbour cell. | +| `cid` | Cell identity in UMTS network mode. Cell identity = RNC_ID × 65536 + Cell_ID. Range of cell identity: 0x0000000–0xFFFFFFF (The cell identity is 28 bits). It means that the first two bytes of cell identity indicate RNC_ID and the last two bytes indicate Cell_ ID. Range of Cell_ID: 0–65535. | +| `lcid` | URA ID. Range: 0–65535. 0 indicates that the information does not exist. | +| `mcc` | Mobile Country Code. Range: 0–999. | +| `mnc` | Mobile Network Code. Range: 0–99. | +| `lac` | Location Area Code. Range: 1–65535. | +| `uarfcn` | UTRA Absolute Radio Frequency Channel Number. Range: 0–65535. | +| `psc` | Primary Scrambling Code. This parameter determines the primary scrambling code of the scanned cell. Range: 0–511. | +| `rssi` | In UMTS network, this value indicates received signal code power (RSCP), that is CPICH/PCCPCH.
RSSI = RSCP - 115. Unit: dBm. Range: -121 to -25 dBm. | + +* Descriptions of `LTE` network mode + +| Parameter | Description | +| ------ | ------------------------------------------------------------ | +| `flag` | Cell type. Range: 0–3. 0: Current serving cell. 1: Neighbour cell. 2: Intra-frequency neighbour cell. 3: Inter-frequency neighbour cell. | +| `cid` | Cell identity, also called E-UTRAN cell identifier (ECI) in LTE network. ECI = eNodeB ID × 256 + Cell ID. Range: 0x0000000–0xFFFFFFF (The cell identity is 28 bits). The first 20 bits indicate eNodeB ID. The last 8 bits indicate LTE Cell ID. | +| `mcc` | Mobile Country Code. Range: 0–999. | +| `mnc` | Mobile Network Code. Range: 0–99. | +| `pci` | Physical-layer cell identity. Range: 0–503. | +| `tac` | Tracking Area Code. Range: 0–65535. | +| `earfcn` | E-UTRA Absolute Radio Frequency Channel Number. Range: 0–65535. | +| `rssi` | In LTE network, RSSI indicates all received signal strength. Range: -140 to -44. Unit: dBm.
Note: All series modules cannot get RSSI currently but use RSRP, excluding BC25/BG95 series module.
RSRP indicates received effective signal strength. Range: -140 to -44. Unit: dBm. | +| `rsrq` |Reference signal receiving quality (RSRQ) of the LTE network. Range: -20 to -3.
Note: Theoretically, RSRQ ranges from -19.5 to -3. But due to the problem of calculation method, the supported RSRQ ranges from -20 to -3.
Currently, it is meaningful to get this parameter only for BC25/BG95/EC600E/EC800E series module. This parameter is meaningless for other modules.| + + + +>Note: This interface will block for 3–5 seconds when searching for cells. In areas without signals, the blocking time will be longer. +> +>BC32 series modules support only NB networks. + + + +**Example:** + +```python +>>> import net +>>> net.getCellInfo() +([], [], [(0, 232301375, 1120, 17, 378, 26909, 1850, -66, -8), (3, 110110494, 1120, 17, 10, 26909, 2452, -87, -17), (3, 94542859, 1120, 1, 465, 56848, 1650, -75, -10), +(3, 94472037, 1120, 1, 369, 56848, 3745, -84, -20)]) + +>>> net.getCellInfo() +([], [], [(0, 17104243, 460, 4, 121, 19472, 3688, -76, -15)]) +``` + + + +## Network Mode and Roaming Configuration + +### `net.getConfig` + +```python +net.getConfig() +``` + +This method gets the current network mode and roaming configuration. + +**Return Value:** + + `-1` - Failed execution + +A tuple containing the current preferred network mode and roaming enabling status - Successful execution + +* Network mode + +| Value | Network mode | | Value | Network mode | +| ----- | :------------------------- | ---- | ----- | ------------------------------------------------------------ | +| 0 | GSM | | 17 | UMTS_LTE (Dual-link) | +| 1 | UMTS | | 18 | GSM_UMTS_LTE (Dual-link) | +| 2 | GSM_UMTS (Automatic) | | 19 | CATM supported by BG95 series module. | +| 3 | GSM_UMTS (GSM prefer) | | 20 | GSM_CATM (GSM prefer) supported by BG95 series module. | +| 4 | GSM_UMTS (UMTS prefer) | | 21 | CATNB supported by BG95 series module. | +| 5 | LTE | | 22 | GSM_CATNB (GSM prefer) supported by BG95/BC32 series module. | +| 6 | GSM_LTE (Automatic) | | 23 | CATM_CATNB (CATM prefer) supported by BG95 series module. | +| 7 | GSM_LTE (GSM prefer) | | 24 | GSM_CATM_CATNB (GSM prefer) supported by BG95 series module. | +| 8 | GSM_LTE (LTE prefer) | | 25 | CATM_GSM (CATM prefer) supported by BG95 series module. | +| 9 | UMTS_LTE (Automatic) | | 26 | CATNB_GSM (CATNB prefer) supported by BG95/BC32 series module. | +| 10 | UMTS_LTE (UMTS prefer) | | 27 | CATNB_CATM (CATNB prefer) supported by BG95 series module. | +| 11 | UMTS_LTE (LTE prefer) | | 28 | GSM_CATNB_CATM (GSM prefer) supported by BG95 series module. | +| 12 | GSM_UMTS_LTE (Automatic) | | 29 | CATM_GSM_CATNB (CATM prefer) supported by BG95 series module. | +| 13 | GSM_UMTS_LTE (GSM prefer) | | 30 | CATM_CATNB_GSM (CATM prefer) supported by BG95 series module. | +| 14 | GSM_UMTS_LTE (UMTS prefer) | | 31 | CATNB_GSM_CATM (CATNB prefer) supported by BG95 series module. | +| 15 | GSM_UMTS_LTE (LTE prefer) | | 32 | CATNB_CATM_GSM (CATNB prefer) supported by BG95 series module. | +| 16 | GSM_LTE (Dual-link) | | 33 | CATNB_GSM (Enterprise) supported by BC32 series module. | + + + +>BC25 series module does not support this method. +> +>BG95-M1 series module only supports CAT-M network mode. +> +>BG95-M2 series module only supports two network modes: CAT-M and CATNB. +> +>BG95-M3/M8 series module supports three network modes: CAT-M, CATNB and GSM. +> +>BC32 series module configurations related to Enterprise standards need to be restarted to take effect. Changing the network format requires cfun=0. + + + +**Example:** + +```python +>>> import net +>>>net.getConfig () +(8, False) +``` + + + +### `net.setConfig` + +```python +net.setConfig(mode [, roaming]) +``` + +This method sets the network mode and roaming configuration. + +**Parameter:** + +* `mode` - Integer type. Network mode. See the above table of network modes for details. + +* `roaming` - Integer type. Roaming switch. Optional parameter (`0`: Disable, `1`: enable). + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + + + +>* roaming is an optional parameter, which can be omitted for unsupported module models. +>* BC25 series module does not support this method. +>* EC200U/EC600U/EG915U/EG912U series module does not support the configuration of roaming parameters and only supports network modes GSM, GSM_LTE (automatic) and GSM_LTE (LTE preferred). +>* EC600E/EC800E/EC800M series module only supports LTE network mode. +>* UC200A series module only supports 2G/3G network mode. +>* EC200A series modules are not saved after power failure. + + + +**Example:** + +```python +>>> import net +>>>net.setConfig(6) +0 + +>>>net.getConfig () +(6, False) +``` + + + +## Get Network Configuration Mode + +### `net.getNetMode` + +```python +net.getNetMode() +``` + +This method gets the network configuration mode. + +**Return Value:** + +`-1` - Failed execution + +A tuple `(selection_mode, mcc, mnc, act)` - Successful execution + +| Parameter | Type | Description | +| ---------------- | ------- | ---------------------------------------- | +| `selection_mode` | Integer | Method. 0 - Automatically. 1 - Manually. | +| `mcc` | String | Mobile Country Code. | +| `mnc` | String | Mobile Network Code. | +| `act` | Integer | ACT mode of the preferred network. | + +Enumeration values of `ACT` modes: + +| Value | ACT Mode | +| ----- |--------------------| +| 0 | GSM | +| 1 | COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E UTRAN CA | +| 10 | NONE | + +Enumeration values of `ACT` modes of BG95 series module: + +| Value | ACT Mode | +| ---- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | E_UTRAN_NBIOT | +| 11 | E_UTRAN_EMTC | +| 12 | NONE | + +**Example:** + +```python +>>> import net +>>> net.getNetMode() +(0, '460', '46', 7) +``` + + + +## Get Detailed Signal Strength + +### `net.getSignal` + +```python +net.getSignal([sinrEnable]) +``` + +This method gets the detailed signal strength. + +**Parameter:** + +* `sinrEnable` - Integer type. Optional parameter. Enable or disable to get SINR. + +| Value | Description | +|-----| ------------- | +| 0 | Disable to get SINR | +| 1 | Enable to get SINR | + +**Return Value:** + +`-1` - Failed execution + +A tuple containing `(GW, LTE)` - Successful execution + + `([rssi, bitErrorRate, rscp, ecno], [rssi, rsrp, rsrq, cqi, sinr])` + +* Descriptions of `GSM/WCDMA` : + +| Parameter | Description | +| -------------- | ------------------------------------------------------------ | +| `rssi` | In GSM and WCDMA network, this value indicates Rx level and describes the received signal strength. 99 indicates unknown or undetectable.
RSSI = RXLEV - 111. Range of RXLEV: 0–63. Unit: dBm. | +| `bitErrorRate` | Bit error rate. Range: 0–7. 99 indicates unknown or undetectable. | +| `rscp` | Receive Signal Channel Power. Range: -121 to -25 dBm. 255 indicates unknown or undetectable. | +| `ecno` | Pilot channel. Range: -24–0. 255 indicates unknown or undetectable. | + +* Descriptions of `LTE` : + +| Parameter | Description | +| --------- | ------------------------------------------------------------ | +| `rssi` | Received Signal Strength Indicator. Range: -140 to -44 dBm. 99 indicates unknown or undetectable. | +| `rsrp` | Reference Signal Receiving Power. Range: -140 to -44 dBm. 99 indicates unknown or undetectable. | +| `rsrq` | Reference Signal Receiving Quality. Range: -20 to -3 dB. The higher the value, the better the reference signal received quality. 255 indicates unknown or undetectable. | +| `cqi` | Channel Quality Indication. 255 indicates unknown or undetectable. | +| `sinr` | Signal to interference plus Noise Ratio. Range: -10–40 dB. 255 indicates unknown or undetectable. | + + + +>* `sinrEnable` is an optional parameter, which can be omitted for the unsupported modules. If you do not enter this parameter, `sinr` won't be got by default. +>* All Quectel series modules support to get `sinr`, excluding BC25/BC32 series module. +>* BC32 series modules support only NB networks. + + + +**Example:** + +```python +>>> import net +>>>net.getSignal() +([99, 99, 255, 255], [-51, -76, -5, 255]) +>>>net.getSignal(0) +([99, 99, 255, 255], [-51, -76, -5, 255]) +>>>net.getSignal(1) +([99, 99, 255, 255], [-51, -76, -5, 255, 18]) +``` + + + +## Get Current Base Station Time + +### `net.nitzTime` + +```python +net.nitzTime() +``` + +This method gets the current base station time, which is the time issued by the base station when the module boots and registers on the network successfully. + +**Return Value:** + +`-1` - Failed execution + +A tuple `(date, abs_time, leap_sec)` containing the base station time and corresponding timestamps and leap seconds (0 indicates that the current base station time is unavailable.) - Successful execution + +| Parameter | Type | Description | +| ---------- | ------- | ------------------------------------------------------------ | +| `date` | String | Base time. The part of the time zone varies with module models. See the example below for details.
Please use `setTimeZone(offset)` and `getTimeZone()` of `utime` feature if you need to set and get the time zone.
The unit of these two interfaces is hour for different modules. See [`utime`](../QuecPython标准库/utime.md) for details. | +| `abs_time` | Integer | Absolute seconds of the base station time. | +| `leap_sec` | Integer | Leap seconds. | + +**Example:** + +```python +>>> import net +>>> net.nitzTime() +# For return values of EC100Y/EC200N/EC600N/EC600S/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EC200A series module, the unit of the time zone is hour. 8 indicates UTC + 08:00. +('21/10/26 06:08:03 8 0', 1635228483, 0) +# For return values of BC25/BC32/EC600E/EC800E/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G series module, the unit of the time zone is 15 minutes. +32 indicates UTC + 08:00. +('20/11/26 02:13:25 +32 0', 1606356805, 0) +# For return values of BG95 series module, there is no time zone. +('23/02/14 02:25:13', 1676312713, 0) +``` + + + +## Get Operator Information + +### `net.operatorName` + +```python +net.operatorName() +``` + +This method gets the operator information of the current network registration. + +**Return Value:** + + `-1` - Failed execution + +A tuple `(long_eons, short_eons, mcc, mnc)` containing the operator information of the current network registration - Successful execution + +| Parameter | Type | Description | +| ------------ | ------ | ----------------------------- | +| `long_eons` | String | Operator's full name. | +| `short_eons` | String | Operator's name abbreviation. | +| `mcc` | String | Mobile Country Code | +| `mnc` | String | Mobile Network Code | + +**Example:** + +```python +>>> import net +>>> net.operatorName() +('CHN-UNICOM', 'UNICOM', '460', '01') +``` + + + +## Get Network Registration Information + +### `net.getState` + +```python +net.getState() +``` + +This interface gets the network registration information. + +**Return Value:** + + `-1` - Failed execution + +A tuple `([voice_state, voice_lac, voice_cid, voice_rat, voice_reject_cause, voice_psc], [data_state, data_lac, data_cid, data_rat, data_reject_cause, data_psc])` containing the information of the phone and network registration - Successful execution + +`voice_state, voice_lac, voice_cid, voice_rat, voice_reject_cause, voice_psc` - Information of the phone registration + +`data_state, data_lac, data_cid, data_rat, data_reject_cause, data_psc` - Information of the current network registration + +* Parameter: + +| Parameter | Description | +| -------------- | ------------------------------------------------------------ | +| `state` | Network registration status. See the table below for details. | +| `lac` | Location Area Code. Range: 1–65535. | +| `cid` | Cell ID. Range: 0x00000000–0x0FFFFFFF. See return values above of `net.getCellInfo()` for details. | +| ``rat`` | Access technology. See the following table for details. | +| `reject_cause` | Reasons for registration rejection. For EC200U/EC600U/EG915U/BC25 series module, this parameter is necessary and it is not an optional parameter. | +| `psc` | Primary scrambling code. For EC200U/EC600U/EG915U/BC25 series module, this parameter is necessary and it is not a valid parameter. | + +* Enumeration values of `state`: + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| 0 | Not registered and MT is not searching for an operator again. | +| 1 | Registration completed. Local network. | +| 2 | Not registered but MT is searching for an operator. | +| 3 | Registration denied. | +| 4 | Unknown. | +| 5 | Registration completed. Roaming network. | +| 6 | Registered on "SMS only" local network (inapplicable). | +| 7 | Registered on "SMS only" roaming network (inapplicable). | +| 8 | Emergency attachment is limited to emergency bearer service. | +| 9 | Registered on "Low priority of CSFB" local network (inapplicable). | +| 10 | Registered on "Low priority of CSFB" roaming network (inapplicable). | +| 11 | Emergency bearer service only. | + +* `access technology` + +| Value | Description | +| ----- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | NONE | + + + +> For BG95 series module: + +| Value | Description | +| ----- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | E_UTRAN_NBIOT | +| 11 | E_UTRAN_EMTC | +| 12 | NONE | + +**Example:** + +```python +>>> import net +>>> net.getState() +([11, 26909, 232301323, 7, 0, 466], [0, 26909, 232301323, 7, 0, 0]) +``` + + + +## Get Cell ID + +### `net.getCi` + +```python +net.getCi() +``` + +This method gets neighbour cells. The result gotten by this interface is the collection of cell IDs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + + An array `[id, ……, id]` containing cell IDs. List type. The number of array members is not fixed, and different locations, signal strength, and other factors may lead to different results. - Successful execution + + `-1` - Failed execution + +**Example:** + +```python +>>> net.getCi() +[14071232, 0] +``` + + + +### `net.getServingCi` + +```python +net.getServingCi() +``` + +This method gets the serving cell ID. The result gotten by this interface is the collection of cell IDs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + +Serving cell ID - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.getServingCi() +94938399 +``` + + + +## Get MNC of Cell + +### `net.getMnc` + +```python +net.getMnc() +``` + +This method gets MNC of the neighbour cell ID. The result gotten by this interface is the collection of MNCs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + + An array `[mnc, ……, mnc]` containing `mnc` of cells. List type. The number of array members is not fixed, and different locations, signal strength, and other factors may lead to different results. - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.getMnc() +[0, 0] +``` + + + +### `net.getServingMnc` + +```python +net.getServingMnc() +``` + +This method gets MNC of the serving cell. The result gotten by this interface is the collection of MNCs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + +`mnc` of the serving cell - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.getServingMnc() +1 +``` + + + +## Get MCC of Cell + +### `net.getMcc` + +```python +net.getMcc() +``` + +This method gets MCCs of the neighbour cells. The result gotten by this interface is the collection of MCCs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + +An array `[mnc, ……, mnc]` containing `mnc` of cells. List type. The number of array members is not fixed, and different locations, signal strength, and other factors may lead to different results. - Successful execution + +`-1` - Failed execution + + + +> For EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95/EG915N series module, the value needs to be converted to hexadecimal. For example, Decimal number 1120 is 0x460 in hexadecimal in which 460 indicates MCC460. For other series modules, this value is in decimal format. + + + +**Example:** + +```python +>>> import net +>>> net.getMcc() +[1120, 0] +``` + + + +### `net.getServingMcc` + +```python +net.getServingMcc() +``` + +This method gets MCC of the serving cell. The result gotten by this interface is the collection of MCCs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + + `mcc` of the serving cell - Successful execution + +`-1` - Failed execution + + + +> For EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95/EG915N series module, the value needs to be converted to hexadecimal. For example, Decimal number 1120 is 0x460 in hexadecimal in which 460 indicates MCC460. For other series modules, this value is in decimal format. + + + +**Example:** + +```python +>>> import net +>>> net.getServingMcc() +1120 +``` + + + +## Get LAC of Cell + +### `net.getLac` + +```python +net.getLac() +``` + +This method gets LACs of the neighbour cells. The result gotten by this interface is the collection of LACs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + +An array `[lac, ……, lac]` containing `lac` of cells. List type. The number of array members is not fixed, and different locations, signal strength, and other factors may lead to different results. - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.getLac() +[21771, 0] +``` + + + +### `net.getServingLac` + +```python +net.getServingLac() +``` + +This method gets LACs of the serving cells. The result gotten by this interface is the collection of LACs in the result gotten by *net.getCellInfo()*. + +**Return Value:** + +`lac` of the serving cell - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.getServingLac() +56848 +``` + + + +## Work Mode Configuration + +### `net.getModemFun` + +```python +net.getModemFun() +``` + +This method gets the current work mode. + +**Return Value:** + +The current work mode of the module - Successful execution + +`-1` - Failed execution + +| Mode | Description | +| --- | ---------- | +| 0 | Minimum functionality. In this mode, the entire radio frequency network protocol stack is completely closed, and the power supply to the SIM card is stopped. | +| 1 | Full functionality (default). In this mode, the device can send and receive RF signals. | +| 4 | Disable UE from both transmitting and receiving RF signals. | + +> The BC32 series does not support mode 4. + +**Example:** + +```python +>>> import net +>>> net.getModemFun() +1 +``` + + + +### `net.setModemFun` + +```python +net.setModemFun(fun [, rst]) +``` + +This method sets the current work mode of the module. + +**Parameter:** + +* `fun` - Integer type. Work mode of the module. +| Mode | Description | +| --- | ---------- | +| 0 | Minimum functionality. In this mode, the entire radio frequency network protocol stack is completely closed, and the power supply to the SIM card is stopped. | +| 1 | Full functionality (default). In this mode, the device can send and receive RF signals. | +| 4 | Disable UE from both transmitting and receiving RF signals. | + +* `rst` - Integer type. Reboot flag. Optional parameter. +| Value | Description | +| --- | ---------- | +| 0 | Do not reboot the module after setting the current work mode (default). | +| 1 | Reboot the module after setting the current work mode. | + +**Return Value:** + + `0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> import net +>>> net.setModemFun(4) +0 +``` + + + +## Set and Get Band + +### `net.setBand` + +```python +net.setBand(netRat, gsmBand, bandTuple) +``` +This method sets the required band, that is, lock the band specified by the user if the module supports this method. + +* Comparison Table of Band Values + +| Network Mode | Band Value | +| --------------- | ------------------------------------------------------------ | +| EGPRS(GSM) | EGSM900 - 0x1
DCS1800 - 0x2
GSM850 - 0x4
PCS1900 - 0x8 | +| LTE/eMTC/NB-IoT | BAND1 - 0x1
BAND2 - 0x2
BAND3 - 0x4
BAND4 - 0x8
BAND5 - 0x10
BAND7 - 0x40
BAND8 - 0x80
BAND12 - 0x800
BAND13 - 0x1000
BAND18 - 0x20000
BAND19 - 0x40000
BAND20 - 0x80000
BAND25 - 0x1000000
BAND26 - 0x2000000
BAND27 - 0x4000000
BAND28 - 0x8000000
BAND31 - 0x40000000
BAND66 - 0x20000000000000000
BAND71 - 0x400000000000000000
BAND72 - 0x800000000000000000
BAND73 - 0x1000000000000000000
BAND85 - 0x1000000000000000000000
| + +**Parameter:** + +* `netRat` - Integer type. Network mode. It indicates the kind of network mode whose band is to be set. +| RAT Value | Description | +| --------- | -------------- | +| 0 | GSM network | +| 1 | LTE network | +| 2 | Cat M network | +| 3 | NB-IoT network | + +* `gsmBand` - Integer type. The `band` value of `GSM` network. See the `band` value comparison table above. + +* `bandtuple` - The `band` value of other network modes excluding `GSM` network and it is a tuple containing 4 elements `(band_hh, band_hl, band_lh, band_ll)`, each of which cannot exceed 4 bytes. + + `band_hh` - The first 4 bytes of the first 8 bytes of the band value. + `band_hl` - The last 4 bytes of the first 8 bytes of the band value. + `band_lh` - The first 4 bytes of the last 8 bytes of the band value. + `band_ll` - The last 4 bytes of the last 8 bytes of the band value. + If you want to set the `band` value to the `band_value` : + `band_hh = (band_value & 0xFFFFFFFF000000000000000000000000) >> 96` + `band_hl = (band_value & 0x00000000FFFFFFFF0000000000000000) >> 64` + `band_lh = (band_value & 0x0000000000000000FFFFFFFF00000000) >> 32` + `band_ll = (band_value & 0x000000000000000000000000FFFFFFFF)` + +**Return Value:** + + `0` - Successful execution + +`-1` - Failed execution + + + +>* Currently, BG95/EG912N/EG915N/EC600N/EC800N module supports this method. +>* BG95 series module does not support the `band` of LTE network. +>* EG912N/EG915N/EC600N/EC800N module only supports the band of GSM network and LTE network. + + + +**Example:** + +```python +import net +import utime + +''' +You can directly use the following two interfaces to set and get the band. +''' +def set_band(net_rat, band_value): + if net_rat == 0: + retval = net.setBand(0, band_value, (0, 0, 0, 0)) + else: + band_hh = (band_value & 0xFFFFFFFF000000000000000000000000) >> 96 + band_hl = (band_value & 0x00000000FFFFFFFF0000000000000000) >> 64 + band_lh = (band_value & 0x0000000000000000FFFFFFFF00000000) >> 32 + band_ll = (band_value & 0x000000000000000000000000FFFFFFFF) + retval = net.setBand(net_rat, 0, (band_hh, band_hl, band_lh, band_ll)) + return retval + + +def get_band(net_rat): + return net.getBand(net_rat) + +#====================================================================================================== + +''' +Sets the band of GSM network to 0xa, that is, DCS1800 + PCS1900 +0xa = 0x2(DCS1800) + 0x8(PCS1900) +''' +def set_gsm_band_example(): + print('Set GSM band to 0xa example:') + gsm_band = get_band(0) + print('GSM band value before setting:{}'.format(gsm_band)) + ret = set_band(0, 0xa) + if ret == 0: + print('Set GSM band successfully.') + else: + print('Set GSM band failed.') + utime.sleep(1) # It takes time to set the band. You can wait for a period of time before getting new results. + gsm_band = get_band(0) + print('GSM band value after setting:{}'.format(gsm_band)) + return ret + + +''' +Sets the band of eMTC network to 0x15, that is BAND1 + BAND3 + BAND5 +0x15 = 0x1(BAND1) + 0x4(BAND3) + 0x10(BAND5) +''' +def set_camt_band_example(): + print('Set CATM band to 0x15 example:') + catm_band = get_band(2) + print('CATM band value before setting:{}'.format(catm_band)) + ret = set_band(2, 0x15) + if ret == 0: + print('Set CATM band successfully.') + else: + print('Set CATM band failed.') + utime.sleep(1) # It takes time to set the band. You can wait for a period of time before getting new results. + catm_band = get_band(2) + print('CATM band value after setting:{}'.format(catm_band)) + return ret + + +''' +Sets the band of NB-IoT network to 0x1000800000000000020011, that is BAND1 + BAND5 + BAND18 + BAND71 + BAND85 +0x1000400000000000020011 = 0x1 + 0x10 + 0x20000 + 0x400000000000000000 + 0x1000000000000000000000 +''' +def set_nb_band_example(): + print('Set NB band to 0x1000400000000000020011 example:') + nb_band = get_band(3) + print('NB band value before setting:{}'.format(nb_band)) + ret = set_band(3, 0x1000400000000000020011) + if ret == 0: + print('Set NB band successfully.') + else: + print('Set NB band failed.') + utime.sleep(1) # It takes time to set the band. You can wait for a period of time before getting new results. + nb_band = get_band(3) + print('NB band value after setting:{}'.format(nb_band)) + return ret + + +def main(): + set_gsm_band_example() + utime.sleep(1) + set_camt_band_example() + utime.sleep(1) + set_nb_band_example() + + +if __name__ == '__main__': + main() + + +#=================================================================================================== +# Running results +Set GSM band to 0xa example: +GSM band value before setting:0xf +Set GSM band successfully. +GSM band value after setting:0xa + +Set CATM band to 0x15 example: +CATM band value before setting:0x10000200000000090e189f +Set CATM band successfully. +CATM band value after setting:0x15 + +Set NB band to 0x1000400000000000020011 example: +NB band value before setting:0x10004200000000090e189f +Set NB band successfully. +NB band value after setting:0x1000400000000000020011 + +``` + + + +### `net.getBand` + +```python +net.getBand(netRat) +``` + +This method gets the band value in the current network mode. + +**Parameter:** + +* `netRat` - Integer type. Network mode. It indicates that the `band` of which network mode you want to set. +| RAT Value | Description | +| --------- | -------------- | +| 0 | GSM network | +| 1 | LTE network | +| 2 | Cat M network | +| 3 | NB-IoT network | + +**Return Value:** + +Band value in hexadecimal. + + + +>* Currently, BG95/EG912N/EG915N/EC600N/EC800N module supports this method. +>* BG95 series module does not support the `band` of LTE network. +>* EG912N/EG915N/EC600N/EC800N module only supports the band of GSM network and LTE network. + + + +**Example:** + +```python +>>> import net +>>> net.getBand(2) +'0x10000200000000090e189f' # The band is in string type. If you need the value in integer type, int(data) can be called for changing the type. +``` + + + +### `net.bandRst` + +```python +net.bandRst() +``` + +This method restores the initial set value of the band. + +**Return Value:** + + `0` - Successful execution + +`-1` - Failed execution + + + +>Note: EG912N/EG915N/EC600N/EC800N series module supports this method. + + + +**Example:** + +```python +''' +Sets to other bands first, calls this interface and checks whether it is successfully restored to the initial value. +Initial set value of EG912N-ENAA series module: gsm_band:0x3(EGSM900/DCS1800 ) lte_band:0x8000000000480800D5(B1/B3/B5/B7/B8/B20/B28/B31/B72 ) +''' +>>> import net +>>> net.bandRst() +0 +``` \ No newline at end of file diff --git a/docs/API_reference/en/iotlib/sim.md b/docs/API_reference/en/iotlib/sim.md new file mode 100644 index 0000000000000000000000000000000000000000..dbd493563dfe61156f286d5cc86ff1554e8ffe50 --- /dev/null +++ b/docs/API_reference/en/iotlib/sim.md @@ -0,0 +1,703 @@ +# sim - SIM Card Related Features + +This feature provides you with the SIM Card APIs, such as the methods of getting SIM card status, ICCID, IMSI and the phone number, etc. + +> To obtain the SIM card ICCID and IMSI, the SIM card status needs to be in the ready state (which can be queried through sim. getStatus()).The PIN code, PUK code, and other related passwords involved in this module should be obtained based on the information provided by the network operator. If you are unsure of the password, please confirm with the network operator first + + + +## Access Generic SIM Features + +### `sim.genericAccess` + +``` +sim.genericAccess(simId, cmd) +``` + +Accesses generic SIM features to send CSIM commands and interact with SIM cards. + +**Parameter** + +* `simId` - Integer type. SIM card slot ID. 0 - SIM card 0. 1- SIM card 1. Only 0 is supported now. +* `cmd` - String type. The command passed by the mobile terminal to the SIM in the format described in GSM 51.011. + +**Return Value** + +A tuple `(len,data)` - Successful execution + +`len` - Integer type. Length of `data`. + +`data` - String type. The data content returned. + +`-1` - Failed execution,Integer type. + + + +> Only EG912N/EG915N series module supports this method. + + + +**Example** + +```python +>>> import sim +>>> sim.genericAccess(0,'80F2000016') +(48, '623E8202782183027FF08410A0000000871002FF86FF9000') +``` + + + +## Get SIM Card Information + +### `sim.getImsi` + +```python +sim.getImsi() +``` + +Gets the IMSI number of the SIM card. + +**Return Value** + +`IMSI` -Successful execution,String type. + +`-1` - Failed execution,Integer type. + +**Example** + +```python +>>> import sim +>>> sim.getImsi() +'460105466870381' +``` + + + +### `sim.getIccid` + +```python +sim.getIccid() +``` + +Gets the ICCID number of the SIM card. + +**Return Value** + +`ICCID` - Successful execution,String type. + +`-1` - Failed execution,Integer type. + +**Example** + +```python +>>> import sim +>>> sim.getIccid() +'89860390845513443049' +``` + + + +### `sim.getPhoneNumber` + +```python +sim.getPhoneNumber() +``` + +Gets the phone number of the SIM card. The phone number of the SIM card must be written into the module first. + +**Return Value** + +`Phone number` - Successful execution,String type. + +`-1` - Failed execution,Integer type. + + + +**Example** + +```python +>>> import sim +>>> sim.getPhoneNumber() +'+8618166328752' +``` + + + +## Get SIM Card Status + +### `sim.getStatus` + +```python +sim.getStatus() +``` + +Gets the current SIM card status. + +**Return Value** + +Integer type. SIM card status codes, as described in details below. + +| Code | Description | +| ---- | ------------------------------------------------------------ | +| -1 | API execution exception. | +| 0 | The SIM card does not exist/has been removed. | +| 1 | The SIM card is ready. | +| 2 | The SIM card has been blocked and waiting for CHV1 password. | +| 3 | The SIM card has been blocked and needs to be unblocked with CHV1 password. | +| 4 | The SIM card has been blocked due to failed SIM/USIM personalized check. | +| 5 | The SIM card is blocked due to an incorrect PCK. An MEP unblocking password is required. | +| 6 | Expecting key for hidden phone book entries | +| 7 | Expecting code to unblock the hidden key | +| 8 | The SIM card has been blocked and waiting for CHV2 password. | +| 9 | The SIM card has been blocked and needs to be unblocked with CHV2 password. | +| 10 | The SIM card has been blocked due to failed network personalization check. | +| 11 | The SIM card is blocked due to an incorrect NCK. An MEP unblocking password is required. | +| 12 | The SIM card has been blocked due to failed personalization check of network lock. | +| 13 | The SIM card is blocked due to an incorrect NSCK. An MEP unblocking password is required. | +| 14 | The SIM card has been blocked due to failed personalization check of the service provider. | +| 15 | The SIM card is blocked due to an incorrect SPCK. An MEP unblocking password is required. | +| 16 | The SIM card has been blocked due to failed enterprise personalization check. | +| 17 | The SIM card is blocked due to an incorrect CCK. An MEP unblocking password is required. | +| 18 | The SIM card is being initialized and waiting for completion. | +| 19 | The SIM card is blocked for the following six reasons.
1) Use of CHV1 is blocked.
2) Use of CHV2 is blocked.
3) Use of the universal PIN is blocked.
4) Use of code to unblock the CHV1 is blocked.
5) Use of code to unblock the CHV2 is blocked.
6) Use of code to unblock the universal PIN is blocked. | +| 20 | The SIM card is invalid. | +| 21 | Unknown status. | + + + +## PIN Code Verification + +### `sim.enablePin` + +```python +sim.enablePin(pin) +``` + +Enables PIN verification. Once this method is called to enable the PIN verification, you need to enter the correct PIN code for verification. Only when the PIN code is verified successfully will the SIM card can be used normally. Please note that you have at most 3 attempts. The SIM card will be locked and must be unblocked with the PUK code after three consecutive failures. + +**Parameter** + +- `pin` - String type. PIN code. Default value: ‘1234’. The value contains a maximum of 15 digits. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +> EC600K/EC800K/EC600M/EC800M part series module does not support PIN function: such as CC/LC/GC suffix series modules. + +**Example** + +```python +>>> sim.enablePin("1234") +0 +``` + + + +### `sim.disablePin` + +```python +sim.disablePin(pin) +``` + +Disables PIN code verification. + +**Parameter** + +- `pin` - String type. PIN code. Default value: ‘1234’. The value contains a maximum of 15 digits. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +> EC600K/EC800K/EC600M/EC800M part series module does not support PIN function: such as CC/LC/GC suffix series modules. + +**Example** + +```python +>>> import sim +>>> sim.disablePin("1234") +0 +``` + + + +### `sim.verifyPin` + +```python +sim.verifyPin(pin) +``` + +Verifies PIN code. After the PIN code verification is enabled, if you need to use the SIM card, you can call this method to temporarily make the SIM card work normally, and this method needs to be called again for verification next time when the module is powered on (Or you can call *sim.disablePin(pin)* to disable the PIN verification, then the PIN verification will not be required when the module is powered on again). + +**Parameter** + +- `pin` - String type. PIN code. Default value: ‘1234’. Length: up to 15 digits. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +> EC600K/EC800K/EC600M/EC800M part series module does not support PIN function: such as CC/LC/GC suffix series modules. + +**Example** + +```python +>>> import sim +>>> sim.verifyPin("1234") +0 +``` + + + +### `sim.changePin` + +```python +sim.changePin(oldPin, newPin) +``` + +Changes the PIN code + +**Parameter** + +- `oldPin` - String type. The old PIN code, with a maximum length of 15 digits. +- `newPin` - String type. The new PIN code, with a maximum length of 15 digits. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +> EC600K/EC800K/EC600M/EC800M part series module does not support PIN function: such as CC/LC/GC suffix series modules. + +**Example** + +```python +>>> import sim +>>> sim.changePin("1234", "4321") +0 +``` + + + +## Unblock SIM Card + +### `sim.unblockPin` + +```python +sim.unblockPin(puk, newPin) +``` + +Unblocks the SIM card. When you enter incorrect PIN codes three times, you need to enter the PUK code to unblock the SIM card. If incorrect PUK codes are entered ten times, the SIM card will be permanently locked and automatically scrapped. + +**Parameter** + +- `puk` - String type. PUK code. Length: 8 to 15 digits. +- `newPin` - String type. New PIN code. Length: up to 15 digits. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +> EC600K/EC800K/EC600M/EC800M part series module does not support PIN function: such as CC/LC/GC suffix series modules. + +**Example** + +```python +>>> import sim +>>> sim.unblockPin("12345678", "0000") +0 +``` + + + +## Phone Book + +### `sim.readPhonebook` + +```python +sim.readPhonebook(storage, start, end, username) +``` + +Reads the phone book to get one or more phone number records from the phone book at the specified storage location. + +**Parameter** + +- `storage` - Integer type. Storage location of the phone numbers, as described below. + +| Value | Description | +| ----- | ----------- | +| 0 | DC | +| 1 | EN | +| 2 | FD | +| 3 | LD | +| 4 | MC | +| 5 | ME | +| 6 | MT | +| 7 | ON | +| 8 | RC | +| 9 | SM | +| 10 | AP | +| 11 | MBDN | +| 12 | MN | +| 13 | SDN | +| 14 | ICI | +| 15 | OCI | + +- `start` - Integer type. The start number of the phone number record to be read. `start` equaling 0 indicates that no number is used to obtain the phone number. `start` must be less than or equal to `end`. +- `end` - Integer type. The end number of the phone number record to be read. The condition that must be met: `end - start <= 20`. +- `username` - String type. The username of a phone number. This parameter is valid when `start` equals 0. Chinese characters are not supported currently. Length: up to 30 bytes. + +**Return Value** + +A tuple `(record_number, [(index, username, phone_number), ... , (index, username, phone_number)])` - Successful execution + +The parameters are described below. + +| Parameter | Type | Description | +| --------------- | ------- | ---------------------------------------- | +| `record_number` | Integer | The number of phone number records read. | +| `index` | Integer | Index of the number in the phone book. | +| `username` | String | Username of the phone number. | +| `phone_number` | String | Phone number. | + +`-1` - Failed execution,Integer type. + + + +>- EC200AAU_HA/EC200AEU_HA/EG912NEN_AA/EG915NEU_AG modules supports this method. +> +>- When you match a phone number record by username, you do not need to enter a full word. As long as there is an existing record in the phone book whose name starts with the username, the name will be matched with the phone number. + + + +**Example** + +```python +>>> import sim +>>> sim.readPhonebook(9, 1, 4, "") +(4,[(1,'Tom','15544272539'),(2,'Pony','15544272539'),(3,'Jay','18144786859'),(4,'Pondy','15544282538')]) +>>> sim.readPhonebook(9, 0, 0, "Tom") +(1, [(1, 'Tom', '18144786859')]) +>>> sim.readPhonebook(9, 0, 0, "Pony") +(1, [(2, 'Pony', '17744444444')]) +>>> sim.readPhonebook(9, 0, 0, "Pon") #Note: Any name that contains'pon' will be matched. +(2, [(2, 'Pony', '17744444444'),(4,'Pondy','15544282538')]) +``` + + + +### `sim.writePhonebook` + +```python +sim.writePhonebook(storage, index, username, number) +``` + +Writes phone book, that is, write a phone record to the specified storage location. + +**Parameter** + +- `storage` - Integer type. Storage location of the phone numbers. For details, see `storage` of `sim.readPhonebook`. + +- `index` - Integer type. Index of the number in the phone book. Range: `1 – 500`. +- `username` - String type. The username of a phone number. Chinese characters are not supported currently. Length: up to 30 bytes. +- `number` - String type. Phone number. Length: up to 20 bytes. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1`- Failed execution,Integer type. + + + +> EC200AAU_HA/EC200AEU_HA/EG912NEN_AA/EG915NEU_AG modules supports this method. + + + +**Example** + +```python +>>> import sim +>>> sim.writePhonebook(9, 1, 'Tom', '18144786859') +0 +``` + + + +## Hot Swap + +### `sim.setSimDet` + +```python +sim.setSimDet(switch, triggerLevel) +``` + +Sets the hot-swap-related features of the SIM card. + +**Parameter** + +- `switch` - Integer type. Enable or disable the hot swap feature of the SIM card. + + `0` - Disable + + `1` - Enable + +- `triggerLevel` - Integer type. This parameter is set according to the actual level of the SIM card. If the present level is high when the SIM card is inserted, this parameter should be set to 1. If the present level is low, this parameter should be set to 0. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +> The EG912N/EG915N/EC200A series modules support SIM card hot-swapping. Configurations take effect immediately and the related settings have power-off preservation. +> +> The EC200U/EG912U/EG915U series modules support SIM card hot-swapping. Configurations take effect immediately, and the related settings have power-off preservation. (Firmware versions after August 23, 2023, support power-off preservation, while earlier versions do not.) +> +> The BG95M1/BG95M2/BG95M3/BG95M6/BG95M8 series modules support SIM card hot-swapping. Configurations require a restart to take effect, and they support the power-off preservation feature. +> +> BG600LM3_LA/BG95M9 does not support this function. + + + +**Example** + +```python +>>> import sim +>>> sim.setSimDet(1, 0) +0 +``` + + + +### `sim.getSimDet` + +```python +sim.getSimDet() +``` + +Gets the hot-swap-related settings of the SIM card. + +**Return Value** + +A tuple `(detenable, insertlevel)` - Successful execution + +The parameters are described below. + +| Parameter | Type | Description | +| ------------- | ------- | ------------------------------------------------------------ | +| `detenable` | Integer | Enable or disable the hot swap feature of the SIM card. 0 - Disable; 1 - Enable. | +| `insertlevel` | Integer | High level or low level (0/1). | + +`-1` - Failed execution,Integer type. + + + +>The EG912N/EG915N/EC200A series modules support SIM card hot-swapping. Configurations take effect immediately and the related settings have power-off preservation. +> +>The EC200U/EG912U/EG915U series modules support SIM card hot-swapping. Configurations take effect immediately, and the related settings have power-off preservation. (Firmware versions after August 23, 2023, support power-off preservation, while earlier versions do not.) +> +>The BG95M1/BG95M2/BG95M3/BG95M6/BG95M8 series modules support SIM card hot-swapping. Configurations require a restart to take effect, and they support the power-off preservation feature. +> +>BG600LM3_LA/BG95M9 does not support this function. + + + +**Example** + +```python +>>> import sim +>>> sim.getSimDet() +(1, 0) +``` + + + +## Switch SIM Card + +### `sim.getCurSimid` + +```python +sim.getCurSimid() +``` + +Gets the SIM card slot ID of the current SIM card. + +**Return Value** + +`simId` - Successful execution + +`0` - `SIM1`,Integer type. + +`1` - `SIM2,Integer ` type. + +`-1` - Failed execution,Integer type. + + + +>EC800GCN_LD/EG912UGL support this method. + + + +**Example** + +```python +>>> import sim +>>> sim.getCurSimid() #Gets the current SIM card ID. 0 indicates SIM card 1. +0 +``` + + + +### `sim.switchCard` + +```python +sim.switchCard(simId) +``` + +This method is used to switch SIM cards between SIM cards. + +**Parameter** + +- `simId` - Integer type. SIM card slot ID. + + `0` - `SIM1` + + `1` - `SIM2` + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +>EC800GCN_LD/EG912UGL support this method. + + + +**Example** + +```python +>>> import sim +>>> sim.getCurSimid() #Gets the current SIM card ID. 0 indicates the current SIM card is SIM 1. +0 +>>> sim.switchCard(1) #Switches to SIM 2. +0 +>>> sim.getCurSimid() #Gets the current SIM card ID. 1 indicates the current SIM card is SIM 2. +1 +``` + + + +## Register Callback Function + +### `sim.setCallback` + +```python +sim.setCallback(usrFun) +``` + +Registers the callback function of hot swap features. When the hot-swap feature is enabled, the callback function registered by this method will be called when the SIM card is inserted or removed. + +**Parameter** + +* `usrFun` - Callback function name. The callback function format and parameters are described below. + +```python +def usrFun(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| `args` | Integer | Current status of The SIM card.
`1` - The SIM card is inserted.
`2` - The SIM card is removed. | + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +> The EG912N/EC200A series modules support SIM card hot-swapping. Configurations take effect immediately and the related settings have power-off preservation. +> +> The EC200U/EG912U/EG915U series modules support SIM card hot-swapping. Configurations take effect immediately, and the related settings have power-off preservation. (Firmware versions after August 23, 2023, support power-off preservation, while earlier versions do not.) +> +> The BG95M1/BG95M3/BG95M6/BG95M8 series modules support SIM card hot-swapping. Configurations require a restart to take effect, and they support the power-off preservation feature. +> +> BG600LM3_LA/BG95M9 does not support this function. + + + +**Example** + +```python +import sim + +def usrCallback(args): + simstates = args + print('sim states:{}'.format(simstates)) + +sim.setCallback(usrCallback) +``` + + + +### `sim.setSwitchcardCallback` + +```python +sim.setSwitchcardCallback(usrFun) +``` + +Registers the callback function of SIM card switch status to respond to the SIM card switch operation. + +**Parameter** + +* `usrFun` - Callback function name. The callback function format and parameters are described below. + +```python +def usrFun(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| args | Integer | The result of SIM switch.
`7` - Successful switch
`8` - Failed switch | + +**Return Value** + +`0` - Successful execution,Integer type. +`-1` - Failed execution,Integer type. + + + +> now not support this method. + + + +**Example** + +```python +import sim + +def usrCallback(args): + switchcard_state = args + print('sim switchcard states:{}'.format(switchcard_state)) + +sim.setSwitchcardCallback(usrCallback) +``` diff --git a/docs/API_reference/en/iotlib/sms.md b/docs/API_reference/en/iotlib/sms.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc6b5cd8196b7ddc3194f6af1202b238276cae7 --- /dev/null +++ b/docs/API_reference/en/iotlib/sms.md @@ -0,0 +1,509 @@ +# sms - SMS Related Feature + +This feature provides methods of reading, sending and deleting SMS. + + + +## Send SMS + +### `sms.sendTextMsg` + +``` +sms.sendTextMsg(phoneNumber, msg, codeMode) +``` + +Sends a text message (Empty messages are not supported). + +**Parameter** + +* `phoneNumber` - String type. Phone number of the recipient. Length: up to 20 bytes. +* `msg` - String type. The message to be sent. Length of a single message: up to 140 bytes. +* `codeMode` - String type. SMS encoding mode. + +| Value | Description | +| -------- | ---------------------------------------- | +| `'GSM'` | GSM 7-bit, used for English SMS. | +| `'UCS2'` | UCS-2, used for Chinese and English SMS. | + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +> Only the following series modules support long messages. +> +> EG912N/EG915N/EC200A series SMS content UCS2 encoding supports up to 420 bytes, and GSM encoding supports up to 960 bytes in length. +> +> The EC200U/EG912U/EG915U/BG95 series SMS content supports UCS2 encoding up to 280 bytes, while GSM encoding supports a maximum SMS length of 640 bytes. +> +> The UCS2 encoding of other series of SMS content supports a maximum of 70 bytes, while the GSM encoding supports a maximum of 160 bytes of SMS length. + + + +**Example** + +```python +# -*- coding: UTF-8 -*- +import sms + +sms.sendTextMsg('18158626517', '这是一条中文测试短信!', 'UCS2') +sms.sendTextMsg('18158626517', 'Hello, world.', 'GSM') +sms.sendTextMsg('18158626517', '这是一条夹杂中文与英文的测试短信,hello world!', 'UCS2') +``` + + + +### `sms.sendPduMsg` + +``` +sms.sendPduMsg(phoneNumber, msg, codeMode) +``` + +Sends an SMS message in PDU mode (Empty messages are not supported). + +**Parameter** + +* `phoneNumber` - String type. Phone number of the recipient. Length: up to 20 bytes. +* `msg` - String type. The message to be sent. Length of a single message: up to 140 bytes. +* `codeMode` - String type. SMS encoding mode. + +| Value | Description | +| -------- | ---------------------------------------- | +| `'GSM'` | GSM 7-bit, used for English SMS. | +| `'UCS2'` | UCS-2, used for Chinese and English SMS. | + +**Return Value** + +`0` - Successful execution + +`-1` - Failed execution + + + +> Only the following series modules support long messages. +> +> > EG912N/EG915N/EC200A series SMS content UCS2 encoding supports up to 420 bytes, and GSM encoding supports up to 960 bytes in length. +> > +> > The EC200U/EG912U/EG915U/BG95 series SMS content supports UCS2 encoding up to 280 bytes, while GSM encoding supports a maximum SMS length of 640 bytes. +> > +> > The UCS2 encoding of other series of SMS content supports a maximum of 70 bytes, while the GSM encoding supports a maximum of 160 bytes of SMS length. +> +> + + + +**Example** + +```python +# -*- coding: UTF-8 -*- +import sms + +sms.sendPduMsg('18158626517', 'send pdu msg by GSM mode.', 'GSM') +sms.sendPduMsg('18158626517', 'send pdu msg by UCS2 mode.', 'UCS2') +sms.sendPduMsg('18158626517', '这是一条中文测试短信!通过PDU-UCS2模式', 'UCS2') +``` + + + +## Delete SMS + +### `sms.deleteMsg` + +``` +sms.deleteMsg(index [, delmode]) +``` + +Deletes the message for the specified index. + +**Parameter** + +* `index` - Integer type. The index number of the SMS message to be deleted. +* `delmode` - Integer type. Deletion mode. It is an optional parameter. Default value: 0. + +| Value | Description | +| ----- | ------------------------------------------------ | +| 0 | Delete the SMS message of the specified `index`. | +| 4 | Delete all SMS messages. | + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +**Example** + +```python +>>> import sms +>>> sms.deleteMsg(2) # Delete the SMS message whose index number is 2. +0 +>>> sms.deleteMsg(1,4) #Delete all SMS messages. +0 +``` + + + +## Set SMS Message Storage Location + +### `sms.setSaveLoc` + +``` +sms.setSaveLoc(mem1, mem2, mem3) +``` + +Sets SMS message storage location. + +**Parameter** + +* `mem1` - String type. The storage location of messages to be read and deleted. + +| Value | Description | +| ------ | ------------------ | +| `"SM"` | SIM card
| +| `"ME"` | Mobile device
| +| `"MT"` | Not supported | + +* `mem2` - String type. The storage location of messages to be written and sent. See the detailed parameters in `mem1`. + +* `mem3` - String type. The storage location of new messages. See the detailed parameters in `mem1`. + +**Return Value** + +`0` - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + + + +> When changing the SMS storage location, ensure the contents of `mem1`, `mem2`, and `mem3` are consistent, all set to either `SM` or `ME`. + + + +**Example** + +```python +>>> import sms +>>> sms.setSaveLoc('SM', 'SM', 'SM') +0 +``` + + + +### `sms.getSaveLoc` + +``` +sms.getSaveLoc() +``` + +Gets SMS message storage location. + +**Return Value** + +A tuple`([loc1, current_nums, max_nums],[loc2, current_nums, max_nums],[loc3, current_nums, max_nums])` - Successful execution + +| Parameter | Type | Description | +| -------------- | ------- | ------------------------------------------------------------ | +| `loc1` | String | The storage location of messages to be read and deleted, as the same as `mem1` in `sms.setSaveLoc`. | +| `loc2` | String | The storage location of messages to be written and sent, as the same as `mem2` in `sms.setSaveLoc`. | +| `loc3` | String | The storage location of new messages, as the same as `mem3` in `sms.setSaveLoc`. | +| `current_nums` | Integer | Current number of SMS messages. | +| `max_nums` | Integer | The maximum number of SMS message storages. | + +`-1` - Failed execution,Integer type. + +**Example** + +```python +>>> sms.getSaveLoc() +(['SM', 2, 50], ['SM', 2, 50], ['SM', 2, 50]) +>>> sms.setSaveLoc('ME','ME','ME') +0 +>>> sms.getSaveLoc() +(['ME', 14, 180], ['ME', 14, 180], ['ME', 14, 180]) +``` + + + +## Get the Number of SMS Messages + +### `sms.getMsgNums` + +``` +sms.getMsgNums() +``` + +Gets the number of SMS messages. + +**Return Value** + +The number of SMS messages - Successful execution,Integer type. + +`-1` - Failed execution,Integer type. + +**Example** + +```python +>>> import sms +>>> sms.getMsgNums() # Please send an SMS message to the module before calling this method. +1 +``` + + + +## Get SMS Content + +### `sms.searchPduMsg` + +``` +sms.searchPduMsg(index) +``` + +Gets an SMS message content in PDU mode. + +**Parameter** + +* `index` - Integer type. The index number of the SMS message to be gotten. Range: `0 – MAX-1`. `MAX` is the maximum number of SMS messages stored by the module. + +**Return Value** + +Message content in PDU mode - Successful execution,String + +type. The SMS message content includes the time when the SMS message is received. Therefore, the PDU data of the same SMS message content is different. + +`-1` - Failed execution,Integer type. + +**Example** + +```python +>>> import sms +>>> sms.sendPduMsg('+8618226172342', '123456789aa', 'GSM') # Send an SMS message to yourself. +>>> sms.searchPduMsg(0) # Get the SMS message content in PDU mode. The text message content can be displayed normally only after it is decoded. +'0891683110305005F0240BA19169256015F70000022141013044230B31D98C56B3DD70B97018' +``` + + + +### `sms.searchTextMsg` + +``` +sms.searchTextMsg(index) +``` + +Gets a message content in text mode. + +**Parameter** + +* `index` - Integer type. The index number of the SMS message to be obtained. Range: `0 – MAX-1`. `MAX` is the maximum number of SMS messages stored by the module. + +**Return Value** + +A tuple`(phoneNumber, msg, msgLen)` - Successful execution + +| Parameter | Type | Description | +| ------------- | ------- | ------------------------------------------ | +| `phoneNumber` | String | Phone number of the sender. | +| `msg` | String | Message content. | +| `msgLen` | Integer | Length of the message content. Unit: byte. | + +`-1` - Failed execution, Integer type. + +**Example** + +```python +>>> import sms +>>> sms.sendPduMsg('+8618226172342', '123456789aa', 'GSM') # Send an SMS message to yourself. +>>> sms.searchTextMsg(0) # Get a message content in text mode. +('+8618226172342', '123456789aa', 22) +``` + + + +## Encode SMS Message in PDU Mode + +### `sms.getPduLength` + +```python +sms.getPduLength(pduMsg) +``` + +Gets the length of the specified SMS message in PDU mode. + +**Parameter** + +- `pduMsg` - String type. SMS message in PDU mode. + +**Return Value** + +Length of an SMS message in PDU mode - Successful execution, Integer type. + +`-1` - Failed execution, Integer type. + +**Example** + +```python +>>> import sms +>>> sms.searchPduMsg(0) +'0891683108501505F0040D91688122162743F200000211529003332318C16030180C0683C16030180C0683E170381C0E87' +>>> sms.getPduLength(sms.searchPduMsg(0)) # Please note that the length of the message in PDU mode is obtained, not the length of the string above. +40 +``` + + + +### `sms.decodePdu` + +```python +sms.decodePdu(pduMsg, pduLen) +``` + +Encodes the SMS message in PDU mode read in `sms.searchPduMsg()`. + +**Parameter** + +- `pduMsg` - String type. The SMS message in PDU mode. + +- `pduLen` - Integer type. Length of the SMS message in PDU mode. + +**Return Value** + +A tuple `(phoneNumber, msg, time, msgLen)` - Successful execution + +| Parameter | Type | Description | +| ------------- | ------- | ---------------------------------- | +| `phoneNumber` | String | Phone number of the sender | +| `msg` | String | SMS message content | +| `time` | Integer | Time for receiving the SMS message | +| `msgLen` | Integer | Length of the SMS message | + +`-1` - Failed execution, Integer type. + +**Example** + +```python +>>> import sms +>>>sms.decodePdu('0891683110305005F00405A10110F000081270319043442354516C76CA77ED4FE1FF1A00320030003200315E7496328303975E6CD596C68D445BA34F2067086D3B52A863D09192FF1A4E3B52A88FDC79BB975E6CD596C68D44FF0C5171540C5B8862A47F8E597D751F6D3B3002',20) +>>>('10010', '公益短信:2021年防范非法集资宣传月活动提醒:主动远离非法集资,共同守护美好生活。', '2021-07-13 09:34:44', 118) +``` + + + +## Set SMS Center Number + +### `sms.getCenterAddr` + +```python +sms.getCenterAddr() +``` + +Gets the SMS center number. + + +**Return Value** + +SMS center number - Successful execution,String type. + +`-1` - Failed execution, Integer type. + +**Example** + +```python +>>> import sms +>>> sms.getCenterAddr() +'+8613800551500' +# If the SMS center number does not contain +, you can query the number and use the default +. +``` + + + +### `sms.setCenterAddr` + +```python +sms.setCenterAddr(addr) +``` + +Sets the SMS center number (It is not recommended to change the SMS center number unless otherwise requested). + +**Parameter** + +- `addr` - String type. SMS center number to be set. + + +**Return Value** + +`0` - Successful execution,String type. + +`-1` - Failed execution, Integer type. + + + +## Register Callback Function + +### `sms.setCallback` + +```python +sms.setCallback(usrFun) +``` + +Registers the callback function of receiving an SMS message. + +**Parameter** + +* `usrFun` - Callback function name. The callback function format and parameters are described below. + +```python +def usrFun(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ------- | ---------------------------- | +| `args[0]` | Integer | SIM card slot ID | +| `args[1]` | Integer | SMS message index | +| `args[2]` | String | SMS message storage location | + +**Return Value** + +`0` - Successful execution, Integer type. + +`-1` - Failed execution, Integer type. + +**Example** + +```python +# Example 1 +import sms + +def cb(args): + index = args[1] + storage = args[2] + print('New message! storage:{},index:{}'.format(storage, index)) + +sms.setCallback(cb) + +# Example 2 +# Versions released before 2021-09-09 adopt different methods, as shown in the example 2. +import sms + +def cb(args): + ind_flag = args[0] + if ind_flag == 4097: + mes_buf, mes_len = args[1], args[2] + print('New message! ind_flag:{},mes_buf:{},mes_len:{}'.format(ind_flag, mes_buf, mes_len)) + elif ind_flag == 4099: + mes_type, storage, index = args[1], args[2], args[3] + print('New message! ind_flag:{},mes_type:{},storage:{},index:{}'.format(ind_flag, mes_type, storage, index)) + elif ind_flag == 4100: + mes_buf = args[1] + print('New message! ind_flag:{},mes_buf:{}'.format(ind_flag, mes_buf)) + elif ind_flag == 4101: + storage,index = args[1], args[2] + print('New message! ind_flag:{},storage:{},index:{}'.format(ind_flag, storage, index)) + +sms.setCallback(cb) +``` + diff --git a/docs/API_reference/en/iotlib/ussd.md b/docs/API_reference/en/iotlib/ussd.md new file mode 100644 index 0000000000000000000000000000000000000000..96925111f4a9cc7dd7f1272302f19095921e6d1b --- /dev/null +++ b/docs/API_reference/en/iotlib/ussd.md @@ -0,0 +1,232 @@ +# USSD - Unstructured Supplementary Service Data + +USSD (Unstructured Supplementary Service Data) is a new type of real-time online interactive session data service based on the global mobile communication system GSM (Global System for Mobile Communications) network. It is based on the SIM card and uses the GSM network's signaling channel to transmit data. It is a new service launched on the technical basis of the GSM short message system, and its ability to explore businesses is far stronger than the SMS system. + +USSD uses character-based codes, supporting up to 182 characters. Users can directly interact through their phones by making selections from various menus. Unlike SMS messages, a real-time connection is created during a USSD session. This means that as long as the communication line remains smooth, USSD can enable two-way information communication. Therefore, queries and answers are almost instantaneous. + +USSD maintains a call connection during the session, providing a transparent channel without storage and forwarding. SMS, on the other hand, has no session channel at the physical bearer layer. It is a store and forward system that requires multiple session processes for a user to complete a query. Since USSD is similar to GPRS and maintains a session process during interaction without needing to re-establish the channel for each data transmission, the USSD system responds instantly to user call requests, greatly speeding up response times. The main response delay has shifted to the application server side, with response times much faster than short messages. + + + +> USSD support requires 3 conditions: +> 1. The module must support USSD functions; +> 2. The SIM card must support it; +> 3. The network must support it and have a USSD server; +> +> Currently, operators in China do not support USSD functions. Please consult local operators in other areas. +> +> Currently, only the EC200UEU_AA and EG915ULA_AB_VOLTE modules support USSD functions. + + + +**Example** + +```python +>>> import ussd + +>>> def ussdCallback(args): +... print(args) +... +>>> ussd.setCallback(ussdCallback) # Register callback function + +>>> ussd.send("*101#") # Send USSD command *101# to network +0 +>>> +(4, '', 0, 4) # Callback receives network reply content + +>>> ussd.getSessionState() #Query if in continuous session state +False +``` + +## Callback Registration Functionality + +### `ussd.setCallback` + +``` +ussd.setCallback(fun) +``` + +Registers a callback function. Receives USSD responses to network-initiated or network-originating operations in the callback function. The callback will be triggered whenever a USSD message is received from the network side. + +**Parameter** + +* `fun` - Callback function name. Callback function format and callback function parameter description are as follows: + +```python +def ussdCallback(args): + pass +``` + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| `args[0]` | Integer | Network response status.
`0` Response succeeded, returns network reply string content, see `args[1]`;
`1` Response succeeded, end session;
`2`,`3` Response succeeded, no reply content;
`4` Local error/network rejection/network error return. | +| `args[1]` | String | Received network-side response USSD message content. Only a normal string when `args[0]` is 0, otherwise empty string; | +| `args[2]` | Integer | Network-issued USSD DCS. DCS: Cell broadcast data coding scheme. | +| `args[4]` | Integer | Exception status error code. | + +**Example** + +```python +import ussd + +def ussdCallback(args): + resp_type = args[0] + ussd_str = args[1] + dcs = args[2] + err_code = args[3] + if resp_type == 0: + print('### USSD Network successful return:',ussd_str) + elif resp_type == 1: + print('### USSD end of session.' + elif resp_type in [2,3]: + print('### USSD Network successful return None') + else: + print('### USSD Network return error,err_code:',err_code) +ussd.setCallback(ussdCallback) +``` + + + +## Sending USSD Commands + +### `ussd.send` + +``` +ussd.send(reqstr) +``` + +This method is used to send USSD commands to the network with the default DCS equal to 15. The network reply result is displayed directly in the callback function. + +**Parameter** + +* `reqstr`- USSD sent to the network, string type, cannot be empty, range of 1~159 bytes. + +**Return Value** + +Returns an integer value, `0` indicates send success, `-1` indicates send failure. + +**Example** + +```python +>>> ussd +>>> ussd.send("*101#") # Send USSD command to network. +0 +``` + + + +## Querying Session Status + +### `ussd.getSessionState` + +``` +ussd.getSessionState() +``` + +This method is used to query the USSD session status. When in continuous session state, further user operations are needed. + +**Return Value** + + Returns Boolean type, `False` non-continuous session state, no further user action needed (network-initiated USSD notification, or no further information needed after device-initiated operation); + +`True` continuous session state, further user action needed (network-initiated USSD request or further information needed after device-initiated operation). + + + +> When `ussd.getSessionState()` returns `True`, the network side will keep the interactive session channel with the user open, requiring further user action. There are two ways to take action: +> +> 1. Continue to use `ussd.send` to send USSD commands to interact with the network side; +> 2. Use `ussd.stopSession` to end the continuous session state; + +**Example** + +```python +>>> import ussd +>>> ussd.getSessionState() +False +``` + + + +## Ending Continuous Session State + +### ``ussd.stopSession`` + +``` +ussd.stopSession() +``` + +This method is used to end the continuous session state and releases the USSD session channel preserved by the network side. This will trigger the USSD callback function to end the session with `args[0]` equal to 1. + +**Return Value** + + Returns an integer value, `0` indicates successfully ending the session, `-1` indicates failure or no need to end session state. + +```python +>>> import ussd +>>> ussd.getSessionState() +True +>>> ussd.stopSession() +0 +``` + + + +## DCS Configuration and Query + +### `ussd.getDcs` + +``` +ussd.getDcs() +``` + +This method is used to query the data coding scheme for sending USSD commands. + +**Return Value** + + Returns the data coding scheme DCS for sending USSD commands, integer, range 1~17, 68, 72, 240. + + + +>DCS: 3GPP TS 23.038 Cell Broadcast Data Coding Scheme. Default: 15, generally does not need to be set. + + + +**Example** + +```python +>>> import ussd +>>> ussd.getDcs() +15 +``` + + + +### `ussd.setDcs` + +``` +ussd.getDcs(Dcs) +``` + +This method is used to set the DCS for sending USSD commands. + +**Parameter** + +* `Dcs`- Cell broadcast data coding scheme, integer, range `0~17, 68, 72, 240`; 0 indicates restoring default value. + +**Return Value** + + Returns an integer value, `0` indicates success, `-1` indicates failure. + +**Example** + +```python +>>> import ussd +>>> ussd.getDcs() +15 +>>> import ussd +>>> ussd.setDcs(1) +0 +>>> ussd.getDcs() +1 +``` \ No newline at end of file diff --git a/docs/API_reference/en/iotlib/voiceCall.md b/docs/API_reference/en/iotlib/voiceCall.md new file mode 100644 index 0000000000000000000000000000000000000000..d867ea5d02afa0876b8ed337df50caa4367a5fab --- /dev/null +++ b/docs/API_reference/en/iotlib/voiceCall.md @@ -0,0 +1,829 @@ +# voiceCall - Voice Call + +This feature provides voice call APIs. + + + +>* The modules supporting voice call are listed below. +> EC600N series: EC600NCN_LC/EC600NCN_LD/EC600NCN_LF +> EC600S series: EC600SCN_LA +> EG912N series: EG912NEN_AA +> EG915N series: EG915NEU_AG/EG915NEA_AC +> EC200A series: EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA +> EC200U series: EC200UAU_AA/EC200UAU_AB/EC200UCN_AA/EC200UEU_AA/EC200UEU_AB +> EC600U series: EEC600UEU_AB/EC600UEC_AC/EC600ULA_AC +> EG912U series: EG912UGL_AA/EG912UGL_AC +> EG915U series: EG915UEU_AB/EG915ULA_AB +> * BC25/BC32/EC600G/EC800G/BG95 series module does not support voice call. +> * EC600M/EC800M/EG810M series modules support voice call only when the firmware supports VOLTE. +>* For other modules, a custom version is required to support voice call. + + + +## Set Automatic Answering Time + +### `voiceCall.setAutoAnswer` + +```python +voiceCall.setAutoAnswer(seconds) +``` + +Sets automatic answering time of a voice call. + +**Parameter** + +* `seconds` - Integer type. Automatic answering time of a voice call. Range: 0–255. Unit: s. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +> EC200U/EC600U/EG912U/EG915U series of module, set ` seconds ` represents the number of telephone ringing before answering. The unit is Rings, not seconds. +> +> For a VolTE-based IMS call, `seconds` indicates whether auto answer is enabled. `0`: disables auto answer. `Non-0` : Enable automatic answer, no answer time setting. + +**Example** + +```python +>>> import voiceCall +>>> voiceCall.setAutoAnswer(5) +0 +``` + + + +## Dial Voice Call + +### `voiceCall.callStart` + +```python +voiceCall.callStart(phonenum) +``` + +Dials a voice call. + +**Parameter** + +* `phonenum` - String type. Phone number of the recipient. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> import voiceCall +>>> voiceCall.callStart("13855169092") +0 +``` + + + +## Answer Voice Call + +### `voiceCall.callAnswer` + +```python +voiceCall.callAnswer() +``` + +Answers a voice call. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> voiceCall.callAnswer() +0 +``` + + + +## End Voice Call + +### `voiceCall.callEnd` + +```python +voiceCall.callEnd() +``` + +Ends a voice call. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> import voiceCall +>>> voiceCall.callEnd() +0 +``` + + + +## Register Callback Function + +### `voiceCall.setCallback` + +```python +voiceCall.setCallback(voicecallFun) +``` + +Registers the callback function of different voice call statuses. + +**Parameter** + +* `voicecallFun` - Callback function name. The callback function format and parameters are described below. +```python +def voicecallFun(args): + pass +``` +`args[0]` - Integer type. Voice call status. The number of parameters to the callback function is not fixed but is determined by the first parameter `args[0]`, as shown in the following table. + +| Value | Number of Parameters | args[0] Description | Description of Other Parameters | +| ----- | -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 1 | 1 | Voice call is initialized (The process is completed in the bottom layer with no user intervention. | | +| 2 | 3 | Incoming call alert, ringing | `args[1]`: Caller ID
`args[2]`: Phone number | +| 3 | 3 | Connected | `args[1]`: Caller ID
`args[2]`: Phone number | +| 4 | 3 | Disconnected | `args[1]`: Caller ID
`args[2]`: Call disconnection reason | +| 5 | 1 | Unknown error | | +| 6 | 5 | Call waiting | `args[1]`: Caller ID
`args[2]`: Phone number
`args[3]`: Phone number type [129/145].
129 - Unknown type
145 - International type
`args[4]`: CLI status | +| 7 | 1 | Dialing | | +| 8 | 4 | Dialing failed | `args[1]`: Caller ID
`args[2]`: Dialing failure reason
`args[3]`: Indicator that whether in-band tones can be obtained from the network side | +| 9 | 3 | Waiting | `args[1]`: Caller ID
`args[2]`: Phone number | +| 10 | 8 | Incoming call alert, ringing (VoLTE call) | `args[1]`: Caller ID
`args[2]`: Call direction (MO/MT)
`args[3]`: Call status
`args[4]`: Business type (Generally, this value is 0, indicating voice call)
`args[5]`: Flag of MTPY
`args[6]`: Phone number
`args[7]`: Phone number type
`args[8]`: Reserve | +| 11 | 8 | Connected (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | +| 12 | 8 | Disconnected (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | +| 13 | 8 | Call waiting (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | +| 14 | 8 | Dialing (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | +| 15 | 8 | Dialing with no ring on the other party (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | +| 16 | 8 | Waiting (VoLTE call) | `args[1] – args[8]`: Same as above for specific description | + + + +When the value of `args[0]` is 10-16, the detailed description of `args[1]`-`args[8]`: + +| args[n] | Description | Type | Parameter value | +| ------- | ----------- | ------- | ------------------------------------------------------------ | +| args[1] | idx | Integer | A unique numeric ID used to distinguish active calls. Usually takes the value 1-n, where n is the maximum number of concurrent calls supported by the module. | +| args[2] | direction | Integer | 0 - Mobile originated (MO) call
1 - Mobile terminated (MT) call | +| args[3] | state | Integer | 0 - Active
1 - Held
2 - Dialing (MO call)
3 - Alerting (MO call)
4 - Incoming (MT call)
5 - Waiting (MT call)
6 - Hang up | +| args[4] | mode | Integer | 0 - Voice
1 - Data
2 - FAX | +| args[5] | mpty | Integer | 0 - Call is not one of multiparty (conference) call parties
1 - Call is one of multiparty (conference) call parties | +| args[6] | number | String | Phone number in string type in format specified by **** | +| args[7] | type | Integer | 129 - Unknown type
145 - International type (contains the character "+")
161 - National type | +| args[8] | Reserve | Integer | Reserve | + + + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> import voiceCall +def voice_callback(args): + if not isinstance(args, tuple): + print('voicecall is GSM call, args:', args) + elif args[0] == 10: + print('voicecall incoming call, PhoneNO: ', args[6]) + elif args[0] == 11: + print('voicecall connected, PhoneNO: ', args[6]) + elif args[0] == 12: + print('voicecall disconnect') + elif args[0] == 13: + print('voicecall is waiting, PhoneNO: ', args[6]) + elif args[0] == 14: + print('voicecall dialing, PhoneNO: ', args[6]) + elif args[0] == 15: + print('voicecall alerting, PhoneNO: ', args[6]) + elif args[0] == 16: + print('voicecall holding, PhoneNO: ', args[6]) + else: + print('voicecall is GSM call, args:', args) + +>>> voiceCall.setCallback(voice_callback) +0 +>>> voiceCall.callStart('10086') +0 +``` + + + +>* 1. The above information only applies to versions released after 2021-09-09 that support voice call. +>* 2. Versions released before QPY_V0004_EC600N_CNLC_FW_VOLTE (released on 2021-09-09) use voice calls according to the following rules. + + + +`args[0]` - Integer type. Voice call status. The number of parameters and the meanings of other parameters are described below. + +| Value | Number of Parameters | args[0] Description | Description of Other Parameters | +| ----- | -------------------- | ------------------------------------------ | ------------------------------------------------------------ | +| 4103 | 8 | Incoming call alert, ringing (VoLTE call) | `args[1]`: Caller ID
`args[2]`: Call direction (MO/MT)
`args[3]`: Call status
`args[4]`: Business type (Generally, this value is 0, indicating voice call)
`args[5]`: Flag of MTPT
0 - Non-MTPT
1 - MTPT
`args[6]`: Phone number
`args[7]`: Phone number type [129/145].
129 - Unknown type
145 - International type | +| 4104 | 8 | Connected (VoLTE call) | `args[1] – args[7]`: Same as above for specific description | +| 4105 | 8 | Disconnected (VoLTE call) | `args[1] – args[7]`: Same as above for specific description | +| 4106 | 8 | Call waiting (VoLTE call) | `args[1] – args[7]`: Same as above for specific description | + +**Example** + +```python +>>> import voiceCall +def voice_callback(args): + if args[0] == 4106: + print('voicecall is waiting') + elif args[0] == 4105: + print('voicecall disconnect') + elif args[0] == 4104: + print('voicecall connected, CallNO: ', args[6]) + elif args[0] == 4103: + print('voicecall incoming call, PhoneNO: ', args[6]) +``` + + + +## Auto Hang-up + +### `voiceCall.setAutoCancel` + +```python +voiceCall.setAutoCancel(enable) +``` + +Enables auto hang-up when receiving calls. + +**Parameter** + +* `enable` - Enable or disable auto hang-up when receiving calls. + + `0` -Disable (default) + + `1` - Enable + + + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + + + +>EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA series module supports this method. + + + +**Example** + +```python +>>> import voiceCall +# When you call the module on your phone, the module will not hang up by default. +>>> voiceCall.getAutoCancelStatus() +0 + +# Enable auto hang-up. When you call the module on your phone, the module will hang up by default. +>>> voiceCall.setAutoCancel(1) +0 +>>> voiceCall.getAutoCancelStatus() +1 +``` + + + +### `voiceCall.getAutoCancelStatus` + +```python +voiceCall.getAutoCancelStatus() +``` + +Gets the enablement status of auto hang-up. + +**Return Value** + +`0`: Auto hang-up is disabled + +`1`: Auto hang-up is enabled + + + +> EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA series module supports this method. + + + +**Example** + +```python +>>> import voiceCall +# When you call the module on your phone, the module will not hang up by default. +>>> voiceCall.getAutoCancelStatus() +0 + +# Enable auto hang-up. When you call the module on your phone, the module will hang up by default. +>>> voiceCall.setAutoCancel(1) +0 +>>> voiceCall.getAutoCancelStatus() +1 +``` + + + +## Detect DTMF + +### `voiceCall.startDtmf` + +```python +voiceCall.startDtmf(dtmf, duration) +``` + +Sets DTMF tone. + +**Parameter** + +* `dtmf` - String type. DTMF symbols. Valid symbols:`0-9, A, B, C, D, * and #`. Maximum number of characters: 6. +* `duration` - Integer type. Duration. Range: 100–1000. Unit: ms. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + + + +>This method takes effect only during a voice call. +> +>Multiple characters can be sent at a time (after 2024/4/2, a maximum of 6 characters can be sent at a time). + + + +**Example** + +```python +>>> import voiceCall +>>> voiceCall.startDtmf('A',100) +0 +``` + + + +### `voiceCall.dtmfDetEnable` + +```python +voiceCall.dtmfDetEnable(enable) +``` + +Enables the feature of DTMF detection. DTMF detection is disabled by default. + +**Parameter** + +* `enable` - Integer type. Enable or disable DTMF detection. + + `0` - Disable DTMF detection + + `1` - Enable DTMF detection + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + + + +>EC600N/EC800N/EG912N/EG915N series module supports this method. + + + +### `voiceCall.dtmfSetCb` + +```python +voiceCall.dtmfSetCb(dtmfFun) +``` + +Registers the callback function of DTMF detection. + +**Parameter** + +* `dtmfFun` - Callback function name. The callback function format and parameters are described below. + +```Python +def dtmfFun(args): + pass +``` + +| Parameter | Type | Description | +| ------- | ---- | ------------------------------------------ | +| `args` | String | DTMF characters entered by the peer end. | + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + + + +>EC600N/EC600S/EC800N/EG912N/EG915N series module supports this method. + + + +**Example** + +```python +>>> import voiceCall +>>> def cb(args): +... print(args) + +>>> voiceCall.dtmfSetCb(cb) +0 +>>> voiceCall.dtmfDetEnable(1) +0 +>>> voiceCall.callStart('13855169092') +0 +>>> +1 # If you press 1 on your phone, the pressed character "1" will be received by the callback function. + +8 # If you press 8 on your phone, the pressed character "8" will be received by the callback function. + +9 # If you press 9 on your phone, the pressed character "9" will be received by the callback function. +``` + + + +## Set Up Call Forwarding + +### `voiceCall.setFw` + +```python +voiceCall.setFw(reason, fwmode, phonenum) +``` + +Sets up call forwarding. + +**Parameter** + +* `reason` - Integer type. Call forwarding conditions, as described below. + +| Value | Description | +| -- | ------------- | +| 0 | Unconditional | +| 1 | Busy | +| 2 | No reply | +| 3 | Not reachable | + +* `fwMode` - Integer type. Call forwarding operations, as described below. + +| Value | Description | +| -- | ------------- | +| 0 | Deactivate call forwarding. | +| 1 | Activate call forwarding. | +| 2 | Query call forwarding status. | +| 3 | Register call forwarding. | +| 4 | Erase call forwarding. | + +* `phonenum` - String type. The number to which calls are forwarded. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +> ​ The call transfer function can be used only after the call transfer function is enabled for the sim card carrier. + + + +## Switch Voice Channel + +### `voiceCall.setChannel` + +```python +voiceCall.setChannel(device) +``` + +Sets the voice output channel during a call. Default value: 0 (handset). + +**Parameter** + +* `device` - Integer type. Output channel, as described below. + +| Value | Description | +| -- | ------------- | +| 0 | Handset | +| 1 | Headset | +| 2 | Loudspeaker | + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +**Example** + +```python +>>> voiceCall.setChannel(2) # Switch to loudspeaker channel. +0 +``` + + + +## Set Call Volume + +### `voiceCall.getVolume` + +```python +voiceCall.getVolume() +``` + +Gets the current call volume. + +**Return Value** + +Integer type. Volume. + + + +### `voiceCall.setVolume` + +```python +voiceCall.setVolume(volume) +``` + +Sets call volume. + +**Parameter** + +* `volume` - Integer type. Volume. Range: `0–11`. The higher the value, the higher the volume. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + + + +## Automatic Recording + + +### `voiceCall.setAutoRecord` + +```python +voiceCall.setAutoRecord(enable, recordType, recordMode, filename) +``` + +Enables automatic recording. Automatic recording is disabled by default. The automatic recording must be enabled before the call. + +**Parameter** + +* `enable` - Integer type. Enable or disable automatic recording. + + `0` - Disable + + `1` - Enable + +* `recordType` - Integer type. Recording file type, as described below. + +| Value | Description | +| -------------- | ---- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - Integer type. Mode, as described below. + +| Value |Description | +|-----|--------| +| 0 | The recording is the audio stream of the downlink channel. | +| 1 | The recording is the audio stream of the uplink channel. | +| 2 | The recording is a mixed audio stream of uplink and downlink channels. | + +* `filename` - String type. The desired file name, which must contain the full path. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +`"NOT SUPPORT"` - The interface is not supported. + +**Example** + +```python +>>> voiceCall.setAutoRecord(1,0,2,'U:/test.amr') +0 +``` + + + +> For EC200U/EC600U/EG912U/EG915U series modules, the `recordMode` parameter currently only supports the value 2. +> +> QuecPython currently does not support automatic creation of subdirectories when creating files. For example, `filename` is 'U:/record/test.amr', if there is no 'record' directory in the usr directory, the user needs to use `uos.mkdir('/usr/record')` to create a 'record' directory . + + + +### `voiceCall.startRecord` + +```python +voiceCall.startRecord(recordType, recordMode, filename) +``` + +Starts recording the call. + +**Parameter** + +* `recordType` - Integer type. Recording file type, as described below. + +| Value | Description | +| ----- | ----------- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - Integer type. Mode, as described below. + +| Value |Description | +|------|--------| +| 0 | The recording is the audio stream of the downlink channel. | +| 1 | The recording is the audio stream of the uplink channel. | +| 2 | The recording is a mixed audio stream of uplink and downlink channels. | + +* `filename` - String type. The desired file name, which must contain the full path. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +`"NOT SUPPORT"` - The interface is not supported. + +**Example** + +```python +>>> import voiceCall +>>> voiceCall.startRecord(0,2,'U:/test.amr') +0 +``` + + + +> For EC200U/EC600U/EG912U/EG915U series modules, the `recordMode` parameter currently only supports the value 2. +> +> QuecPython currently does not support automatic creation of subdirectories when creating files. For example, `filename` is 'U:/record/test.amr', if there is no 'record' directory in the usr directory, the user needs to use `uos.mkdir('/usr/record')` to create a 'record' directory . + + + +### `voiceCall.stopRecord` + +```python +voiceCall.stopRecord() +``` + +Stops recording the call. + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +`"NOT SUPPORT"` - The interface is not supported. + +**Example** + +```python +>>> voiceCall.stopRecord() +0 +``` + + + +### `voiceCall.readRecordStream` + +```python +voiceCall.readRecordStream(readBuf, bufLen) +``` + +Reads recording data stream. + +**Parameter** + +* `readBuf` - Buffer used to save the data read. + +* `bufLen` - Length of the string to be read, which cannot be longer than the data length requested by `readBuf`. + +**Return Value** + +Length of the data read - Successful execution + +`-1` - Failed execution + +`"NOT SUPPORT"` - The interface is not supported. + + + +>* The first packet of data in the recording stream is the header of the file in the corresponding format. +>* The first packet of recording streams in WAV format does not contain the file size. You need to calculate the file size after the recording is complete. + + + +### `voiceCall.startRecordStream` + +```python +voiceCall.startRecordStream(recordType, recordMode, callbackFun) +``` + +Starts recording the call in stream format. + +**Parameter** + +* `recordType` - Integer type. Recording file type, as described below. + +| Value | Description | +| ----- | ----------- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - Integer type. Mode, as described below. + +| Value |Description | +|------|--------| +| 0 | RX | +| 1 | TX | +| 2 | MIX | + +* `callbackFun` - Callback function name. The callback function format and parameters are described below. +```python +def recordStreamCallback(args): + pass +``` +| Parameter | Type | Description | +| ------- | ---- | -------------------- | +| `args[0]` | String | Recording data stream | +| `args[1]` | Integer | Length of the recording data stream. | +| `args[2]` | Integer | Recording status
-1: Recording error
0: Start recording
1: Return recording data
2: Stop recording
3: Recording ends
4: No remaining space. | + +**Return Value** + + `0` - Successful execution + +`-1` - Failed execution + +`"NOT SUPPORT"` - The interface is not supported. + + + +>* The first packet of data in the recording stream is the header of the file in the corresponding format. +>* The first packet of recording streams in WAV format does not contain the file size. You need to calculate the file size after the recording is completed. + + + +**Example** + +```python +>>> import voiceCall +>>> import audio + +>>> f=open('usr/mia.amr','w') + +>>> def cb(para): +... if(para[2] == 1): +... read_buf = bytearray(para[1]) +... voiceCall.readRecordStream(read_buf,para[1]) +... f.write(read_buf,para[1]) +... del read_buf +... elif(para[2] == 3): +... f.close() +... +>>> voiceCall.callStart('13855169092') +0 +>>> voiceCall.startRecordStream(0,2,cb) +0 +# Hang up. Either MO or MT hangs up. +>>> uos.listdir('usr') +['system_config.json', 'mia.amr'] +>>> aud=audio.Audio(0) +>>> aud.setVolume(11) +0 +>>> aud.play(2,1,'U:/mia.amr') +0 +``` \ No newline at end of file diff --git a/docs/API_reference/en/media/README/QuecPython_Architecture.png b/docs/API_reference/en/media/README/QuecPython_Architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..acc9d53eb3c2578f858de146888971b0112701cd Binary files /dev/null and b/docs/API_reference/en/media/README/QuecPython_Architecture.png differ diff --git a/docs/API_reference/en/medialib/README.md b/docs/API_reference/en/medialib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..61ba2ddf9fd00798aab46ebc548ade28d075a33c --- /dev/null +++ b/docs/API_reference/en/medialib/README.md @@ -0,0 +1,11 @@ +# QuecPython Multimedia + +> QuecPython multimedia library includes photo, audio, two-dimensional code and other functional components + +This article describes the modules in the QuecPython multimedia library. + +## List of QuecPython multimedia libraries + +- [camera - camera](./camera.md) +- [audio - audio playback](./audio.md) +- [qrcode - Two-dimensional code display](./qrcode.md) \ No newline at end of file diff --git a/docs/API_reference/en/medialib/audio.Audio.md b/docs/API_reference/en/medialib/audio.Audio.md new file mode 100644 index 0000000000000000000000000000000000000000..a4731dfacf77de7693a1d6b8a9faf9e52e98475b --- /dev/null +++ b/docs/API_reference/en/medialib/audio.Audio.md @@ -0,0 +1,296 @@ +# audio - Audio Playback + +Class feature: Audio playback. + +> Currently supported modules:EC600N Series, EC800N Series, EC600M-CN(LA/LE), EC800M-CN(LA/LE/GA), EC600U Series, EC200U Series, EG912U, EG915U and EG915N-EUAG. + +**Example:** + +```python +# -*- coding: UTF-8 -*- +import audio +from machine import Pin +import utime + +def audio_cb(event): + if event == 0: + print('audio-play start.') + elif event == 7: + print('audio-play finish.') + +aud = audio.Audio(0) +aud.setCallback(audio_cb) +# Sets pa +aud.set_pa(Pin.GPIO15,2) +# Plays MP3 +aud.play(2, 1, 'U:/music.mp3') +aud.stop() + +# Audio stream playback +size = 10*1024 # Ensures that the audio data filled at once is large enough for continuous playback on the underlying layer +format = 4 + +def play_from_fs(): + file_size = uos.stat("/usr/test.amr")[6] # Gets the total number of bytes of the file + print(file_size) + with open("/usr/test.amr", "rb")as f: + while 1: + b = f.read(size) # read + if not b: + break + aud.playStream(format, b) + utime.sleep_ms(20) + + +play_from_fs() +# Waits for the playback to finish +utime.sleep_ms(5000) +# Stops the playback so that it does not affect the next playback +aud.stopPlayStream() +``` + +## Constructor + +### `audio.Audio` + +```python +class audio.Audio(device) +``` + +Creates an audio object. + +**Parameter:** + +- `device` - Integer type. The output channel. 0 indicates earpiece, 1 indicates headphone and 2 indicates speaker. See the table below for the specific channels supported by each module. + +**Channels Supported by the Module:** + +| Module Series | Earpiece | Headphone | Speaker | +| -------------------- | ----------- | ----------- | ----------- | +| EC200N/EC600N/EC800N | Supported | Unsupported | Unsupported | +| EC600M-CN(LA/LE) | Supported | Unsupported | Unsupported | +| EC800M-CN(LA/LE/GA) | Supported | Unsupported | Unsupported | +| EG810M | Supported | Unsupported | Unsupported | +| EG915N/EG912N | Supported | Unsupported | Unsupported | +| EG912U | Supported | Unsupported | Unsupported | +| EC200U | Unsupported | Unsupported | Supported | +| EC600U | Supported | Supported | Supported | +| EG915U | Supported | Supported | Unsupported | +| EC600S | Supported | Unsupported | Unsupported | +| EC600K/EC800K | Supported | Unsupported | Unsupported | +| EC800G-CN(GA/TT/LA) | Supported | Supported | Supported | +| EC600G-CN(LA) | Supported | Supported | Supported | + +## Methods + +### Audio.set_pa + +```python +Audio.set_pa(gpio,num) +``` + +This method sets the GPIO of the output PA. + +**Parameter:** + +- `gpio` - Integer type. The output GPIO. Refer to [Pin](./machine.Pin.md). +- `num` - Integer type. Number of power-on pulses. + +**Return Value** + +`1`- Successful execution; `0`- Failed execution. + +### Audio.play + +```python +Audio.play(priority, breakin, filename) +``` + +This method plays audio files. + +It supports the playback of MP3, AMR, and WAV format files. Priorities from 0 to 4 are supported, with a higher number indicating a higher priority. Each priority group supports up to 10 playback tasks simultaneously, and the same playback queue is shared with TTS playback. + +> **Note:** Since the TTS and audio file playback share the same playback queue, the playback priority and interruption mode set in the TTS are not only compared with those set in other TTS playback tasks, but also with those set in audio file playback tasks. Similarly, the playback priority and interruption mode set in audio file playback are also valid for those set in TTS tasks. + +**Parameter:** + +- `priority` - Integer type. Playback priority. Supports priorities from 0 to 4, with a higher number indicating a higher priority. +- `breakin` - Integer type. Interruption mode. 0 indicates the playback is not allowed to be interrupted and 1 indicates the playback is allowed to be interrupted. +- `filename` - Mode. String type. The name of the file to be played, including the file storage path. Click here for the description of the playback path. + +**Return Value:** + +`0` - Successful execution + +`-1`- Failed execution + +`1` - The task cannot be played immediately and is added to the playback queue. + +`-2`- The task can neither be played immediately nor added to the playback queue because the task queue of the priority group for the request has reached its limit. + +**Description of the Playback Path:** + +The user partition path is fixed to start with ’U:/‘, representing the root directory of the user partition. If the user creates an "audio" directory in the root directory and stores the audio files in the "audio" directory, then the path parameter passed in the playback interface should be 'U:/audio/music.mp3'. + +### Audio.stop + +```python +Audio.stop() +``` + +This method stops the audio that is currently playing. + +**Return Value:** + +`0` - Successful execution; `-1`- Failed execution. + +### Audio.stopAll + +```python +Audio.stopAll() +``` + +This method stops the playback of the entire queue. That is, if an audio file is currently being played and there are other audio files waiting to be played in the queue, calling this method will not only stop the current playback but also clear the entire queue and no more content is played. If an audio file is currently being played and the playback queue is empty, calling this method is as same as calling Audio.stop(). + +**Return Value:** + +`0` - Successful execution; `-1`- Failed execution. + +### Audio.setCallback + +```python +Audio.setCallback(cb) +``` + +This method registers the user's callback function to notify the user of the playback status of the audio file. + +> Note: It is recommended to only perform simple and short operations instead of time-consuming or blocking operations in this callback function. + +**Parameter** + +- `cb` - Function type. User callback function. The prototype is as follows: + + ``` + cb(event) + ``` + + **Parameter of the Callback Function**: + + - `event` - Integer type. Playback status. click here for the description of this parameter. + +**Return Value** + +`0` - Successful execution; `-1` - Failed execution. + +**Description of Parameter `event` ** + +| event | Status | +| ----- | ----------------- | +| 0 | Start playback | +| 7 | Playback complete | + +### Audio.getState + +```python +Audio.getState() +``` + +This method gets the audio initialization state. + +**Return Value:** + +`0` - Successful initialization; `-1` - Failed initialization. + +### Audio.getVolume + +```python +Audio.getVolume() +``` + +This method gets the current playback volume. Range: 0–11. 0 indicates mute. + +**Return Value:** + +Volume value in integer type. + +### Audio.setVolume + +```python +Audio.setVolume(vol) +``` + +This method sets the playback volume. Range: 0–11. 0 indicates mute. + +**Parameter:** + +- `vol` - Integer type. Playback volume. Range: 0–11. + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + +### Audio.playStream + +```python +Audio.playStream(format, buf) +``` + +This method plays audio stream. It supports audio stream in MP3, AMR, and WAV format. + +> Note: When playing an AMR format audio stream, if the audio comes from a file, it is recommended to skip the first 6 bytes (i.e., the file header) after starting to read the file; otherwise, playback may fail. + +**Parameter:** + +- `format` - Integer type. The audio stream format. `2` - `WAVPCM`,`3` - `MP3`,`4` - `AMRNB`. +- `buf` - Binary file. The content of the audio stream. + +**Return value:** + +`0` - Successful execution; `-1` - Failed execution. + +### Audio.stopPlayStream + +```python +Audio.stopPlayStream() +``` + +This method stops playing the audio stream. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + +### Audio.aud_tone_play + +```python +Audio.aud_tone_play(tone, time) +``` + +This method plays tone, and automatically stops playing after playing for a period of time. + +> For EC600N/EC800N series module, the value is immediately returned after calling this method. For EC600U/EC200U series module, the return value is in blocked and wait status. + +**Parameter:** + +- `tone` - Integer type. The type of tone. Range: `0–15`. Key tone (0~9, A, B, C, D, #, *),`16`: dialing tone. +- `time` - Integer type. Playback time. Unit: ms. `0` indicates always playing without stopping. + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + +### Audio.aud_tone_play_stop + +```python +Audio.aud_tone_play_stop() +``` + +This method actively stops playing the key tones. + +**Return Value:** + +`0` - Successful execution; `-1`- Failed execution. \ No newline at end of file diff --git a/docs/API_reference/en/medialib/audio.Record.md b/docs/API_reference/en/medialib/audio.Record.md new file mode 100644 index 0000000000000000000000000000000000000000..2fdc7462986708f903eca48859ae3dc83f207e00 --- /dev/null +++ b/docs/API_reference/en/medialib/audio.Record.md @@ -0,0 +1,422 @@ + + +# Record - Audio Record + +Class feature: Recording. + +> Currently supported models: EC600N Series, EC800N Series, EC600M-CN(LA/LE), EC800M-CN(LA/LE/GA), EC600U Series, EC200U Series, EG912U, EG915U and EG915N-EUAG. + +**Example:** + +```python +# -*- coding: UTF-8 -*- +import utime +import audio +from machine import Pin + + +flag = 1 +''' +External speaker plays recording file, select 0 +''' +aud = audio.Audio(0) +tts = audio.TTS(0) + +aud.setVolume(11) + +def record_callback(args): + global flag + print('file_name:{}'.format(args[0])) + print('file_size:{}'.format(args[1])) + print('record_sta:{}'.format(args[2])) + + record_sta = args[2] + if record_sta == 3: + print('The recording is over, play it') + tts.play(1, 0, 2, 'The recording is over, play it') + aud.play(1, 0, audio.getFilePath(path)) + flag = 0 + elif record_sta == -1: + print('The recording failure.') + tts.play(1, 0, 2, 'The recording failure.') + flag = 0 + +record = audio.Record() +record.end_callback(record_callback) +record.start('recordfile.wav', 10) + +while 1: + if flag: + pass + else: + break +``` + +## Constructor + +### `audio.Record` + +```python +class audio.Record(device) +``` + +Creates a record object. + +> If a parameter is passed, it should be consistent with the parameter of `audio.Audio(device)`. + +**Parameter:** + +- `device` - Integer type. The output channel. `0` indicates earpiece, `1` indicates headphone and `2` indicates speaker. Default value: `0`. See the table below for the specific channels supported by each module. + +**Channels Supported by the Module:** + +| Module Series | Earpiece | Headphone | Speaker | +| ------------------- | ----------- | ----------- | ----------- | +| EC600N Series | Supported | Unsupported | Unsupported | +| EC800N Series | Supported | Unsupported | Unsupported | +| EC600M-CN(LA/LE) | Supported | Unsupported | Unsupported | +| EC800M-CN(LA/LE/GA) | Supported | Unsupported | Unsupported | +| EG915N | Supported | Unsupported | Unsupported | +| EG912N | Supported | Unsupported | Unsupported | +| EG912U | Supported | Unsupported | Unsupported | +| EC200U Series | Unsupported | Unsupported | Supported | +| EC600U Series | Supported | Supported | Supported | +| EG915U | Supported | Supported | Unsupported | + + + +## Method + +### Record.start + +```python +audio.start(file_name,seconds) +``` + +This method starts recording, recording data stored as files. + +> When recording files in AMR and WAV formats using this method, default sampling rate 8000. When recording files in MP3 format, default sampling rate 22050. + +**Parameter:** + +- `file_name` - String type. Name of the recording file. +- `seconds` - Integer type. Recording duration. Unit: second. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed to overwrite the file + +`-2` - Failed to open the file + +`-3` - The file is in use. + +`-4` - Channel setting error + +`-5` - Timer resource request failure + +`-6` - Audio format error + +### Record.stop + +```python +Record.stop() +``` + +This method stops recording. + +**Return Value:** + +`0` - Successful execution; `-1` - Failed execution. + +### Record.getFilePath + +```python +Record.getFilePath(file_name) +``` + +This method reads the path of the recording file. + +**Parameter:** + +- `file_name` - String type. Name of the recording file. + +**Return Value:** + +Returns the recording file path for successful execution. + +`-1` - The target file does not exist. + +`-2`- The file name length is 0. + +### Record.getData + +```python +Record.getData(file_name, offset, size) +``` + +This method reads the recording data. + +**Parameter:** + +- `file_name` - String type. The name of the recording file. +- `offset` - Integer type. The offset of the data to be read. +- `size` - Integer type. Data size. Unit: byte. The size should be less than 10 KB. + +**Return Value:** + +Returns the recording data (bytearray type) for successful execution. + +The following are return values for failed execution: + +`-1` - Failed to read the data. + +`-2` - Failed to open the file. + +`-3` - Failed to set the offset. + +`-4` - The file is in use. + +`-5` - The setting is beyond the file size (offset+size > file_size). + +`-6` - The data size to be read is greater than 10 KB. + +`-7` - The memory is less than 10 K. + +### Record.getSize + +```python +Record.getSize(file_name) +``` + +This method reads the size of the recording file. + +**Parameter:** + +- `file_name` - String type. The name of the recording file. + +**Return Value:** + +Returns the file size for successful execution. Unit: byte. + +The return values for failed execution are as follows: + +`-1` - Failed to get the file size. + +`-2` - Failed to open the file. + +`-3` - The file is in use. + +`-4` - The file name length is 0. + +### Record.Delete + +```python +Record.Delete(file_name) +``` + +This method deletes the recording file. + +**Parameter:** + +- `file_name` - String type. The name of the recording file. + +**Return Value:** + +`0` - Successful execution + +`-1` - The file does not exist. + +`-2` - The file is in use. + +### Record.exists + +```python +Record.exists(file_name) +``` + +This method determines whether the recording file exists. + +**Parameter:** + +- `file_name` - String type. The name of the recording file. + +**Return Value:** + +`true` - The file exists. + +`false` - The file does not exist. + +### Record.isBusy + +```python +Record.isBusy() +``` + +This method determines whether recording is in progress. + +**Return Value:** + +`0` - Not in progress; `1` - In progress. + +### Record.end_callback + +```python +Record.end_callback(cb) +``` + +This method sets the callback function for the end of the recording. + +**Parameter:** + +- `cb` - Function type. Callback function for the end of the recording. The prototype is as follows: + + ``` + cb(audio_msg) + ``` + + **Parameter of the Callback Function**: + + - `audio_msg` - List type. The recording information. The elements are as follows: + + ​ `audio_msg[0]`:`file_path` . String type. The file path. + + ​ `audio_msg[1]`:`audio_len` . Integer type. The recording length. + + ​ `audio_msg[2]`:`audio_state` . Integer type. The recording status. Click here for the description of `audio_state` of the callback function. + +**Return Value:** + +`0` - Successful execution; `-1` -Failed execution. + +**Description of `audio_state`:** + +| event | Description | +| ----- | -------------- | +| -1 | Failure | +| 0 | Start playback | +| 3 | Playback ends | + +### Record.gain_set + +```python +Record.gain(code_gain,dsp_gain) +``` + +This method sets the recording gain. + +> Currently, only the EC200N/EC600N/EC800N/EC600S/EG915N/EC600M/EC800M/EG810M/EG800P series modules support this function. + +**Parameter:** + +- `code_gain` - Integer type. Uplink codec gain. Range: [0,4]. +- `dsp_gain` - Integer type. Uplink digital gain. Range: [-36,12]. + +**Return Value:** + +`0` - Successful execution; `-1`- Failed execution. + +### Record.gain_get + +```python +Record.gain_get() +``` + +This method obtains the set recording gain. + +> Currently, only the EC200N/EC600N/EC800N/EC600S/EG915N/EC600M/EC800M/EG810M/EG800P series modules support this function. + +**Parameter:** + +No parameter. + +**Return Value:** + +The return value is a tuple, with the form of:`(code_gain, dsp_gain)` + +- `code_gain` - Integer type. Uplink codec gain. +- `dsp_gain` - Integer type. Uplink digital gain. + +### Record.amrEncDtx_enable + +```python +Record.amrEncDtx_enable(on_off) +``` + +This method controls the DTX feature of the AMR recording. + +> Currently, only the EC600N/EC800N series modules support this feature. + +**Parameter:** + +- `on_off` - Integer type. Enable or disable the DTX feature. `1`- Enable; `0`- Disable. +- No parameter passed - get the current configuration + +**Return Value:** + +No parameter passed: return the current configuration. + +The parameter is passed: no return value if the parameter is correct, and an exception is thrown if the parameter is incorrect. + +### Record.stream_start + +```python +Record.stream_start(format, samplerate, time) +``` + +This method starts recording audio streams. Note that when recording an audio stream, max cached 8k bytes,read the audio stream timely. Currently, a loop buffer is used. Failure to read the audio stream in time will result in data loss. + +**Parameter:** + +- `format` - Integer type. Audio format. See constant. Different module projects can support different audio formats for recording, and the support situation needs to be consulted with Quectel technical personnel. +- `samplerate` - Integer type. Sample rate. Except for MP3 format, it currently supports 8000 sps and 16000 sps, and only supports 22050 sps in MP3 format +- `time` - Integer type. Recording duration. Unit: second. Setting to 0 means continuous recording until stopped using the `Record.stream_stop` interface. + +**Return Value:** + +`0` - Successful execution. `-1`- Failed execution. + +### Record.stream_read + +```python +Record.stream_read(read_buf, len) +``` + +This method reads the recording stream. + +**Parameter:** + +- `read_buf` - Bytearray type. Recording stream buffer. +- `len` - Integer type. Length to be read. + +**Return Value:** + +Returns the number of bytes actually read for successful execution or -1 if failed. + +### Record.stream_stop + +```python +Record.stream_stop() +``` + +This method stop the recording stream. + +**Parameter:** + +No parameter. + +**Return Value:** + +Returns the number of bytes actually read for successful execution or -1 if failed. + +## Constant + +| Constant | Value | Description | +| ---------------- | ----- | ------------------------------------------------------------ | +| `Record.PCM` | 1 | Record audio data in PCM format. | +| `Record.WAV` | 2 | Record audio data in WAV format, and set the recording time to 0 when recording this format. | +| `Record.MP3` | 3 | Record audio data in MP3 format. | +| `Record.AMRNB` | 4 | Record audio data in AMR-NB format, with a sampling rate set to 8000 sps when recording this format. | +| `Record.AMRWB` | 5 | Record audio data in AMR-WB format, with a sampling rate set to 16000 sps when recording this format. | +| `Record.OGGOPUS` | 11 | Record audio data in OggOpus format. | \ No newline at end of file diff --git a/docs/API_reference/en/medialib/audio.md b/docs/API_reference/en/medialib/audio.md new file mode 100644 index 0000000000000000000000000000000000000000..67755f08bfa9d14860f5560eab0d894b506db9dc --- /dev/null +++ b/docs/API_reference/en/medialib/audio.md @@ -0,0 +1,10 @@ +# audio - Audio Playback + +The module contains various audio features, including audio playback, TTS (text-to-speech) playback, recording and so on. + +## Classes + +- [class Audio - Audio Playback](audio.Audio.md) + +- [class Record - Recording](audio.Record.md) + diff --git a/docs/API_reference/en/medialib/camera.CamCapture.md b/docs/API_reference/en/medialib/camera.CamCapture.md new file mode 100644 index 0000000000000000000000000000000000000000..1e3a3ba188422342f872fa9f90496f61fec975f4 --- /dev/null +++ b/docs/API_reference/en/medialib/camera.CamCapture.md @@ -0,0 +1,146 @@ +# CamCapture - Camera Capture + +Class feature: Camera capturing and saving. + +> Note: Please initialize the LCD before using this feature. + +**Example:** + +```python +from machine import LCD +import camera + +# Initialize the LCD object based on the contents of the machine.LCD class +# lcd = LCD() +# lcd.lcd_init(*args) + +# Define a callback function +def cam_callback(para): + # para[0] Camera capture result 0: Success Other: Failure + print("cam capture result is ", para[0]) + # para[1] Name of the saved image + if para[0] == 0: + print("image {} has been saved".format(para[1])) + +# Create a camCapture object +cam = camera.camCapture(0,640,480,1,240,240) + +# Enable camera feature +cam.open() + +# Set a callback function +cam.callback(cam_callback) + +# Take a picture and save it +cam.start(240, 240, "image_demo") + +# Disable camera feature +cam.close() +``` + +## Constructor + +### `camera.camCapture` + +```python +class camera.camCapture(model,cam_w,cam_h,perview_level,lcd_w,lcd_h) +``` + +Creates a camCapture object. + +**Parameter:** + +- `model` - Integer type. Camera model. It can be set to 0 or 1. Click here for corresponding camera model. +- `cam_w` - Integer type. Camera horizontal resolution. Please fill in according to the specifications of the corresponding camera model. +- `cam_h` - Integer type. Camera vertical resolution. Please fill in according to the specifications of the corresponding camera model. +- `perview_level` - Integer type. Preview level. Fill with 1 or 2 on EC600N series, EC800N series, EC600M series and EC800M series modules. The higher the level, the smoother the image, and the more resources consumed. Fill with 1 on other modules. +- `lcd_w` - Integer type. LCD horizontal resolution. Please fill in according to the specifications of the LCD actually used. +- `lcd_h` - Integer type. LCD vertical resolution. Please fill in according to the specifications of the LCD actually used. + +**Corresponding Camera Model:** + +| Number | Camera Model | Communication Method | +| ------ | ------------ | -------------------- | +| 0 | GC032A | SPI | +| 1 | BF3901 | SPI | + +## Method + +### camCapture.open + +```python +camCapture.open() +``` + +This method enables the camera capturing feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camCapture.close + +```python +camCapture.close() +``` + +This method disables the camera capturing feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camCapture.start + +```python +camCaputre.start(width, height, pic_name) +``` + +This method starts capturing and saving the image. + +**Parameter:** + +- `width` - Integer type. The horizontal resolution of the saved image. +- `height` - Integer type. The vertical resolution of the saved image. +- `pic_name` - String type. The name of the image. You don't have to add `.jpeg` suffix to the image name as it will be added automatically. + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +> Note: The capture result is based on the callback function parameters. + +### camCapture.callback + +```python +camCapture.callback(cb) +``` + +This method sets the callback function of camera capturing. + +**Parameter:** + +- `cb` - The callback function of camera capture. The prototype is as follows: + + ``` + cb(result_list) + ``` + + **Parameter of the Callback Function:** + + - `result_list[0]` - Integer type. The save result. `0` indicates successful execution and other values indicate failed execution. + + - `result_list[1]` - String type. The name of the saved image. + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + diff --git a/docs/API_reference/en/medialib/camera.CamDecoder.md b/docs/API_reference/en/medialib/camera.CamDecoder.md new file mode 100644 index 0000000000000000000000000000000000000000..5a6737cc17859779fe9ac6bb4637274cdc343392 --- /dev/null +++ b/docs/API_reference/en/medialib/camera.CamDecoder.md @@ -0,0 +1,195 @@ +# CamDecoder - Camera Scan Code + +Class feature: Camera code scanning. + +> Note: Please initialize the LCD before enabling preview feature. + +**Example:** + +```python +from machine import LCD +import camera + +# Initialize the LCD object based on the contents of the machine.LCD class before enabling preview feature +# lcd = LCD() +# lcd.lcd_init(*args) + +# The LCD object can be left uninitialized if there is no need to enable preview feature + +# Define a callback function +def scan_callback(para): + # para[0] Scan result 0: Success Other: Failure + print("scan result is ", para[0]) + # para[1] Decode content + if para[0] == 0: + print("decode content is ", para[1]) + +# Create a camScandecode object +scaner = camera.camScandecode(0,1,640,480,1,240,240) + +# Enable camera scanning feature +scaner.open() + +# Register scanning callback function +scaner.callback(scan_callback) + +# Start scanning +scaner.start() + +# Stop scanning +scaner.stop() + +# Disable camera scanning feature +scaner.close() +``` + +## Constructor + +### `camera.camScandecode` + +```python +class camera.camScandecode(model,decode_level,cam_w,cam_h,perview_level,lcd_w,lcd_h) +``` + +Creates a camScandecode object. + +**Parameter:** + +- `model` - Integer type. Camera model. It can be set to 0 or 1. Click here for corresponding camera model. +- `decode_level` - Integer type. Decoding level. Fill with 1 or 2 on EC600N series, EC800N series, EC600M series and EC800M series modules. The higher the level, the smoother the image, and the more resources consumed. Fill with 1 on other modules. +- `cam_w` - Integer type. Camera horizontal resolution. Please fill in according to the specifications of the corresponding camera model. +- `cam_h` - Integer type. Camera vertical resolution. Please fill in according to the specifications of the corresponding camera model. +- `perview_level` - Integer type. Preview level. Fill with 1 or 2 on EC600N series, EC800N series, EC600M series and EC800M series modules. The higher the level, the smoother the image, and the more resources consumed. Fill with 1 on other modules. +- `lcd_w` - Integer type. LCD horizontal resolution. Please fill in according to the specifications of the LCD actually used. +- `lcd_h` - Integer type. LCD vertical resolution. Please fill in according to the specifications of the LCD actually used. + +**Corresponding Camera Model:** + +| Number | Camera Model | Communication Method | +| ------ | ------------ | -------------------- | +| 0 | GC032A | SPI | +| 1 | BF3901 | SPI | + +## Method + +### camScandecode.open + +```python +camScandecode.open() +``` + +This method enables the camera code scanning feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.close + +```python +camScandecode.close() +``` + +This method disables the camera code scanning feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.start + +```python +camScandecode.start() +``` + +This method starts the camera code scanning. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.stop + +```python +camScandecode.stop() +``` + +This method stops the camera code scanning. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.pause + +```python +camScandecode.pause() +``` + +This method pauses the camera code scanning. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.resume + +```python +camScandecode.resume() +``` + +This method resumes the camera code scanning. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camScandecode.callback + +```python +camScandecode.callback(cb) +``` + +This method sets the scanning callback function. + +**Parameter:** + +- `cb` - Scanning callback function. The prototype is as follows: + + ``` + cb(result_list) + ``` + + **Parameter of the Callback Function:** + + - `result_list[0]` - Integer type. The scanning result. `0` indicates successful execution and other values indicate failed execution. + + - `result_list[1]` - String type. The scanning content. + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. \ No newline at end of file diff --git a/docs/API_reference/en/medialib/camera.CamPreview.md b/docs/API_reference/en/medialib/camera.CamPreview.md new file mode 100644 index 0000000000000000000000000000000000000000..6ee9a12bb81b8eb7e100adedf293ba30f847e4f4 --- /dev/null +++ b/docs/API_reference/en/medialib/camera.CamPreview.md @@ -0,0 +1,87 @@ + + +# CamPreview - Camera Preview + +Class feature: Camera previewing. + +> Note: Please initialize the LCD before using this feature. + +**Example:** + +```python +from machine import LCD +import camera + +# Initialize the LCD object based on the contents of the machine.LCD class +# lcd = LCD() +# lcd.lcd_init(*args) + +# Create a camPreview object +preview = camera.camPreview(0,640,480,240,240,1) + +# Enable camera preview feature +preview.open() + +# Disable camera preview feature +preview.close() +``` + +## Constructor + +### `camera.camPreview` + +```python +class camera.camPreview(model,cam_w,cam_h,lcd_w,lcd_h,perview_level) +``` + +Creates a camPreview object. + +**Parameter:** + +- `model` - Integer type. Camera model. Click here for corresponding camera model. +- `cam_w` - Integer type. Camera horizontal resolution. Please fill in according to the specifications of the corresponding camera model. +- `cam_h` - Integer type. Camera vertical resolution. Please fill in according to the specifications of the corresponding camera model. +- `lcd_w` - Integer type. LCD horizontal resolution. Please fill in according to the specifications of the LCD actually used. +- `lcd_h` - Integer type. LCD vertical resolution. Please fill in according to the specifications of the LCD actually used. +- `perview_level` - Integer type. Preview level. Fill with 1 or 2 on EC600N series, EC800N series, EC600M series and EC800M series modules. The higher the level, the smoother the image, and the more resources consumed. Fill with 1 on other modules. + +**Corresponding Camera Model:** + +| Number | Camera Model | Communication Method | +| ------ | ------------ | -------------------- | +| 0 | GC032A | SPI | +| 1 | BF3901 | SPI | + +## Method + +### camPreview.open + +```python +camPreview.open() +``` + +This method enables the camera preview feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. + +### camPreview.close + +``` +camPreview.close() +``` + +This method disables the camera preview feature. + +**Parameter:** + +None + +**Return Value:** + +`0` - Successful execution; Other values - Failed execution. \ No newline at end of file diff --git a/docs/API_reference/en/medialib/camera.md b/docs/API_reference/en/medialib/camera.md new file mode 100644 index 0000000000000000000000000000000000000000..be8ed8462f51d0c227608c7ff03b8955e1bca337 --- /dev/null +++ b/docs/API_reference/en/medialib/camera.md @@ -0,0 +1,63 @@ +# camera - Camera Driver + +Module feature: Camera preview, camera decoder, and camera capture. + +> Currently supported modules: EC600N Series, EC800N Series, EC600M Series, EC800M Series, EC600U-CN and EC200U-CN. +> +> Note: If the preview feature is needed, please initialize the LCD object first by referring to [the content of lcd class in the machine module](machine.LCD.md) before initializing the camera object. + +**Example:** + +```python +# -*- coding: UTF-8 -*- +from machine import LCD +import camera + +# If the preview feature is needed, please initialize the LCD object first by referring to the content of the lcd class in the machine module. +# lcd = LCD() +# lcd.lcd_init(*args) + +# Camera preview feature +preview = camera.camPreview(0,640,480,240,240,1) +preview.open() +preview.close() + +# Camera decoder feature +def scan_callback(para): + # para[0] Scan result 0: Success Other: Failure + print("scan result is ", para[0]) + # para[1] Decode content + if para[0] == 0: + print("decode content is ", para[1]) + +scaner = camera.camScandecode(0,1,640,480,1,240,240) +scaner.open() +scaner.callback(scan_callback) +scaner.start() +scaner.stop() +scaner.close() + +# Camera capture feature +def cam_callback(para): + # para[0] Camera capture result 0: Success Other: Failure + print("cam capture result is ", para[0]) + # para[1] Name of the saved image + if para[0] == 0: + print("image {} has been saved".format(para[1])) + +cam = camera.camCapture(0,640,480,1,240,240) +cam.open() +cam.callback(cam_callback) +cam.start(240, 240, "image_demo") +cam.close() +``` + + + +## Classes + +- [class CamPreview - Camera Preview](./camera.CamPreview.md) + +- [class CamDecoder - Camera Decoder](camera.CamDecoder.md) + +- [class CamCapture - Camera Capture](camera.CamCapture.md) \ No newline at end of file diff --git a/docs/API_reference/en/medialib/qrcode.md b/docs/API_reference/en/medialib/qrcode.md new file mode 100644 index 0000000000000000000000000000000000000000..6f036e5e6c7545c188bd2e7f46639eb59bea9817 --- /dev/null +++ b/docs/API_reference/en/medialib/qrcode.md @@ -0,0 +1,68 @@ +# qrcode- QR Code Display + +Feature introduction: generate a corresponding QR code according to the input content. + +## Display QR Code + +### `qrcode.show` + +```python +qrcode.show(qrcode_str,magnification,start_x,start_y,Background_color,Foreground_color,Rotate) +``` + +Displays QR codes to LCD. + +**Parameter:** + +- `qrcode_str` - String type. QR code content. +- `magnification` - Integer type. Magnification. Range: 1–6. +- `start_x` - Integer type. The start x coordinate of the displayed QR code. +- `start_y` - Integer type. The start y coordinate of the displayed QR code. +- `Background_color` - Integer type. Background color. Default value: 0xffff. +- `Foreground_color` - Integer type. Foreground color. Default value: 0x0000. +- `Rotate` - Integer type. Rotation angle. Reference [Constant](#constant). Default value: 0. + +**Return Value:** + +`0` - Successful execution + +`-1` - QR code generation failed + +`-2` - Magnification failed + +`-3` - Display failed + +## Generation QR Code Data + +### `qrcode.getQRData` + +```python +qrcode.getQRData(qrcode_str,magnification,Background_color,Foreground_color) +``` + +Generation QR code and retrieve data. + +**Parameter:** + +- `qrcode_str` - String type. QR code content. +- `magnification` - Integer type. Magnification. Range: 1–6. +- `Background_color` - Integer type. Background color. Default value: 0xffff. +- `Foreground_color` - Integer type. Foreground color. Default value: 0x0000. + +**Return Value:** + +`-1` - QR code generation failed + +Return tuple upon success `(side_length, data)` + +- `side_length`: Side length of QR code. +- `data`: Data of QR code. + +## Constant + +| Constant | Value | Description | +| ------------------- | ----- | ------------------------------------------------------ | +| `qrcode.ROTATE_0` | 0 | QR code display without rotation | +| `qrcode.ROTATE_90` | 1 | Rotate the QR code clockwise by 90 degrees to display | +| `qrcode.ROTATE_180` | 2 | Rotate the QR code clockwise by 180 degrees to display | +| `qrcode.ROTATE_270` | 3 | Rotate the QR code clockwise by 270 degrees to display | \ No newline at end of file diff --git a/docs/API_reference/en/networklib/Lwm2m.md b/docs/API_reference/en/networklib/Lwm2m.md new file mode 100644 index 0000000000000000000000000000000000000000..80c10258fbc6fb09696ba405ef4bddf26fc68aef --- /dev/null +++ b/docs/API_reference/en/networklib/Lwm2m.md @@ -0,0 +1,218 @@ +# LWM2M - Lightweight M2M (Machine to Machine) +## Create Object +The lightweight IoT protocol provides functionality for managing devices on a cloud platform, such as checking device online status, monitoring current signal conditions, restarting devices, and more. + +>The following models support this module function. For customized functions,please refer to the actual features: +> +>EC200UEU_AB_SANX/BG95M8_SANX/EC200AAU_HA_SANX/EG912NEN_AA. + +### `lwm2m` + +```python +lw=lwm2m() +``` + +Create LwM2M object. + +**Parameter Description:** + +No parameters. + +**Return Value Description:** + +Returns the lwm2m object. + +## Initialize Object + +### `lwm2m.init` + +```python +lwm2m.init() +``` + +Initialize the object. + +**Parameter Description:** + +No parameters. + +**Return Value Description:** + +Returns an integer value of 0 for success, and an integer value of -1 for failure. + +## Configure Object + +### `lwm2m.config` + +```python +lwm2m.config(config_type,config_list) +``` + +Configure functional module parameters. + +**Parameter Description:** + +* `config_type` - Configuration type, an enumerated value under the lwm2m object, see below. + +| Configuration Type | Corresponding config_list Parameter | Remarks | +| ------------------ | ------------------------------------------------------------------- | ------------------------------ | +| lwm2m.Epnamemode | [mode] | | +| lwm2m.Reset | [] | Empty list | +| lwm2m.Security | [serverID,SSID,server_addr,bootstrap,security_mode,psk_id,psk_key] | | +| lwm2m.Server | [serverID,life_time,pmin,pmax,disable_timeout,storing,binding_mode] | | +| lwm2m.Urc | [URC_onoff] | Must be enabled to capture URC | +| lwm2m.Fota | [download,update] | Capture URC in manual mode. | + +* `config_list` - List of configuration parameters, list data type, list element values are explained in below. + +| Field Name | Data Type | Field Description | +| --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| serverID | Integer | 0 - Bootstrap server
1 - DM server
| +| SSID | Integer | 100 - Bootstrap server
1000 - Diagnostics server
| +| server_addr | String | Server address in the format "address", maximum length 256. | +| bootstrap | Integer | 0 - Do not use bootstrap (only when serverID is not 0)
1 - Use bootstrap (only when serverID is 0) | +| security_mode | Integer | Encryption method:
0 - Pre-shared key mode
3 - No security mode | +| psk_id | String | Used when security_mode is 0 | +| psk_key | String | Used when security_mode is 0 | +| life_time | Integer | Lifetime, range 1-86400, default is 86400, in seconds. | +| pmin | Integer | Default pmin period, range 1-86400, default is 86400, in seconds. | +| pmax | Integer | Default pmax period, range 1-86400, default is 86400, in seconds. | +| disable_timeout | Integer | Time interval before the next connection after disconnection from lwm2m server. Range 1-86400, default is 86400, in seconds. | +| storing | Integer | Whether to save server information:
0 Do not save
1 Save | +| binding_mode | String | Connection method to the server, currently only supporting UDP-based connection
"U" - UDP mode
"UQ" - UDP with queue mode
"S" - SMS mode
"SQ" - SMS with queue mode
"US" - UDP and SMS mode
"UQS" - UDP and SMS with queue mode | +| mode | Integer | Terminal device name format:
3 - Format: urn:imeixxxxx,lconfigured epname format | +| download | Integer | Download mode:
0 - Manual download
1 - Automatic download | +| update | Integer | Update mode:
0 - Manual update
1 - Automatic update | +| URC_onoff | Integer | Enable/Disable URC reporting for lwm2m:
0 - Disable URC reporting
1 - Enable URC reporting | + +**Return Value Description:** + +Returns an integer value of 0 for success, an integer value of -1 for failure, and an integer value of -2 for unsupported operatio +## Register + +### `lwm2m.register` + +```python +lwm2m.register() +``` + +Send a login request to the LwM2M server. The result of the login, whether successful or failed, will be sent through a callback function with the login success message. + +**Parameter Description:** + +No parameters. + +**Return Value Description:** + +Returns 0 for success, -1 for failure. The registration result requires calling the query interface to check. + +## Unregister + +### `lwm2m.unregister` + +```python +lwm2m.unregister() +``` + +Send a logout request to the LwM2M server. The result, whether successful or failed, will be notified through a callback function. + +**Parameter Description:** + +No parameters. + +**Return Value Description:** + +Returns 0 for success, -1 for failure. The unregister result requires calling the query interface to check. + +## Query Registration Status + +### `lwm2m.stat` + +```python +lwm2m.stat() +``` + +Query the current login status. + +**Parameter Description:** + +No parameters. + +**Return Value Description:** + +Returns an integer value of 0 for 'Not Registered' status, 1 for 'Registering' status, 2 for 'Registered' status, 3 for 'Deregistering' status, and 4 for 'Login Failed' status. + +## Send Heartbeat + +### `lwm2m.update` + +```python +lwm2m.update(ssid) +``` + +Send a heartbeat packet to the LwM2M server. There is an automatic heartbeat process internally, and it is not recommended to call this interface manually. + +**Parameter Description:** + +* `ssid` - Configured ssid or the ssid issued during BS login in the bootstrap stage, integer value. + +**Return Value Description:** + +Returns 0 for success, -1 for failure. The result of the update is notified through the callback function. + +## Register Callback Function + +### `lwm2m.register_call` + +```python +lwm2m.register_call(usrfun) +``` + +Register a callback function. This callback function will notify the upper-layer application of the login result and messages sent by the server. + +**Parameter Description:** + +* `usrfun` - The callback function to be set, which is called when the server responds. + +**回调函数参数** + +* `list` - The callback function notification data, list type, described in detail below: + +| Element | Data Type | Description | +| ------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| list[0] | Integer | Event type (can be ignored) | +| list[1] | Integer | Event code (can be ignored) | +| list[2] | Integer | Captured URC string data (specific event description can be found in [Event-Description](#Event-Description), used to determine the connection event of Lwm2m. | + +**Return Value Description:** + +Returns 0 for success, -1 for failure. To remove an already registered callback function, pass in None. + + +## Event-Description + +The event types may vary slightly across platforms, for example, some platforms do not have APN, which does not affect functionality or usage. + +| Event Type | Description | Remarks | +| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| +QLWURC: "pdp active",result,APN | Result of PDP activation. Before sending the registration request to LwM2M, the PDP server should be activated. | result: string type
"successfully"
"failed"
APN: string type
APN value | +| +QLWURC: "initial",result,SSID | Initialization result when the client connects to the lwm2m server. | result: string type
"successfully"
"failed"
SSID: integer type
0 - All servers
Other values - Specific servers | +| +QLWURC: "dtls",result,SSID | DTLS handshake result when using encryption. | Same as above | +| +QLWURC: "bootstraping" | Reports this URC when the bootstrap process is active. | | +| +QLWURC: "bootstrap",result,SSID | Result of the Bootstrap process. | Same as above | +| +QLWURC: "registering" | Reports this URC when the client is registering with the lwm2m server. | Same as above | +| +QLWURC: "ready",result,SSID | Result of registration request sent to the lwm2m server. | Same as above | +| +QLWURC: "update",result,SSID | Result of update request sent to the lwm2m server. | Same as above | +| +QLWURC: "deregister",SSID,code
+QLWURC: "deregister",code | Result of the deregistration request sent to the lwm2m server. | SSID: integer type
0 - All servers
Other values - Specific servers
Code: integer
0 - Success
1 - Failure
3 - Unknown Error | +| +QLWURC: "fota/pkgurl",url | The URL address sent by the lwm2m server. | | +| +QLWURC: "apn_changed",APN | The APN sent by the lwm2m server. | | +| +QLWURC: "user_name_changed",user | The user name sent by the lwm2m server. | | +| +QLWURC: "secret_changed",password | The password sent by the lwm2m server. | | +| +QLWURC: "authentication_type_changed", | The authentication type sent by the lwm2m server. | | +| +QLWURC: "lifetime_changed",lifetime | The lifetime (heartbeat period) sent by the lwm2m server. | | +| +QLWURC: "current_time_changed",data_time | The timestamp sent by the lwm2m server. | | + +--- + +## Get example +*[Click to view example code.](https://github.com/QuecPython/examples/tree/main/network-comm/net-protocols/lwm2m/example_lwm2m.py)* diff --git a/docs/API_reference/en/networklib/README.md b/docs/API_reference/en/networklib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ddda2ace69edf4c5ead03eb5a2250e84df7042 --- /dev/null +++ b/docs/API_reference/en/networklib/README.md @@ -0,0 +1,17 @@ +# QuecPython web app + +> QuecPython Web Application Library includes functional components related to web applications + +This article describes the modules in the QuecPython web application library. + +## QuecPython Web application library list + +- [ussl - SSL Encrypted communication](./ussl.md) +- [request - HTTP client](./request.md) +- [umqtt - MQTT client](./umqtt.md) +- [uwebsocket - websocket client](./uwebsocket.md) +- [uping - Sends ping packets](./uping.md) +- [ntptime - Network Time synchronization](./ntptime.md) +- [lwm2m - Light Weight Machine-To-Machine](./Lwm2m.md) +- [ftp - ftp client](./ftp.md) + diff --git a/docs/API_reference/en/networklib/ftp.md b/docs/API_reference/en/networklib/ftp.md new file mode 100644 index 0000000000000000000000000000000000000000..55f28a898424e370f6eaa0d677f9b57470d1a961 --- /dev/null +++ b/docs/API_reference/en/networklib/ftp.md @@ -0,0 +1,508 @@ +# ftplib - FTP Client + +FTP (File Transfer Protocol) is a standard protocol for transferring files over a computer network. It is based on a client-server model and uses control and data connections to enable file upload, download, and management operations. + +> ftplib is implemented in Python source code. If the corresponding firmware version does not support it by default, users can use the source code [ftplib.py](https://github.com/QuecPython/ftplib) and put it in the default directory /usr. When using it, change from ftplib import FTP to from usr.ftplib import FTP. + +## Constructor + +### `ftplib.FTP` + +```python +class ftplib.FTP(host=None, port=None, user=None, passwd=None, acct=None,timeout=None) +``` + +Construct an FTP connection object. + +> 1. If `host` and `port` are actively passed when instantiating parameters, the `connect` method will be actively called after the object is successfully constructed to connect to the server. Connection failure will trigger an exception. If not passed, you need to call the `connect` method yourself. +> 2. On the basis of active connection, entering `user` and `port` will call the `login` method to log in to the server after the connection is successful. If not entered, you need to call the `login` method yourself. + +**Parameter** + +- `host` - Optional parameter, FTP server address, string type, need to call `connect` method to connect server if not passed. +- `port` - Optional parameter, FTP server port, integer, default port is 21. +- `user` - Optional parameter, client login username, string type, anonymous access if not specified, default is `'anonymous'`. +- `passwd`- Optional parameter, client login password, string type, default is `'anonymous@'` if `user` is `'anonymous'`. +- `acct`- Optional parameter, account, string type, empty by default, generally not set. +- `timeout`- Optional parameter, connection timeout, integer, unit second. + +**Return Value** + +- Return FTP object. + +**Example** + +```python +# The feature is included if no exception is thrown +from ftplib import FTP + +# Create FTP object without passing parameters +ftp = FTP() + +# Create FTP object by passing parameters, will connect and login server based on passed host and user +host = 'xxx.xxx.xxx.xxx' +port = 21 +ftp = FTP(host='xxx.xxx.xxx.xxx', port=21, user='xxx', passwd='xxx') +``` + +## Set Debug Level + +### `ftp.set_debuglevel` + +```python +ftp.set_debuglevel(level) +``` + +Set the debug level of the instance, which controls the amount of debug information. The default value 0 does not generate debug information. The value 1 generates a medium amount of debug information, usually one line per request. Values greater than or equal to 2 generate the most debug information, and every line sent and received on the FTP control connection will be logged. + +**Parameter** + +- `level` - Optional parameter, debug level, integer, default is 0. + +**Return Value** + +- None. + +**Example** + +```python +ftp.set_debuglevel(1) +``` + +## Connect to FTP Server + +### `ftp.connect` + +```python +ftp.connect(host, port, timeout) +``` + +The FTP client initiates a connection request to the server. + +**Parameter** + +- `host` - Required parameter, FTP server address, string type, need to call `connect` method if not passed. +- `port` - Optional parameter, FTP server port, integer, default port is 21. +- `timeout` - Optional parameter, connection timeout, integer, unit second. + +**Return Value** + +- Return string starting with `220`, indicating successful connection (e.g. `'220 (vsFTPd 3.0.3)'`), otherwise connection failed. + +**Example** + +```python +host = 'xxx.xxx.xxx.xxx' +port = 21 + +ftp.connect(host=host, port=port) +# 220 (vsFTPd 3.0.3) +``` + +## Login to FTP Server + +### `ftp.login` + +```python +ftp.login(user, passwd) +``` + +The FTP client initiates a login request to the server. The login request needs to be made after the connection is established successfully. + +**Parameter** + +- `user` - Optional parameter, client login username, string type, anonymous access if not specified, default is `'anonymous'`. +- `passwd` - Optional parameter, client login password, string type, default is `'anonymous@'` if `user` is `'anonymous'`. + +**Return Value** + +- Return string starting with `230`, indicating successful login (e.g. `'230 Login successful.'`), otherwise login failed. + +**Example** + +```python +user = 'xxx' +passwd = 'xxx' + +ftp.login(user=user, passwd=passwd) +# 230 Login successful. +``` + +## FTP Operation Commands + +### `ftp.nlst` + +```python +ftp.nlst(*args) +``` + +Return file name list, default is current server directory. + +**Parameter** + +- `args` - Optional parameter, directory to be listed (default is current server directory), list type. + +**Return Value** + +- File name list. + +**Example** + +```python +ftp.nlst() +# ['FTP-TEST', 'system_config.json'] +``` + +### `ftp.dir` + +```python +ftp.dir(*args) +``` + +Get content list in current directory. + +**Parameter** + +- `args` - Optional parameter, directory to return, list type. + +**Return Value** + +- Content list in the directory. + +**Example** + +```python +ftp.dir() +# -rw-r--r-- 1 1002 1002 12 Jul 26 10:07 FTP-TEST +# -rw------- 1 1002 1002 17 Jul 28 16:40 +``` + +### `ftp.pwd` + +```python +ftp.pwd() +``` + + Get current FTP server directory. + +**Return Value** + +- Current FTP server directory. + +**Example** + +```python +ftp.pwd() +# /home/ftpuser +``` + +### `ftp.rename` + +```python +ftp.rename(fromname, toname) +``` + +Rename a file on the FTP server. + +**Parameter** + +- `fromname` - Required parameter, filename to be modified, string type. +- `toname` - Required parameter, renamed filename, string type. + +**Return Value** + +- Return string starting with `250`, indicating successful renaming (e.g. `'250 Rename successful.'`), otherwise renaming failed. + +**Example** + +```python +from_name = ftp.pwd() + '/system_config.json' +to_name = ftp.pwd() + '/system.json' +ftp.rename(from_name, to_name) +# 250 Rename successful. +``` + +### `ftp.delete` + +```python +ftp.delete(file_name) +``` + +Delete a file on the FTP server. + +**Parameter** + +- `file_name` - Required parameter, filename to delete, string type. + +**Return Value** + +- Return string starting with `250`, indicating successful deletion (e.g. `'250 Delete operation successful.'`), otherwise deletion failed. + +**Example** + +```python +file_name = ftp.pwd() + '/system.json' +ftp.delete(file_name) +# 250 Delete operation successful. +``` + +### `ftp.mkd` + +```python +ftp.mkd(pathname) +``` + +Create a directory on the FTP server. + +**Parameter** + +- `pathname` - Required parameter, file path of directory to be created, string type. + +**Return Value** + +- Return created path information, string format. + +**Example** + +```python +new_dir = ftp.pwd() + '/test_dir' +ftp.mkd(new_dir) +# /home/ftpuser/test_dir +``` + +### `ftp.cwd` + +```python +ftp.cwd(pathname) +``` + +Set current directory on server side. + +**Parameter** + +- `pathname` - Required parameter, path to set, string type. + +**Return Value** + +- Return string starting with `250`, indicating successful setting (e.g. `'250 Directory successfully changed.'`), otherwise setting failed. + +**Example** + +```python +target_dir = ftp.pwd() + '/test_dir' +ftp.cwd(target_dir) +# 250 Directory successfully changed. +``` + +### `ftp.quit` + +```python +ftp.quit() +``` + +Close FTP server connection. + +**Return Value** + +- Return string starting with `221`, indicating successful disconnection (e.g. `'221 Goodbye.'`), otherwise disconnection failed. + +**Example** + +```python +ftp.quit() +# 221 Goodbye. +``` + +## File Download + +### `ftp.retrbinary` + +```python +ftp.retrbinary(cmd, callback, blocksize) +``` + +Use `RETR filename` FTP command to download files from FTP server to local in binary mode. It is recommended when handling binary files (such as images, videos, audios, etc.). + +**Parameter** + +- `cmd` - Required parameter, transfer command, consist of `RETR + filename` (separated by spaces), string type. +- `callback` - Required parameter, callback function to receive remote file data. + - **Function prototype:** `function(msg)` + - **Parameter:** + - `msg`: Bytes type, used to receive file data transferred from FTP server to local. +- `blocksize` - Optional parameter, set maximum bytes per transfer, default is `2048K`. + +**Return Value** + +- Return string starting with `226`, indicating successful file download (e.g. `226 Transfer complete`), otherwise download failed. + +**Example** + +```python +path = 'usr/' # Root dir of module user partition is 'usr' +filename = 'ftp_file.bin' # Filename to download + +# Open and create a file +save_fp = open(path + filename, 'wb+') +# Get current path on server +server_path = ftp.pwd() +# Establish download connection, save_fp.write is write file operation, passed as callback function +res = ftp.retrbinary('RETR ' + server_path + '/' + filename, save_fp.write) +# Download complete +msg = 'Down %s to device %s.' +if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True +else: + print(msg % (filename, 'falied')) + return False +``` + +### `ftp.retrlines` + +```python +ftp.retrlines(cmd, callback) +``` + +Use `RETR filename` FTP command to download files in text mode, usually used to download text files. + +**Parameter** + +- `cmd` - Required parameter, transfer command, consist of `RETR + filename` (separated by spaces), string type. +- `callback` - Required parameter, callback function to receive remote file data. + - **Function prototype:** `function(msg)` + - **Parameter:** + - `msg`: Bytes type, used to receive file data transferred from FTP server to local. + +**Return Value** + +- Return string starting with `226`, indicating successful file download (e.g. `226 Transfer complete`), otherwise download failed. + +**Example** + +```python +path = 'usr/' # Root dir of module user partition is 'usr' +filename = 'ftp_file.txt' # Filename to download + +# Open and create a file +save_fp = open(path + filename, 'wb+') +# Get current path on server +server_path = ftp_obj.pwd() +# Establish download connection, save_fp.write is write file operation, passed as callback function +res = ftp_obj.retrlines('RETR ' + server_path + '/' + filename, save_fp.write) +# Download complete +msg = 'Down %s to device %s.' +if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True +else: + print(msg % (filename, 'falied')) + return False +``` + +## File Upload + +### `ftp.storbinary` + +```python +ftp.storbinary(cmd, fp, blocksize) +``` + +Upload file to FTP server in binary format. + +**Parameter** + +- `cmd` - Required parameter, transfer command, consist of `STOR + filename` (separated by spaces), string type. +- `fp` - Required parameter, local file handle. +- `blocksize` - Optional parameter, maximum bytes to read per file each time, default is `2048K`. + +**Return Value** + +- Return string starting with `226`, indicating successful file upload (e.g. `226 Transfer complete`), otherwise upload failed. + +**Example** + +```python +path = 'usr/' # Root dir of module user partition is 'usr' +filename = 'ftp_file.bin' + +# Check if file exists +if filename in uos.listdir('usr/'): + print('File exists') + with open(path + filename, 'rb') as fp: + # cmd should be STOR command. fp is a file object (opened in binary mode). + res = ftp.storbinary('STOR ' + filename, fp) + msg = 'Upload %s to FTP Server %s.' + if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True + else: + print(msg % (filename, 'falied')) + return False +else: + print('File path does not exist') +``` + +### `ftp.storlines` + +```python +ftp.storlines(cmd, fp) +``` + +Upload file to FTP server in ASCII format. + +**Parameter** + +- `cmd` - Required parameter, transfer command, consist of `STOR + filename` (separated by spaces), string type. +- `fp` - Required parameter, local file handle. + +**Return Value** + +- Return string starting with `226`, indicating successful file upload (e.g. `226 Transfer complete`), otherwise upload failed. + +**Example** + +```python +path = 'usr/' # Root dir of module user partition is 'usr' +filename = 'ftp_file.txt' + +# Check if file exists +if filename in uos.listdir('usr/'): + print('File exists') + with open(path + filename, 'rb') as fp: + # cmd should be STOR command. + res = ftp.storlines('STOR ' + filename, fp) + msg = 'Upload %s to FTP Server %s.' + if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True + else: + print(msg % (filename, 'falied')) + return False +else: + print('File path does not exist') +``` + +## Introduction to FTP Client Commands + +Following are commonly used FTP client commands: + +- CONNECT: Establish connection with FTP server. +- USER: Specify login username. +- PASS: Specify login password. +- LIST: List files and subdirectories in current directory on server. +- CWD: Change current working directory. +- PWD: Show path of current working directory. +- RETR: Download files from server to local computer. +- STOR: Upload local files to server. +- DELE: Delete files on server. +- MKD: Create new directories on server. +- RMD: Delete directories on server. +- RNFR: Specify file or directory to rename. +- RNTO: Specify renamed file or directory name. +- PASV: Enter passive mode for data transfer. +- TYPE: Specify data transfer type, e.g. ASCII or binary. +- SIZE: Get file size information on server. +- SYST: Get operating system type of server. +- NOOP: Null operation to keep control connection active. +- QUIT: Disconnect from server. \ No newline at end of file diff --git a/docs/API_reference/en/networklib/ntptime.md b/docs/API_reference/en/networklib/ntptime.md new file mode 100644 index 0000000000000000000000000000000000000000..516f7599513cdcb91854edee5a490866d895c20b --- /dev/null +++ b/docs/API_reference/en/networklib/ntptime.md @@ -0,0 +1,95 @@ +# ntptime - Network Time Protocol + +This feature is used for time synchronization. + +Note: You need to confirm with the carrier whether the current SIM card supports this feature. + + +### `ntptime.host` + +```python +ntptime.host +``` + +Returns the current NTP server address. Default value: "ntp.aliyun.com". + + +### `ntptime.sethost` + +```python +ntptime.sethost(host) +``` + +Sets NTP server address. + +* Parameter + +| Parameter | Type | Description | +| :-------- | :----- | ------------------ | +| host | String | NTP server address | + +* Return Value + +0 - Successful execution + +-1 - Failed execution + + +### `ntptime.settime` + +```python +ntptime.settime(timezone=0) +``` + +Synchronize NTP server time. + +* Parameter + +| Parameter | Type | Description | +| :------- | :----- | ------------- | +| timezone | Integer | Range: -12 to 12. Default value: 0. | + +* Return Value + +0 - Successful execution + +-1 - Failed execution + + + +**Example** + +```python +import ntptime +import log +import utime +import checkNet + + +''' +The following two global variables are required. You can modify the values of the following two global variables according to your actual projects. +''' +PROJECT_NAME = "QuecPython_NTP_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# Set the log output level. +log.basicConfig(level=log.INFO) +ntp_log = log.getLogger("NtpTime") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + ntp_log.info('Network connection successful!') + + # View the default NTP server address. + ntp_log.info(ntptime.host) + # Set NTP server address. + ntptime.sethost('pool.ntp.org') + + # Synchronize NTP server time. + ntptime.settime() + else: + ntp_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) +``` \ No newline at end of file diff --git a/docs/API_reference/en/networklib/request.md b/docs/API_reference/en/networklib/request.md new file mode 100644 index 0000000000000000000000000000000000000000..5403ca5402e51978690e0c3984df972943255e2e --- /dev/null +++ b/docs/API_reference/en/networklib/request.md @@ -0,0 +1,283 @@ +# request - HTTP Client + +The `request` feature is used for sending an HTTP request to a server, fetching data from a server, or submitting data to a server. Multiple request methods, including GET, POST, and PUT are supported. + +## HTTP Request + +### `request.get` + +```python +response = request.get(url) +``` + +Sends a GET request. + +**Parameter** + +- `url` - Required parameter. The server IP address in the request(Automatically identify http/https requests, and enable ssl on https). +- `data` - Optional parameter. Parameters to be carried in JSON format in the request. +- `headers` - Dictionary type. Optional parameter. The header information in the request. +- `decode` - Boolean type. Optional parameter. Decode the response result with UTF-8 after the request is successful. True: Decode. False: Not decode. Default value: True. Bytes will be returned if False is entered. This parameter is only used for *response.content*. +- `timeout` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `ipvtype` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `username` - Optional parameter. User name for user authentication, string type. +- `password` - Optional parameter. Password for user authentication, string type. +- `sizeof` - Optional parameter. The size of the data blocks in the buffer. Recommended value: 255–4096. Default value: 2048. The larger the value, the faster the read speed. Unit: byte. +- `ssl_params` - Optional parameter. When the URL is an https request, if the key needs to be passed in during SSL authentication, Format: {"cert": certificate_content, "key": private_content}, content is a string type. + +**Return Value** + +- A response object containing all information returned by the server, such as response status codes, response headers, and response bodies. + +**Example** + +```python +import request +import utime + +url = "http://www.example.com" +response = request.get(url) + +for i in response.text: + print(i);utime.sleep_ms(10) + +url = "https://www.example.com" +response = request.get(url) + +for i in response.text: + print(i);utime.sleep_ms(10) + +``` + +### `request.post` + +```python +response = request.post(url,data) +``` + +Sends a POST request. + +**Parameter** + +- `url` - Required parameter. The server IP address in the request(Automatically identify http/https requests, and enable ssl on https). +- `data` - Optional parameter. Parameters to be carried in JSON format in the request. +- `headers` - Dictionary type. Optional parameter. The header information in the request. +- `decode` - Boolean type. Optional parameter. Decode the response result with UTF-8 after the request is successful. True: Decode. False: Not decode. Default value: True. Bytes will be returned if False is entered. This parameter is only used for *response.content*. +- `timeout` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `ipvtype` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `username` - Optional parameter. User name for user authentication, string type. +- `password` - Optional parameter. Password for user authentication, string type. +- `sizeof` - Optional parameter. The size of the data blocks in the buffer. Recommended value: 255–4096. Default value: 2048. The larger the value, the faster the read speed. Unit: byte. +- `ssl_params` - Optional parameter. When the URL is an https request, if the key needs to be passed in during SSL authentication, Format: {"cert": certificate_content, "key": private_content}, content is a string type. + +**Return Value** + +- A response object containing all information returned by the server, such as response status codes, response headers, and response bodies. + +**Content-Type Introduction:** + +There are four types of data submitted in the POST method: + +- application/x-www-form-urlencoded: The form data is encoded in key/value pairs and is sent to the server. It is the default type for the data submission in the form. +- multipart/form-data: This type is required for uploading files in the form. +- application/json: JSON format. +- application/octet-stream: Binary data stream. This type is used for downloading files. + +**Example** + +```python +import request + +url = "http://httpbin.org/post" +data = {"key1": "value1", "key2": "value2", "key3": "value3"} +header = {'key1': 'value1', "key2": "value2", "key3": "value3"} +response = request.post(url, data=ujson.dumps(data), header) + +for i in response.text: + print(i) + +``` + +### `request.put` + +```python +response = request.put(url) +``` + +Sends a PUT request. + +**Parameter** + +- `url` - Required parameter. The server IP address in the request(Automatically identify http/https requests, and enable ssl on https). +- `data` - Optional parameter. Parameters to be carried in JSON format in the request. +- `headers` - Dictionary type. Optional parameter. The header information in the request. +- `decode` - Boolean type. Optional parameter. Decode the response result with UTF-8 after the request is successful. True: Decode. False: Not decode. Default value: True. Bytes will be returned if False is entered. This parameter is only used for *response.content*. +- `timeout` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `ipvtype` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `username` - Optional parameter. User name for user authentication, string type. +- `password` - Optional parameter. Password for user authentication, string type. +- `sizeof` - Optional parameter. The size of the data blocks in the buffer. Recommended value: 255–4096. Default value: 2048. The larger the value, the faster the read speed. Unit: byte. +- `ssl_params` - Optional parameter. When the URL is an https request, if the key needs to be passed in during SSL authentication, Format: {"cert": certificate_content, "key": private_content}, content is a string type. + +**Return Value** + +- A response object containing all information returned by the server, such as response status codes, response headers, and response bodies. + +### `request.head` + +```python +response = request.head(url) +``` + +Sends a HEAD request. + +**Parameter** + +- `url` - Required parameter. The server IP address in the request(Automatically identify http/https requests, and enable ssl on https). +- `data` - Optional parameter. Parameters to be carried in JSON format in the request. +- `headers` - Dictionary type. Optional parameter. The header information in the request. +- `decode `- Boolean type. Optional parameter. Decode the response result with UTF-8 after the request is successful. True: Decode. False: Not decode. Default value: True. Bytes will be returned if False is entered. This parameter is only used for *response.content*. +- `timeout` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `ipvtype` - Optional parameter. Timeout, Default value: 20. Unit: s. +- `username` - Optional parameter. User name for user authentication, string type. +- `password` - Optional parameter. Password for user authentication, string type. +- `sizeof` - Optional parameter. The size of the data blocks in the buffer. Recommended value: 255–4096. Default value: 2048. The larger the value, the faster the read speed. Unit: byte. +- `ssl_params` - Optional parameter. When the URL is an https request, if the key needs to be passed in during SSL authentication, Format: {"cert": certificate_content, "key": private_content}, content is a string type. + +**Return Value** + +- A response object containing all information returned by the server, such as response status codes, response headers, and response bodies. + +## Get Response + +After the `request` library sends a request, a response object will be returned which contains all information sent by the server, such as response status codes, response headers, and response bodies. + +### `response.status_code` + +Gets the request status codes. + +```python +response.status_code +``` + +**Return Value** + +- Integer type. The request status codes. + +**Example** + +```python +import request + +response = request.get("http://httpbin.org/get") +print(response.status_code) +``` + +### `response.headers` + +Gets the request header. + +```python +response.headers +``` + +**Return Value** + +- Dict type. The request header. + +**Example** + +```python +import request + +response = request.get("http://httpbin.org/get") +print(response.headers) +``` + +### `response.text` + +Gets the text data of the response body,You can directly release resources using `response.close` without reading the data. + +```python +response.text +``` + +**Return Value** + +- A generator object reading all returned text data through a for loop. + +**Example** + +```python +import request + +response = request.get("http://httpbin.org/get") +if True: + for i in response.text: + print(i) +else: + response.close() +``` + +### `response.content` + +Gets the response body. + +```python +response.content +``` + +**Return Value** + +- A generator object reading all returned response body data through a for loop. + +**Example** + +```python +import request + +response = request.get("http://httpbin.org/get") +for i in response.content: + print(i) +``` + +### `response.json` + +Gets the response body in JSON format. + +```python +response.json() +``` + +**Return Value** + +- The response data in dictionary type. + +**Example** + +```python +import request + +response = request.get("http://httpbin.org/get") +data = response.json() +print(data) +``` + +### `respnse.close` + +Proactively close the HTTP connection without reading data from the server to release resources. + +```python +response.close() +``` +**Return Value** + +- No return value + +**Example** +```python +import request + +response = request.get("http://httpbin.org/get") +response.close() +``` diff --git a/docs/API_reference/en/networklib/umqtt.md b/docs/API_reference/en/networklib/umqtt.md new file mode 100644 index 0000000000000000000000000000000000000000..790cfbadb6d3f4c96a6f29747f8489726fff4ddb --- /dev/null +++ b/docs/API_reference/en/networklib/umqtt.md @@ -0,0 +1,619 @@ +# umqtt - MQTT Protocol + +This feature is used to create MQTT clients to publish and subscribe to topics. + +> umqtt is implemented in Python source code. If the corresponding firmware version does not support it by default, users can use the source code [umqtt.py](https://github.com/QuecPython/umqtt) and put it in the default directory /usr. When using it, change from umqtt import MQTTClient to from usr.umqtt import MQTTClient. + +``` +QoS Level Description +In MQTT protocol, three levels of QoS are defined. +QoS0 – At most once. Lowest level. After sending the message, the sender does not care whether the message has been received by the receiver. +QoS1 – At least once. Middle level. The message is guaranteed to be received by the receiver at least once. +QoS2 – Only once. Highest level. The message is guaranteed to be received by the receiver only once. +``` + +## Initialize MQTT + +### `MQTTClient` + +```python +MQTTClient(client_id, server, port=0, user=None, password=None, keepalive=60, ssl=False, ssl_params={},reconn=True,version=4) +``` + +Creates MQTT clients. + +* Parameter + +| Parameter | Type | Description | +| ---------- | ------- | ------------------------------------------------------------ | +| client_id | String | Client ID. Each client ID is unique. | +| server | String | Server address, which can be an IP address or domain name. | +| port | Integer | Server port (optional). Default value: 1883. The default port of MQTT over SSL/TLS is 8883. | +| user | String | Username registered on the server (optional). | +| password | String | Password registered on the server (optional). | +| keepalive | Integer | Timeout of keep-alive (optional). Default value: 60. Unit: s. | +| ssl | bool | Enable or disable SSL/TSL encryption. | +| ssl_params | String | SSL/TLS parameter (optional). if the key needs to be passed in during SSL authentication, Format: {"cert": certificate_content, "key": private_content}, content is a string type.| +| reconn | bool | Enable or disable the internal reconnection mechanism (optional). Default value: True (enable). | +| version | Integer | The selected MQTT version (optional). version=3 indicates MQTTv3.1. Default value: 4. version=4 indicates MQTTv3.1.1. | + +* Return Value + +An MQTT client. + +## Set Callback Function + +### `MQTTClient.set_callback` + +```python +MQTTClient.set_callback(callback) +``` + + +Sets the callback function of receiving messages. + +* Parameter + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------- | +| callback | function | The callback function of receiving messages. | + +* Return Value + +None + +### `MQTTClient.error_register_cb` + +```python +MQTTClient.error_register_cb(callback) +``` + +Sets the callback function of error occurrence. When the MQTT internal thread is abnormal, the error message is returned by the callback function. The callback function can be called only when the internal reconnection is not enabled. + +* Parameter + +| Parameter | Type | Description | +| --------- | -------- | ------------------------------------------- | +| callback | function | The callback function of error occurrences. | + +* Return Value + +None + +Example + +```python +from umqtt import MQTTClient + +def err_cb(err): + print("thread err:") + print(err) + +c = MQTTClient("umqtt_client", "mq.tongxinmao.com", 18830) +c.error_register_cb(err_cb) +``` + +### `MQTTClient.set_last_will` + +```python +MQTTClient.set_last_will(topic,msg,retain=False,qos=0) +``` + +Sets the last will to be sent to the MQTT server. If a client ungracefully disconnects from the server without calling *MQTTClient.disconnect()*, the last will will be sent to other clients. + +* Parameter + +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------------------ | +| topic | String | Last-will topic. | +| msg | String | Last-will content | +| retain | bool | When *retain* = True, the MQTT broker will retain the message. Default value: False. | +| qos | Integer | Quality of Service, 0 or 1. | + +* Return Value + +None + +## MQTT Connection Related Features + +### `MQTTClient.connect` + +```python +MQTTClient.connect(clean_session=True) +``` + + +Connects to MQTT server. Failed connection leads to an MQTT exception. + +* Parameter + +| Parameter | Type | Description | +| ------------- | ---- | ------------------------------------------------------------ | +| clean_session | bool | Client session type, optional parameter. If this value is True, the MQTT server will delete all information about the client when the client disconnects from the MQTT server. If this value is False, the client session is persistent, that is, when the client disconnects from the MQTT server, the subscription and queuing information will be retained. Default value: False. | + +* Return Value + +0 – Successful execution + +Error message – Failed execution + +### `MQTTClient.disconnect` + +```python +MQTTClient.disconnect() +``` + +Disconnects from the MQTT server. + +* Parameter + +None + +* Return Value + +None + +### `MQTTClient.close` + +```python +MQTTClient.close() +``` + +Releases socket resources. (Please note the differences between *MQTTClient.disconnect()* and *MQTTClient.close()*, where *MQTTClient.close()* only releases socket resources but *MQTTClient.disconnect()* releases resources including threads.) + +Note: This method can be used only when the client needs to reconnect to the MQTT server. See ***Example of MQTT Reconnection After Ungraceful Disconnection*** below for details. Call *MQTTClient.disconnect()* to normally disconnect from the MQTT server. + +* Parameter + +None + +* Return Value + +None + +### `MQTTClient.ping` + +```python +MQTTClient.ping() +``` + +Pings to MQTT server to check the connection when *keepalive* is not 0. When *keepalive* is 0, this method is disabled. + +* Parameter + +None + +* Return Value + +None + +## Publish and Subscribe Related Features + +### `MQTTClient.publish` + +```python +MQTTClient.publish(topic,msg, retain=False, qos=0) +``` + +Publishes messages. + +* Parameter + +| Parameter | Type | Description | +| ----- | ----- | ------------------------------------------------------------ | +| topic | String | Message topic. | +| msg | String | Data to be sent. | +| retain | bool | Default value: False. If this value is set to True when you send a message, the message is retained.
The MQTT server retains the last received message with a RETAIN flag bit of True on the server. Whenever the MQTT client connects to the MQTT server and subscribes to a topic, if there is a Retained message under that topic, the MQTT server immediately pushes the Retained message to the client.
Note: The MQTT server will only save the last received message with the RETAIN flag bit of True for each topic, that is, if the MQTT server saves one retained message for a Topic, when the client publishes a new retained message, the original message on the server is overwritten. | +| qos | Integer | MQTT QoS, 0 or 1. Default value: 0.
0 – The sender sends a message only once.
1 – The sender sends a message at least once and guarantees that the message has been delivered to the MQTT broker. | + +* Return Value + +None + +### `MQTTClient.subscribe` + +```python +MQTTClient.subscribe(topic,qos) +``` + +Subscribes to MQTT topics. + +* Parameter + +| Parameter | Type | Description | +| ---- | ----- | ------------------------------------------------------------ | +| topic | String | topic | +| qos | Integer | MQTT QoS, 0 or 1. Default value: 0.
0 – The sender sends a message only once.
1 – The sender sends a message at least once and guarantees that the message has been delivered to the MQTT broker. | + +* Return Value + +None + +### `MQTTClient.check_msg` + +```python +MQTTClient.check_msg() +``` + +Checks whether the MQTT server has messages to be processed. + +* Parameter + +None + +* Return Value + +None + +### `MQTTClient.wait_msg` + +```python +MQTTClient.wait_msg() +``` + +Blocks waiting for a message response from the MQTT server. + +>If this method is called in a thread, it is necessary to ensure that the thread stack created is >= 16K. For details, please refer to the mqtt reconnection sample code. + +* Parameter + +None + +* Return Value + +None + +### `MQTTClient.get_mqttsta` + +```python +MQTTClient.get_mqttsta() +``` + +Gets MQTT connection status. + +Note: + + 1. BG95 series module does not support the API. + +2. If you call *MQTTClient.disconnect()* before calling *MQTTClient.get_mqttsta()*, -1 will be returned, because the created object resources are released. + +* Parameter + +None + +* Return Value + +0 – Successful connection + +1 – Connecting + +2 – Server connection closed + +-1 – Connection error + + + +**Example** + +```python +''' +@Author: Baron +@Date: 2020-04-24 +@LastEditTime: 2020-04-24 17:06:08 +@Description: example for module umqtt +@FilePath: example_mqtt_file.py +''' +from umqtt import MQTTClient +import utime +import log +import checkNet + + +''' +The following two global variables are required. You can modify the values of the following two global variables according to your actual projects. +''' +PROJECT_NAME = "QuecPython_MQTT_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# Set the log output level. +log.basicConfig(level=log.INFO) +mqtt_log = log.getLogger("MQTT") + + +state = 0 + +def sub_cb(topic, msg): + global state + mqtt_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + state = 1 + + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + mqtt_log.info('Network connection successful!') + + # Create an MQTT example. + c = MQTTClient("umqtt_client", "mq.tongxinmao.com", 18830) + # Set the callback function of receiving messages. + c.set_callback(sub_cb) + # Connect to the MQTT server. + c.connect() + # Subscribe to a topic. + c.subscribe(b"/public/TEST/quecpython") + mqtt_log.info("Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic" ) + # Publish a message. + c.publish(b"/public/TEST/quecpython", b"my name is Quecpython!") + mqtt_log.info("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython") + + while True: + c.wait_msg() # Blocking function of monitoring messages. + if state == 1: + break + # Disconnects from the MQTT server. + c.disconnect() + else: + mqtt_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +``` + +**Example of MQTT Reconnection After Ungraceful Disconnection** + +Note: + +1. The parameter *reconn* in the following example enables or disables the internal reconnection mechanism. Default value: True (enable). + +2. If you need to test or use the external reconnection mechanism, please refer to this example code below. Before testing, set reconn to False, otherwise, the internal reconnection mechanism will be used by default. + +```python +''' +@Author: Baron +@Date: 2020-04-24 +@LastEditTime: 2021-05-25 17:06:08 +@Description: example for module umqtt +@FilePath: example_mqtt_file.py +''' +''' +The following two global variables are required. You can modify the values of the following two global variables according to your actual projects. +The values of these two variables are printed before the user code is executed. +''' +import utime +import log +import net +import _thread +import checkNet +import dataCall +import uos +from umqtt import MQTTClient + +PROJECT_NAME = "QuecPython_MQTT_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# Reclaim the thread resource through the status after calling MQTTClient.disconnect(). +TaskEnable = True +# Set the log output level. +log.basicConfig(level=log.INFO) +mqtt_log = log.getLogger("MQTT") + + +# Encapsulate MQTT so it can support more custom logic. +class MqttClient(): + ''' + mqtt init + ''' + + # Note: The parameter reconn enables or disables the internal reconnection mechanism. Default value: True (enable). + # If you need to test or use the external reconnection mechanism, please refer to this example code below. Before testing, set reconn to False, otherwise, the internal reconnection mechanism will be used by default. + def __init__(self, clientid, server, port, user=None, password=None, keepalive=0, ssl=False, ssl_params={}, + reconn=True): + self.__clientid = clientid + self.__pw = password + self.__server = server + self.__port = port + self.__uasename = user + self.__keepalive = keepalive + self.__ssl = ssl + self.__ssl_params = ssl_params + self.topic = None + self.qos = None + # Network status flag. + self.__nw_flag = True + # Create a mutex. + self.mp_lock = _thread.allocate_lock() + # Create a class to initialize the MQTT object. + self.client = MQTTClient(self.__clientid, self.__server, self.__port, self.__uasename, self.__pw, + keepalive=self.__keepalive, ssl=self.__ssl, ssl_params=self.__ssl_params, + reconn=reconn) + + def connect(self): + ''' + Connect to the MQTT server. + ''' + self.client.connect() + # Register the callback function of network status. When the network status changes, the function will be called. + flag = dataCall.setCallback(self.nw_cb) + if flag != 0: + # The network callback registration failed. + raise Exception("Network callback registration failed") + + def set_callback(self, sub_cb): + ''' + Set the callback function of receiving messages. + ''' + self.client.set_callback(sub_cb) + + def error_register_cb(self, func): + ''' + Set the callback function of receiving MQTT thread error occurrence. + ''' + self.client.error_register_cb(func) + + def subscribe(self, topic, qos=0): + ''' + Subscribe to topics. + ''' + self.topic = topic # Save the topic. Multiple topics can be saved by a list. + self.qos = qos # Save the QoS. + self.client.subscribe(topic, qos) + + def publish(self, topic, msg, qos=0): + ''' + Publish a message. + ''' + self.client.publish(topic, msg, qos) + + def disconnect(self): + ''' + Disconnect from the MQTT server. + ''' + global TaskEnable + # Close the monitoring thread of wait_msg. + TaskEnable = False + # Disconnect from the MQTT server and release the resources. + self.client.disconnect() + + def reconnect(self): + ''' + MQTT reconnection mechanism (The following example is for your reference only and you can adjust based on actual needs.) + Note: 1. If other services need to be restarted after the client reconnects to the server, determine whether to release the resources of the previous services before restarting the services. + 2. This section needs to be added based on the actual business logic, and this example only covers the process that the client resubscribes to topics after reconnecting to the MQTT server. + ''' + # Determine whether the lock has been acquired. + if self.mp_lock.locked(): + return + self.mp_lock.acquire() + # Close the previous connection before reconnecting to release resources. Please note the differences between *MQTTClient.disconnect()* and *MQTTClient.close()*, where MQTTClient.close() only releases socket resources but *MQTTClient.disconnect()* releases resources including threads. + self.client.close() + # Reconnect to the MQTT server. + while True: + net_sta = net.getState() # Get network registration information. + if net_sta != -1 and net_sta[1][0] == 1: + call_state = dataCall.getInfo(1, 0) # Get data call information. + if (call_state != -1) and (call_state[2][0] == 1): + try: + # The network is normal. Reconnect to the MQTT server. + self.connect() + except Exception as e: + # Reconnection to the MQTT server failed. Try again 5 s later. + self.client.close() + utime.sleep(5) + continue + else: + # The network is unrestored. Please wait. + utime.sleep(10) + continue + # Connect to the MQTT server successfully and subscribe to the topic. + try: + # Multiple topics can be saved by a list. Traverse the list to resubscribe the topic. + if self.topic is not None: + self.client.subscribe(self.topic, self.qos) + self.mp_lock.release() + except: + # Subscription failed. Reconnect to the MQTT server. + self.client.close() + utime.sleep(5) + continue + else: + utime.sleep(5) + continue + break # Stop loop. + # Exit and reconnect. + return True + + def nw_cb(self, args): + ''' + Call the callback function of data call. + ''' + nw_sta = args[1] + if nw_sta == 1: + # Network connected. + mqtt_log.info("*** network connected! ***") + self.__nw_flag = True + else: + # Network disconnected. + mqtt_log.info("*** network not connected! ***") + self.__nw_flag = False + + def __listen(self): + while True: + try: + if not TaskEnable: + break + self.client.wait_msg() + except OSError as e: + # Determine whether the network is disconnected. + if not self.__nw_flag: + # Reconnect after the network is restored from disconnection. + self.reconnect() + # Reconnect when the socket status is abnormal. + elif self.client.get_mqttsta() != 0 and TaskEnable: + self.reconnect() + else: + # You can call the raise method to return an exception or -1. + return -1 + + def loop_forever(self): + task_stacksize =_thread.stack_size() + name,platform = uos.uname()[1].split("=",1) + if platform == "EC600E" or platform == "EC800E": + _thread.stack_size(8 * 1024) + elif platform == "FCM362K": + _thread.stack_size(3 * 1024) + else: + _thread.stack_size(16 * 1024) + # Before creating a thread, modify the thread stack space according to the platform. + _thread.start_new_thread(self.__listen, ()) + # After the thread is created successfully, the platform thread stack default size is restored. + _thread.stack_size(task_stacksize) + +if __name__ == '__main__': + ''' + When running this routine manually, you can remove this delay. If you change the file name of the routine to main.py, you need to add this delay when you want to start the routine automatically. Otherwise, you cannot see the information printed in poweron_print_once() below from the CDC interface. + ''' + utime.sleep(5) + checknet.poweron_print_once() + ''' + If the user program contains network-related codes, it must execute wait_network_connected() to wait for the network to be ready (successful data call); If it is a network-independent code, you can mask wait_network_connected(). + 【This routine must retain the following line.】 + ''' + checknet.wait_network_connected() + + def sub_cb(topic, msg): + # global state + mqtt_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + + c = MqttClient("umqtt_client_753", "mq.tongxinmao.com", 18830, reconn=False) + + def err_cb(error): + ''' + Set the callback function of receiving MQTT thread error occurrence. + + ''' + mqtt_log.info(error) + c.reconnect() # Reconnect to MQTT server after error occurrences. + + # c = MqttClient("umqtt_client_753", "mq.tongxinmao.com", 18830, reconn=False) + # Set the callback function of receiving messages. + c.set_callback(sub_cb) + # Set the callback function of error occurrence. + c.error_register_cb(err_cb) + # Connect to the MQTT server. + c.connect() + # Subscribe to topics. + c.subscribe(b"/public/TEST/quecpython758") + mqtt_log.info("Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic") + # Publish a message. + c.publish(b"/public/TEST/quecpython758", b"my name is Quecpython!") + mqtt_log.info("Publish topic: /public/TEST/quecpython758, msg: my name is Quecpython") + # Monitor MQTT messages. + c.loop_forever() + # Wait for 5 s to receive the message. + # Note: Comment c.disconnect () and utime.sleep(5) if you want to test the reconnection mechanism, including server disconnection. + # utime.sleep(5) + # Disconnect to the MQTT server. + # c.disconnect() +``` \ No newline at end of file diff --git a/docs/API_reference/en/networklib/uping.md b/docs/API_reference/en/networklib/uping.md new file mode 100644 index 0000000000000000000000000000000000000000..0ce859bf8f279ccfed618169e4c5ac375be219b4 --- /dev/null +++ b/docs/API_reference/en/networklib/uping.md @@ -0,0 +1,53 @@ +# class uping - Ping Package + +This class pings IPv4 request packages. + +> Note: 1. It may occur that the socket cannot be set up at the host address, causing a connection error. 2. Determine the ping period by initializing `COUNT` and `INTERVAL`. + +**Example** + +```python +# Mode 1 +# Print the output mode. +import uping +uping.ping('baidu.com') + +# The following lists the output of uping.start(), without return values. +#72 bytes from 49.49.48.46: icmp_seq=1, ttl=53, time=1169.909000 ms +#72 bytes from 49.49.48.46: icmp_seq=2, ttl=53, time=92.060000 ms +#72 bytes from 49.49.48.46: icmp_seq=3, ttl=53, time=94.818000 ms +#72 bytes from 49.49.48.46: icmp_seq=4, ttl=53, time=114.879000 ms +#4 packets transmitted, 4 packets received, 0 packet loss +#round-trip min/avg/max = 92.06000000000001/367.916/1169.909 ms + + +# Mode 2 +# Set quiet to get the output. +import uping +result = uping.ping('baidu.com', quiet=True) +# The corresponding data can be gotten in the result. +# result(tx=4, rx=4, losses=0, min=76.93899999999999, avg=131.348, max=226.697) +``` + +## Constructor + +### `uping.ping` + +```python +uping.ping(HOST, SOURCE=None, COUNT=4, INTERVAL=1000, SIZE=64, TIMEOUT=5000, quiet=False) +``` + +Pings packages periodically. + +**Parameter** + +| Parameter | Type | Description | +| --------- | ---- | ------------------------------------------------------------ | +| HOST | str | The IP address to be pinged, such as "baidu.com". | +| SOURCE | str | Source IP address, used for binding and with no need for input. | +| COUNT | int | Default value: 4. Unit: time. | +| INTERVAL | int | Interval. Default value: 1000. Unit: ms. | +| SIZE | int | Size of the package read every time. Default value: 64. Unit: byte. No change is required. | +| TIMEOUT | int | Timeout. Default value: 5000. Unit: ms. | +| quiet | bool | False: print and output directly.
True: The default value printed by *start* is converted to an object and returned.
Default: false. | + diff --git a/docs/API_reference/en/networklib/ussl.md b/docs/API_reference/en/networklib/ussl.md new file mode 100644 index 0000000000000000000000000000000000000000..8e40d2bea44f55948422574a669f6482f3f185f9 --- /dev/null +++ b/docs/API_reference/en/networklib/ussl.md @@ -0,0 +1,178 @@ +# ussl – SSL/TLS Protocol + +ussl realizes the encrypted communication using TLS/SSL protocol, mainly for unidirectional and bidirectional authentication. + + + +## Create Secure Channel over SSL + +### `ussl.wrap_socket` + +```python +ussl.wrap_socket(sock,server_hostname=None,cert=None,key=None) +``` + +**Parameter** + +- `sock` – The usocket.socket object to be wrapped. Required parameter. + +- `server_hostname` – String type. Server IP address. Optional parameter. + +- `cert` – String type. Digital certificate. Optional parameter. + +- `key` – String type. Private key. Optional parameter. + +**Return Value** + +A wrapped `usocket.socket` object. + + + +**Example** + +```python +# Import ussl +# -*- coding: UTF-8 -*- +import ussl +import usocket +import log +import utime +import checkNet + +''' +The following two global variables are required. You can modify the values of the following two global variables according to your actual projects. +''' +PROJECT_NAME = "QuecPython_Socket_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# Set the log output level. +log.basicConfig(level=log.INFO) +socket_log = log.getLogger("SOCKET") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + socket_log.info('Network connection successful!') + # 1. Unidirectional-authentication description + # Create a socket instance. + sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) + # Resolve a domain name. + sockaddr=usocket.getaddrinfo('myssl.com', 443)[0][-1] + # Set up a connection. + sock.connect(sockaddr) + # Create Secure Channel over SSL, supported by the server. + sock = ussl.wrap_socket(sock, server_hostname="myssl.com") + # Send messages to the server. + ret = sock.write('GET / HTTP/1.0\r\nHost: myssl.com\r\nAccept-Encoding: deflate\r\n\r\n') + socket_log.info('write %d bytes' % ret) + # Receive the messages from the server. + data=sock.read(256) + socket_log.info('read %s bytes:' % len(data)) + socket_log.info(data.decode()) + + # Close the connection. + sock.close() + socket_log.info('--------------------Socket Ussl End-------------------') + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +# 2. Bidirectional-authentication description +cert = "Certificate" +key = "Private Key" +sock = ussl.wrap_socket(sock, server_hostname="myssl.com", cert=cert, key=key) + +``` + + + +## List of Supported Cipher Suites + +``` +SSL version description: +ussl supports SSL 3.0 up to TLS 1.2 and DTLS communication. +``` + +| Cipher Suite | +| ------------------------------------------------------ | +| TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca9) | +| TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xccaa) | +| TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8) | +| TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c) | +| TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030) | +| TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x009f) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CCM (0xc0ad) | +| TLS_DHE_RSA_WITH_AES_256_CCM (0xc09f) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 (0xc024) | +| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (0xc028) | +| TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 (0x006b) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a) | +| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014) | +| TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 (0xc0af) | +| TLS_DHE_RSA_WITH_AES_256_CCM_8 (0xc0a3) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc087) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc08b) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc07d) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc073) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc077) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 (0x00c4) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA (0x0088) | +| TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b) | +| TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f) | +| TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x009e) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CCM (0xc0ac) | +| TLS_DHE_RSA_WITH_AES_128_CCM (0xc09e) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (0xc023) | +| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (0xc027) | +| TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 (0x0067) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009) | +| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013) | +| TLS_DHE_RSA_WITH_AES_128_CBC_SHA (0x0033) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (0xc0ae) | +| TLS_DHE_RSA_WITH_AES_128_CCM_8 (0xc0a2) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc086) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc08a) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc07c) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc072) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc076) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0x00be) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA (0x0045) | +| TLS_RSA_WITH_AES_256_GCM_SHA384 (0x009d) | +| TLS_RSA_WITH_AES_256_CCM (0xc09d) | +| TLS_RSA_WITH_AES_256_CBC_SHA256 (0x003d) | +| TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) | +| TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 (0xc032) | +| TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 (0xc02a) | +| TLS_ECDH_RSA_WITH_AES_256_CBC_SHA (0xc00f) | +| TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02e) | +| TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 (0xc026) | +| TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA (0xc005) | +| TLS_RSA_WITH_AES_256_CCM_8 (0xc0a1) | +| TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc07b) | +| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 (0x00c0) | +| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA (0x0084) | +| TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc08d) | +| TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc079) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc089) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc075) | +| TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) | +| TLS_RSA_WITH_AES_128_CCM (0xc09c) | +| TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003c) | +| TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) | +| TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 (0xc031) | +| TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 (0xc029) | +| TLS_ECDH_RSA_WITH_AES_128_CBC_SHA (0xc00e) | +| TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02d) | +| TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 (0xc025) | +| TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA (0xc004) | +| TLS_RSA_WITH_AES_128_CCM_8 (0xc0a0) | +| TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc07a) | +| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0x00ba) | +| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA (0x0041) | +| TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc08c) | +| TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc078) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc088) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc074) | +| TLS_EMPTY_RENEGOTIATION_INFO_SCSV (0x00ff) | \ No newline at end of file diff --git a/docs/API_reference/en/networklib/uwebsocket.md b/docs/API_reference/en/networklib/uwebsocket.md new file mode 100644 index 0000000000000000000000000000000000000000..6a20ae986c15ee87263a5ddc203315a129a148c6 --- /dev/null +++ b/docs/API_reference/en/networklib/uwebsocket.md @@ -0,0 +1,87 @@ +# uwebsocket – WebSocket Client + +This feature establishes a WebSocket connection. + + + +## Connect to Client + +### uwebsocket.Client.connect + +```python +ws_client = uwebsocket.Client.connect(url, headers=None, debug=False) +``` + +**Parameter** + +* `url` – String type. WebSocket connection URL, usually in the form of "ws://xxx/" or "wss://xxx/". +* `headers` – Dict type. The additional header to be added, used in the scenarios where both the standard header and the additional header passed by users are allowed. +* `debug` – Bool type. True – Output logs. False – Not output logs. Default value: False. + + + +## Send Data + +### ws_client.send + +```python +ws_client.send(msg) +``` + +**Parameter** +* `msg` – String/Byte type. The data to be sent. + + + +## Receive Data + +### ws_client.recv + +```python +ws_client.recv() +``` + +**Return Value** + +* `result `– String/Byte type. The returned result. When this value is null or None, the connection is closed. + + + +## Close Connection + +### ws_client.close + +```python +ws_client.close() +``` + + + +**Example** + +```python +import uwebsocket +import _thread + + +def recv(cli): + while True: + # Receive data in an infinite loop. + recv_data = cli.recv() + print("recv_data = {}".format(recv_data)) + if not recv_data: + # The server or client closes the connection. + print("cli close") + client.close() + break + + +# Create a WebSocket client. "debug=True" indicates outputing logs. You need to customize the IP address, port or domain name. +client = uwebsocket.Client.connect('ws://xxx/', debug=True) + +# Receive data in threads. +_thread.start_new_thread(recv, (client,)) + +# Send data. +client.send("this is a test msg") +``` \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/README.md b/docs/API_reference/en/peripherals/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3ce210eacb184e5928b527a9d44d9fe1040c985e --- /dev/null +++ b/docs/API_reference/en/peripherals/README.md @@ -0,0 +1,11 @@ +# QuecPython peripheral interface + +> QuecPython peripheral interface library includes GPIO, UART and other hardware interface related functional components + +This article describes the modules in the QuecPython peripheral interface library. + +## List of QuecPython peripheral interface libraries + +- [machine - Hardware related functions](./machine.md) +- [misc - other](./misc.md) +- [ethernet - Ethernet related functions](./ethernet.md) \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/ethernet.CH395.md b/docs/API_reference/en/peripherals/ethernet.CH395.md new file mode 100644 index 0000000000000000000000000000000000000000..5e25a8e75b44fcfc7a8ad73ebb2c595893d9f84d --- /dev/null +++ b/docs/API_reference/en/peripherals/ethernet.CH395.md @@ -0,0 +1,182 @@ +# class CH395 - CH395 Ethernet NIC Control + +This class controls Ethernet NIC devices of `CH395`. + +> Currently, only EC600N module series support this feature. + +## Constructor + +### `ethernet.CH395` + +```python +class ethernet.CH395(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +Loads CH395 driver, initializes CH395 Ethernet NIC and returns CH395 NIC object. + +**Parameter:** + +- `mac` - Byte stream. MAC address with a length of 6 bytes. +- `ip` - IP address of Ethernet NIC. The default value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The default value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The default value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. +- `spi_port` - Connect to [SPI port](./machine.SPI.md) of `CH395`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `SPI1` port. +- `spi_cs_pin` - Connect to `SPI` chip select [GPIO pin](./machine.Pin.md) of `CH395`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO4`. +- `extint_pin` - Connect to external interrupt [GPIO pin](./machine.Pin.md) of `CH395`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO24`. +- `reset_pin` - Connect to reset [GPIO pin](./machine.Pin.md) of `CH395`. It indicates that the last configured value is used and the default configuration in the program is `Pin.GPIO30`. +- `work_mode` - Configure Ethernet working mode. The default mode is terminal mode. `0` and `1` respectively represents terminal mode and gateway mode. Terminal mode indicates that the module is used as a terminal device to connect to a network supply device to access the network. Gateway mode indicates that the module is used as a gateway to provide network access for external devices through LTE network. + +## Methods + +### `CH395.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +Configures NIC static IP Address. + +**Parameter:** + +- `ip` - IP address of Ethernet NIC. The value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +* Example + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `CH395.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +Configures NIC DNS server. + +**Parameter:** + +- `primary_dns` - Primary address of `DNS` server. +- `secondary_dns` - Secondary address of `DNS` server. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `CH395.set_up` + +```python +nic.set_up() +``` + +Enables NIC and then NIC processes network interfaces and messages normally. + +### `CH395.set_down` + +```python +nic.set_down() +``` + +Disables NIC and then NIC no longer processes network interfaces and messages. + +### `CH395.dhcp` + +```python +nic.dhcp() +``` + +Obtains dynamic IP. This method is used in the terminal mode so that IP information can be automatically obtained. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +### `CH395.ipconfig` + +```python +nic.ipconfig() +``` + +Obtains NIC network information. MAC address, host name, IP address type, IP address, subnet mask, gateway address and DNS server address can be obtained through this method. + +**Return Value:** + +Returns list type. + +The format is as follows: + +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)]. + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `mac` | `str` | `mac` address and the format is`'XX-XX-XX-XX-XX-XX'`. | +| `hostname`| `str` | NIC name | +| `iptype` | `str` | `ip` type. `4` indicates `IPv4` and `6` indicates `IPv6`. Currently, only `IPv4` is supported. | +| `ip` | `str` | IP address | +| `subnet` | `str` | Subnet mask | +| `gateway`| `str` | Gateway address | +| `primary_dns`| `str` | Primary address of DNS server | +| `secondary_dns`| `str` | Secondary address of DNS server | + +### `CH395.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +Configures the default NIC. + +**Parameter:** + +- `ip` - Default NIC IP address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_default_NIC('192.168.1.100') +``` + +### `CH395.status` + +```python +nic.status() +``` + +Obtains NIC current status. + +**Return Value:** + +Tuple type. + +The format is as follows: + +(dev, active, link). + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `dev` | `bool` | Whether NIC device is normally connected. `True` and `False` respectively indicate that NIC device is connected and is not connected. | +| `active`| `bool` | Whether NIC is activated. `True` and `False` respectively indicate enable and disable, which correspond to `set_up` and `set_down`. | +| `link` | `bool` | Whether the network cable of NIC is connected. `True` and `False` respectively indicate the network cable is connected and is not connected. | \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/ethernet.DM9051.md b/docs/API_reference/en/peripherals/ethernet.DM9051.md new file mode 100644 index 0000000000000000000000000000000000000000..a90428585cb26e346a4e825b2d5a59fe982f4b14 --- /dev/null +++ b/docs/API_reference/en/peripherals/ethernet.DM9051.md @@ -0,0 +1,138 @@ +# class DM9051 - DM9051 Ethernet NIC Control + +This class controls Ethernet NIC devices of `DM9051`. + +> Currently, only the EC600N/EG912N/EG915N series and EC800MCN_LE are supported. + +## Constructor + +### `ethernet.DM9051` + +```python +class ethernet.DM9051(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +Loads DM9051 driver, initializes DM9051 Ethernet NIC and returns DM9051 NIC object. + +**Parameter:** + +- `mac` - Byte stream. MAC address with a length of 6 bytes. +- `ip` - IP address of Ethernet NIC. The default value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The default value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The default value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. +- `spi_port` - Connect to [SPI port](./machine.SPI.md) of `DM9051`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `SPI1` port. +- `spi_cs_pin` - Connect to `SPI` chip select [GPIO pin](./machine.Pin.md) of `DM9051`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO13`. +- `extint_pin` - Connect to external interrupt [GPIO pin](./machine.Pin.md) of `DM9051`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO19`. +- `reset_pin` - Connect to reset [GPIO pin](./machine.Pin.md) of `DM9051`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO17`. +- `work_mode` - Configure Ethernet working mode. The default mode is terminal mode. `0` and `1` respectively represents terminal mode and gateway mode. Terminal mode indicates that the module is used as a terminal device to connect to a network supply device to access the network. Gateway mode indicates that the module is used as a gateway to provide network access for external devices through LTE network. + +> The default value varies from platform to platform. It is recommended to define the available GPIO usage + +## Methods + +### `DM9051.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +Configures NIC static IP Address. + +**Parameter:** + +- `ip` - IP address of Ethernet NIC. The value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +* Example + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `DM9051.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +Configures NIC DNS server. + +**Parameter:** + +- `primary_dns` - Primary address of `DNS` server . +- `secondary_dns` - Secondary address of `DNS` server. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `DM9051.set_up` + +```python +nic.set_up() +``` + +Enables NIC and then NIC processes network interfaces and messages normally. + +### `DM9051.set_down` + +```python +nic.set_down() +``` + +Disables NIC and then NIC no longer processes network interfaces and messages. + +### `DM9051.dhcp` + +```python +nic.dhcp() +``` + +Obtains dynamic IP. This method is used in the terminal mode so that IP information can be automatically obtained. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +### `DM9051.ipconfig` + +```python +nic.ipconfig() +``` + +Obtains NIC network information. MAC address, host name, IP address type, IP address, subnet mask, gateway address and DNS server address can be obtained through this method. + +**Return Value:** + +List type. + +The format is as follows: + + [(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)]. + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `mac` | `str` | `mac` address and the format is`'XX-XX-XX-XX-XX-XX'`. | +| `hostname`| `str` | NIC name | +| `iptype` | `str` | `ip` type. `4` indicates `IPv4` and `6` indicates `IPv6`. Currently, only `IPv4` is supported. | +| `ip` | `str` | IP address | +| `subnet` | `str` | Subnet mask | +| `gateway`| `str` | Gateway address | +| `primary_dns`| `str` | Primary address of DNS server | +| `secondary_dns`| `str` | Secondary address of DNS server | diff --git a/docs/API_reference/en/peripherals/ethernet.W5500.md b/docs/API_reference/en/peripherals/ethernet.W5500.md new file mode 100644 index 0000000000000000000000000000000000000000..b3d41e56f61287e9926732886dd4389dd1257c08 --- /dev/null +++ b/docs/API_reference/en/peripherals/ethernet.W5500.md @@ -0,0 +1,163 @@ +# class W5500 - W5500 Ethernet NIC Control + +This class controls Ethernet NIC devices of `W5500`. + +> Currently, only EC600N and EC600U module series support this feature. + + +## Constructor + +### `ethernet.W5500` + +```python +class ethernet.W5500(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +Loads W5500 driver, initializes W5500 Ethernet NIC and returns W5500 NIC object. + +**Parameter:** + +- `mac` - Byte stream. MAC address with a length of 6 bytes. +- `ip` - IP address of Ethernet NIC. The default value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The default value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The default value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. +- `spi_port` - Connect to [SPI port](./machine.SPI.md) of `W5500`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `SPI1` port. +- `spi_cs_pin` - Connect to `SPI` chip select [GPIO pin](./machine.Pin.md) of `W5500`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO34`. +- `extint_pin` - Connect to external interrupt [GPIO pin](./machine.Pin.md) of `W5500`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO19`. +- `reset_pin` - Connect to reset [GPIO pin](./machine.Pin.md) of `W5500`. The default value is `-1`, indicating that the last configured value is used and the default configuration in the program is `Pin.GPIO17`. +- `work_mode` - Configure Ethernet working mode. The default mode is terminal mode. `0` and `1` respectively represents terminal mode and gateway mode. Terminal mode indicates that the module is used as a terminal device to connect to a network supply device to access the network. Gateway mode indicates that the module is used as a gateway to provide network access for external devices through LTE network. + +> Note: Do not use the hardware CS pin of spi_port. Instead, select another GPIO pin as the CS pin. + +## Methods + +### `W5500.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +Configures NIC static IP Address. + +**Parameter:** + +- `ip` - IP address of Ethernet NIC. The value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +* Example + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `W5500.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +Configures NIC DNS server. + +**Parameter:** + +- `primary_dns` - Primary address of `DNS` server. +- `secondary_dns` - Secondary address of `DNS` server. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `W5500.set_up` + +```python +nic.set_up() +``` + +Enables NIC and then NIC processes network interfaces and messages normally. + +### `W5500.set_down` + +```python +nic.set_down() +``` + +Disables NIC and then NIC no longer processes network interfaces and messages. + +### `W5500.dhcp` + +```python +nic.dhcp() +``` + +Obtains dynamic IP. This method is used in the terminal mode so that IP information can be automatically obtained. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +### `W5500.ipconfig` + +```python +nic.ipconfig() +``` + +Obtains NIC network information. MAC address, host name, IP address type, IP address, subnet mask, gateway address and DNS server address can be obtained through this method. + +**Return Value:** + +List type. + +The format is as follows: + + [(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)]. + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `mac` | `str` | `mac` address and the format is`'XX-XX-XX-XX-XX-XX'`. | +| `hostname`| `str` | NIC name | +| `iptype` | `str` | `ip` type. `4` indicates `IPv4` and `6` indicates `IPv6`. Currently, only `IPv4` is supported. | +| `ip` | `str` | IP address | +| `subnet` | `str` | Subnet mask | +| `gateway`| `str` | Gateway address | +| `primary_dns`| `str` | Primary address of DNS server | +| `secondary_dns`| `str` | Secondary address of DNS server | + +### `W5500.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +Configures the default NIC. + +**Parameter:** + +- `ip` - Default NIC IP address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_default_NIC('192.168.1.100') +``` diff --git a/docs/API_reference/en/peripherals/ethernet.YT8512H.md b/docs/API_reference/en/peripherals/ethernet.YT8512H.md new file mode 100644 index 0000000000000000000000000000000000000000..a3018f43b25f150e715890c33ac5220cffda6c92 --- /dev/null +++ b/docs/API_reference/en/peripherals/ethernet.YT8512H.md @@ -0,0 +1,177 @@ +# class YT8512H - YT8512H PHY Control + +This class controls Ethernet NIC devices of `YT8512H and SZ18201`. + +> Currently, only EC600A module series support this feature. + +## Constructor + +### `ethernet.YT8512H` + +```python +class ethernet.YT8512H(mac, ip='', subnet='', gateway='') +``` + +Loads YT8512H driver, initializes YT8512H phy device and returns YT8512H NIC object. + +**Parameter:** + +- `mac` - Byte stream. MAC address with a length of 6 bytes. +- `ip` - IP address of Ethernet NIC. The default value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The default value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The default value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. + +## Methods + +### `YT8512H.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +Configures NIC static IP Address. + +**Parameter:** + +- `ip` - `ip` address of Ethernet NIC. The value is an empty string'', indicating that the default IP address is `192.168.1.100` in the program. +- `subnet` - Subnet mask address of Ethernet NIC. The value is an empty string'', indicating that `255.255.255.0` is used as the subnet mask. +- `gateway` - Gateway address of Ethernet NIC. The value is an empty string'', indicating that the last bit of IP address is replaced with `1` as the gateway address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +* Example + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `YT8512H.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +Configures NIC DNS server. + +**Parameter:** + +- `primary_dns` - Primary address of `DNS` server. +- `secondary_dns` - Secondary address of `DNS` server. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `YT8512H.set_up` + +```python +nic.set_up() +``` + +Enables NIC and then NIC processes network interfaces and messages normally. + +### `YT8512H.set_down` + +```python +nic.set_down() +``` + +Disables NIC and then NIC no longer processes network interfaces and messages. + +### `YT8512H.dhcp` + +```python +nic.dhcp() +``` + +Obtains dynamic IP. This method is used in the terminal mode so that IP information can be automatically obtained. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +### `YT8512H.ipconfig` + +```python +nic.ipconfig() +``` + +Obtains NIC network information. MAC address, host name, IP address type, IP address, subnet mask, gateway address and DNS server address can be obtained through this method. + +**Return Value:** + +List type. + +The format is as follows: + +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)]. + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `mac` | `str` | `mac` address and the format is`'XX-XX-XX-XX-XX-XX'`. | +| `hostname`| `str` | NIC name | +| `iptype` | `str` | `ip` type. `4` indicates `IPv4` and `6` indicates `IPv6`. Currently, only `IPv4` is supported. | +| `ip` | `str` | IP address | +| `subnet` | `str` | Subnet mask | +| `gateway`| `str` | Gateway address | +| `primary_dns`| `str` | Primary address of DNS server | +| `secondary_dns`| `str` | Secondary address of DNS server | + +### `YT8512H.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +Configures the default NIC. + +**Parameter:** + +- `ip` - Default NIC IP address. + +**Return Value:** + +0 - Successful execution + +Other values - Failed execution + +**Example:** + +```python +nic.set_default_NIC('192.168.1.100') +``` + +### `YT8512H.status` + +```python +nic.status() +``` + +Obtains NIC current status. + +**Return Value:** + +Tuple type. + +The format is as follows: + +(dev, active, link). + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `dev` | `bool` | Whether NIC device is normally connected. `True` and `False` respectively indicate that NIC device is connected and is not connected. | +| `active`| `bool` | Whether NIC is activated. `True` and `False` respectively indicate enable and disable, which correspond to `set_up` and `set_down`. | +| `link` | `bool` | Whether the network cable of NIC is connected. `True` and `False` respectively indicate the network cable is connected and is not connected. | diff --git a/docs/API_reference/en/peripherals/ethernet.md b/docs/API_reference/en/peripherals/ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..3e5c6e8ceb6677c66fd265d5daec9c723c0cecd7 --- /dev/null +++ b/docs/API_reference/en/peripherals/ethernet.md @@ -0,0 +1,86 @@ +# ethernet - Ethernet Driver +`ethernet` module contains features related to Ethernet control and network configuration, and provides unified management for different types of Ethernet NIC. + +**Example:** + +This section introduces the initialization process of NIC in the terminal mode, gateway mode and static IP address configuration respectively based on different application scenarios. + + +> 1. The following example is only for NIC application configuration on the module. Ethernet NICs can be normally used after the corresponding operation is performed on the peer device. +> 2. Some NICs are not applicable to the following examples. Please use NICs according to the corresponding instructions for different NIC drivers. + + +Terminal mode: + +```python +# In the terminal mode, the module connects to the external network through the Ethernet interface. For example, the W5500 network interface is connected to the router and obtains IP information through dynamic host configuration protocol (DHCP), so that the module can connect to the external network through this network interface. + +import ethernet + +# Loads the corresponding NIC driver and initializes the relevant configuration of NIC. Replaces the driver with the actual corresponding NIC driver. +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# Obtains the static IP address. +nic.dhcp() +print(nic.ipconfig()) + +# Now starts other network services and accesses the network through Ethernet. +... + +``` + +Gateway mode: + +```python +# In the gateway mode, the module connects to the externel network with LTE network. For example, the w5500 network interface is connected to a computer and the computer configures a static IP address on the same network segment as the W5500 Ethernet interface. The gateway address is the same as that of the W5500 NIC address so that the computer can connect to the network throught a LTE NIC. +import ethernet +import dataCall + +# Loads the corresponding NIC driver and initializes the relevant configuration of NIC. Replaces the driver with the actual corresponding NIC driver. +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# Obtains current LTE network data call IP information. +lte=dataCall.getInfo(1, 0) +print(lte) +if lte[2][0] == 1: + # Sets LTE network as the default NIC. + nic.set_default_NIC(lte[2][2]) + +#Starts NIC. +nic.set_up() + +# Now other devices can connect to the module through the network cable for LTE network access. +... + +``` + +Static IP Address Configuration + +```python +# In the static IP address configuration, customizes network information based on the current environment. +import ethernet + +# Loads the corresponding NIC driver and initializes the relevant configuration of NIC. Replaces the driver with the actual corresponding NIC driver. +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# Configures the static IP address to 192.168.0.2, subnet mask to 255.255.255.0 and gateway address to 192.168.0.1. +nic.set_addr('192.168.1.100','255.255.255.0','192.168.1.1') +print(nic.ipconfig()) + +# Starts NIC. +nic.set_up() + +# 1. In the terminal mode, starts other network services and accesses the network through Ethernet. +# 2. In the gateway mode, configures the default NIC and the peer static IP address according to the gateway user guide in the above example and then you can use this module to provide network services. +... + +``` + +## Classes +- [class W5500 – W5500 Driver](./ethernet.W5500.md) +- [class DM9051 – DM9051 Driver](./ethernet.DM9051.md) +- [class CH395 – CH395 Driver](./ethernet.CH395.md) +- [class YT8512H – YT8512H Driver](./ethernet.YT8512H.md) diff --git a/docs/API_reference/en/peripherals/machine.ExtInt.md b/docs/API_reference/en/peripherals/machine.ExtInt.md new file mode 100644 index 0000000000000000000000000000000000000000..fff2f0b5427f5ad9a624ca193708ce30e25cb9a6 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.ExtInt.md @@ -0,0 +1,138 @@ +# ExtInt - External Interrupt + +This class configures I/O pins to interrupt when external events occur. + +## Constructor + +### `machine.ExtInt` + +```python +class machine.ExtInt(GPIOn, mode, pull, callback, [filter_time]) +``` + +**Parameter:** + +- `GPIOn` - Integer type. GPIO pin number to be controlled. See [Pin Modules](./machine.Pin.md) for pin definitions (excluding BG95M3). Click here to view pin correspondences of BG95M3 platform. + +- `mode` - Integer type. Trigger mode.
`IRQ_RISING` – Trigger rising edge
`IRQ_FALLING` – Trigger falling edge
`IRQ_RISING_FALLING` – Trigger rising and falling edge + +- `pull` - Integer type. Pull selection mode.
`PULL_PU` – Pull-up mode
`PULL_PD` – Pull-down mode
`PULL_DISABLE` – Floating mode + +- `callback` - Integer type. The interrupt triggers the callback function.
A tuple with the length of 2 bytes
args[0]: GPIO number
args[1]: Trigger edge (0: rising edge 1: falling edge) + +- `[filter_time]` - Integer type. Filtering time,uint: ms, default value is 0.Allowed input nonzero value is multiple of 10.If the value is not 0, the filtering is performed at the specified time. + + > parameter [filter_time] only EG912N/EG915N/EC600M/EC800M/EG810M/EC200A/UC200A series module support + +
+ Pin Correspondences of BG95M3,BG95M8 Module
+GPIO2 – Pin5
GPIO3 – Pin6
GPIO6 – Pin19
GPIO7 – Pin22
GPIO8 – Pin23
GPIO9 – Pin25
GPIO11 – Pin27
GPIO12 – Pin28
GPIO14 – Pin41
GPIO16 – Pin65
GPIO17 – Pin66
GPIO18 – Pin85
GPIO19 – Pin86
GPIO22 – Pin20
GPIO23 – Pin21
GPIO24 – Pin30
GPIO25 – Pin34
GPIO26 – Pin35
GPIO29 – Pin38
GPIO30 – Pin39 +
+ + + +**Example:** + +```python +>>> # Creates an ExtInt object +>>> from machine import ExtInt +>>> def fun(args): + print('### interrupt {} ###'.format(args)) # args[0]: GPIO number args[1]: rising edge or falling edge +>>> extint = ExtInt(ExtInt.GPIO1, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, fun) +``` + +## Methods + +### `extint.enable` + +``` +extint.enable() +``` + +This method enables interrupts that is to enable external interrupt of an extint object. When the interrupt pin receives the rising edge signal or falling edge signal, it will call a callback function to execute the interrupt. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `extint.disable` + +``` +extint.disable() +``` + +This method disables interrupts associated with extint objects. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `extint.line` + +``` +extint.line() +``` + +This method reads the line number mapped by the pin. + +**Return Value:** + +The line number mapped by the pin. + +**Example:** + +```python +>>> extint = ExtInt(ExtInt.GPIO1, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, fun) +>>> extint.line() +1 +``` + +### `extint.read_count` + +``` +extint.read_count(is_reset) +``` + +This method returns number of times an interrupt was triggered. + +**Parameter:** + +- `is_reset` - Integer type. Whether to reset the count after reading. `0` indicates that the count is not resetted and `1` indicates a count resetting. + +**Return Value:** + +The list `[rising_count, falling_count]`
`rising_count`: Number of times that the rising edge triggers an interrupt
`falling_count`: Number of times that the falling edge triggers an interrupt + +### `extint.count_reset` + +``` +extint.count_reset() +``` + +This method clears number of times an interrupt is triggered. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `extint.read_level` + +``` +extint.read_level() +``` + +This method reads the current pin level. + +**Return Value:** + +Pin level. + +`0` - low level. + +`1` - high level. \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/machine.I2C.md b/docs/API_reference/en/peripherals/machine.I2C.md new file mode 100644 index 0000000000000000000000000000000000000000..976672d5eb859332c09574a42ba682db5e41316b --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.I2C.md @@ -0,0 +1,1570 @@ +# I2C – Two-wire Serial Protocol + +This class is designed for the two-wire serial protocol for communication between devices. + +## Constructor + +### `machine.I2C` + +
+
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • + +
+
+ + +
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2
    I2C3 : 3 - Channel 3

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • + +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • +
  • Note: +
    1.Inside the module, Pin57 is the same as Pin11, and Pin56 is the same as Pin12. +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • +
  • Note: +
    1.Inside the module, Pin67 is the same as Pin57, and Pin66 is the same as Pin58. +
    2.The 57th and 58th pins of EC800ECN_LE&LQ&CG are not available. +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode
    ENHANCED_FAST_MODE2 - Enhanced Fast mode

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE, [group])
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • +
  • [group] - Select to use I2C in different pins. Currently, only FCM362K supports Iics. The default value is 0

    +
  • +
+
+
+
class machine.I2C(I2Cn, MODE, [group])
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • +
  • [group] - Select to use I2C in different pins. Currently, only FCM362K supports Iics. The default value is 0

    +
  • +
+
+ + +
+
class machine.I2C(I2Cn, MODE)
+
+

Parameter:

+
    +
  • I2Cn - Integer type. I2C channel index number.
    I2C0 : 0 - Channel 0
    I2C1 : 1 - Channel 1
    I2C2 : 2 - Channel 2

    +
  • +
  • MODE - Integer type. I2C working mode.
    STANDARD_MODE : 0 - Standard mode
    FAST_MODE1 - Fast mode

    +
  • +
+
+ +
+ +
+ +
+

Example:

+

+>>> from machine import I2C
+>>> # Creates an I2C object
+>>> i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE)  # Returns an I2C object
+
+
+
+

Example:

+

+>>> from machine import I2C
+>>> # Creates an I2C object
+>>> i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE,0)  # Returns an I2C object
+
+
+ +
+ +**I2C Pin Correspondences:** + +
+ + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin11pin12
I2C1pin57pin56
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin41pin42
I2C1pin141引142
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin41pin42
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin41pin42
I2C1pin143pin144
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin41pin42
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin23pin22
I2C1pin20pin21
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin18pin19
I2C1pin40pin41
I2C2pin26pin25
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin9pin64
I2C1pin57pin56
I2C2pin67pin65
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin103pin114
I2C1pin40pin41
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C1pin75pin74
I2C2pin68pin69
I2C3pin57pin58
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C1pin75pin74
I2C2pin68pin69
I2C3pin57pin58
+ + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C1pin40pin41
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C1pin57(11)pin56(12)
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67(57)pin66(58)
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin57pin56
I2C1pin11pin12
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C1pin57pin58
I2C2pin68pin69
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C1pin40pin41
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C1pin57pin56
I2C3pin11pin12
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C2pin68pin69
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C2pin68pin69
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C2pin68pin69
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin29pin23
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin30pin29
+ + + + + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin81(group=0)pin80(group=0)
I2C0pin67(group=1)pin66(group=1)
I2C1pin57pin58
+ + + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin12pin26
I2C1pin43pin44
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin12pin26
I2C2pin43pin44
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C1pin40pin41
+ + + + + + + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin67pin66
I2C1pin57pin58
+ + + + + + + + + + + + + + + + +
I2CSCLSDA
I2C0pin40pin41
+ +
+ +## Methods + +### `I2C.read` + +```python +I2C.read(slaveaddress, addr,addr_len, r_data, datalen, delay) +``` + +This method reads data to I2C bus. + +**Parameter:** + +- `slaveaddress` - Integer type. I2C device address. +- `addr` - Bytearray type. I2C register address. +- `addr_len` - Integer type. Register address length. +- `r_data` - Bytearray type. Byte array for receiving data. +- `datalen` - Integer type. Length of byte array. +- `delay` - Integer type. Delay. Data conversion buffer time (unit: ms). + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `I2C.write` + +```python +I2C.write(slaveaddress, addr, addr_len, data, datalen) +``` + +This method writes data to I2C bus. + +**Parameter:** + +- `slaveaddress` - Integer type. I2C device address. +- `addr` - Bytearray type. I2C register address. +- `addr_len` - Integer type. Register address length. +- `data` - Bytearray type. Data to be written. +- `datalen` - Integer type. Length of data to be written. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +> Please connect the device. + +```python +import log +from machine import I2C +import utime + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement. +''' +PROJECT_NAME = "QuecPython_I2C_example" +PROJECT_VERSION = "1.0.0" + +''' +I2C usage example +''' + +# Sets log output level +log.basicConfig(level=log.INFO) +i2c_log = log.getLogger("I2C") + + +if __name__ == '__main__': + I2C_SLAVE_ADDR = 0x1B # I2C device address + WHO_AM_I = bytearray([0x02, 0]) # I2C register address. It is passed in as a buff. Take the first value and calculate the length of a value + + data = bytearray([0x12, 0]) # Inputs the corresponding command + i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE) # Returns an I2C object + i2c_obj.write(I2C_SLAVE_ADDR, WHO_AM_I, 1, data, 2) # Writes data + + r_data = bytearray(2) # Creates a byte array with the length of 2 bytes for receiving + i2c_obj.read(I2C_SLAVE_ADDR, WHO_AM_I, 1, r_data, 2, 0) # read + i2c_log.info(r_data[0]) + i2c_log.info(r_data[1]) + +``` + +## Constants + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C1I2C passage index number: 1
I2C.I2C3I2C passage index number: 3
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.I2C3I2C passage index number: 3
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.I2C3I2C passage index number: 3
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.I2C1I2C passage index number: 1
I2C.I2C2I2C passage index number: 2
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
I2C.ENHANCED_FAST_MODEEnhanced fast mode
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
I2C.I2C0I2C passage index number: 0
I2C.STANDARD_MODEStandard mode
I2C.FAST_MODEFast mode
+ +
\ No newline at end of file diff --git a/docs/API_reference/en/peripherals/machine.I2C_simulation.md b/docs/API_reference/en/peripherals/machine.I2C_simulation.md new file mode 100644 index 0000000000000000000000000000000000000000..27c34874aaf9f3dd50ace20f8768a25fba89ca11 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.I2C_simulation.md @@ -0,0 +1,187 @@ +# I2C_simulation - Software Implementation of I2C Protocol + +This class is designed for GPIO simulating standard I2C protocol. Except for creating the object, all other operations (read and write) are consistent with I2C communication. + +## Constructor + +### `machine.I2C_simulation` + +```python +class machin.I2C_simulation(GPIO_clk, GPIO_sda, CLK) +``` + +**Parameter:** + +- `GPIO_clk` - Integer type. CLK pin of I2C (See definitions in [machine.Pin](machine.Pin.md) for GPIO pin numbers that need to be controlled). +- `GPIO_sda` - Integer type. SDA pin of I2C (See definitions in [machine.Pin](machine.Pin.md) for GPIO pin numbers that need to be controlled). +- `CLK` - Integer type. Frequency of I2C. Range: [1, 1000000 Hz]. + +**Example:** + +```python +>>> from machine import I2C_simulation +>>> # Creates an I2C_simulation object +>>> i2c_obj = I2C_simulation(I2C_simulation.GPIO10, I2C_simulation.GPIO11, 300) # Returns an I2C object +``` + +## Methods + +### `I2C_simulation.read` + +```python +I2C_simulation.read(slaveaddress, addr,addr_len, r_data, datalen, delay) +``` + +This method reads data to I2C bus. + +**Parameter:** + +- `slaveaddress` - Integer type. I2C device address. +- `addr` - Bytearray type. I2C register address. +- `addr_len` - Integer type. Register address length. +- `r_data` - Bytearray type. Byte array used to receive data. +- `datalen` - Integer type. Length of byte array. +- `delay` - Integer type. Delay. Data conversion buffer time (unit: ms). + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `I2C_simulation.write` + +```python +I2C_simulation.write(slaveaddress, addr, addr_len, data, datalen) +``` + +This method writes data to I2C bus. + +**Parameter:** + +- `slaveaddress` - Integer type. I2C device address. +- `addr` - Bytearray type. I2C register address. +- `addr_len` - Integer type. Register address length. +- `data` - Bytearray type. Data to be written. +- `datalen` - Integer type. Length of data to be written. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +import log +#from machine import I2C +from machine import I2C_simulation +import utime as time +""" +1. calibration +2. Trigger measurement +3. read data +""" + +# API manual +# https://python.quectel.com/doc/API_reference/en/peripherals/machine.I2C_simulation.html + +# AHT10 instructions +# https://server4.eca.ir/eshop/AHT10/Aosong_AHT10_en_draft_0c.pdf +# This example shows that driver AHT10 obtains temperature and humidity data. + +class aht10class(): + i2c_log = None + i2c_dev = None + i2c_addre = None + + # Initialization command + AHT10_CALIBRATION_CMD = 0xE1 + # Trigger measurement + AHT10_START_MEASURMENT_CMD = 0xAC + # reset + AHT10_RESET_CMD = 0xBA + + def write_data(self, data): + self.i2c_dev.write(self.i2c_addre, + bytearray(0x00), 0, + bytearray(data), len(data)) + pass + + def read_data(self, length): + print("read_data start") + r_data = [0x00 for i in range(length)] + r_data = bytearray(r_data) + print("read_data start1") + ret = self.i2c_dev.read(self.i2c_addre, + bytearray(0x00), 0, + r_data, length, + 0) + print("read_data start2") + print('ret',ret) + print('r_data:',r_data) + return list(r_data) + + def aht10_init(self, addre=0x38, Alise="Ath10"): + self.i2c_log = log.getLogger(Alise) + self.i2c_dev = I2C_simulation(I2C_simulation.GPIO10, I2C_simulation.GPIO11, 300) + self.i2c_addre = addre + self.sensor_init() + pass + + def aht10_transformation_temperature(self, data): + r_data = data + # Convert the temperature according to descriptions in the data manual + humidity = (r_data[0] << 12) | ( + r_data[1] << 4) | ((r_data[2] & 0xF0) >> 4) + humidity = (humidity/(1 << 20)) * 100.0 + print("current humidity is {0}%".format(humidity)) + temperature = ((r_data[2] & 0xf) << 16) | ( + r_data[3] << 8) | r_data[4] + temperature = (temperature * 200.0 / (1 << 20)) - 50 + print("current temperature is {0}°C".format(temperature)) + + + def sensor_init(self): + # calibration + self.write_data([self.AHT10_CALIBRATION_CMD, 0x08, 0x00]) + time.sleep_ms(300) # At least 300 ms + pass + + + def ath10_reset(self): + self.write_data([self.AHT10_RESET_CMD]) + time.sleep_ms(20) # At least 20 ms + + def Trigger_measurement(self): + # Trigger data conversion + self.write_data([self.AHT10_START_MEASURMENT_CMD, 0x33, 0x00]) + time.sleep_ms(200) # At least delay 75 ms + # check has success + r_data = self.read_data(6) + # check bit7 + if (r_data[0] >> 7) != 0x0: + print("Conversion has error") + else: + self.aht10_transformation_temperature(r_data[1:6]) + +ath_dev = None + +def i2c_aht10_test(): + global ath_dev + ath_dev = aht10class() + ath_dev.aht10_init() + + # Test ten times + for i in range(5): + ath_dev.Trigger_measurement() + time.sleep(1) + + +if __name__ == "__main__": + print('start') + i2c_aht10_test() + + +``` diff --git a/docs/API_reference/en/peripherals/machine.KeyPad.md b/docs/API_reference/en/peripherals/machine.KeyPad.md new file mode 100644 index 0000000000000000000000000000000000000000..c56e5b076690fbfbb0fa6dd6a51bf2c7644042f5 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.KeyPad.md @@ -0,0 +1,704 @@ +# KeyPad - Matrix Keyboard + +This class provides the matrix keyboard interface. + + + +## Constructor + +### `machine.KeyPad` + +```python +class machine.KeyPad(row,col) +``` + +**Parameter:** + +- `row` - Integer type. Row number. It shall be greater than 0 and cannot exceed the maximum value supported by the module. +- `col` - Integer type. Column number. It shall be greater than 0. The value cannot exceed the maximum value supported by the module. + +> If you do not set the row and column value, the default value is 4X4. + +
+ + + + + + + + + + + + + +
Maximum RowMaximum Column
44
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
6(series only suprrort 4 Row,see Pin Correspondences)4
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
66
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
55
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
55
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
5(EG810MEU series only suprrort 3 Row,see Pin Correspondences)5(EG810MEU series only suprrort 3 Row,see Pin Correspondences)
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
33
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
44
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
33
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
55
+ + + + + + + + + + + + + + +
Maximum RowMaximum Column
44
+ +
+ +**KeyPad Pin Correspondences:** + +> When part of pins are used, you shall connect the keyboard and the pin according to row and column numbers in ascending order. For example, for EC600M, when a 2x2 matrix keyboard is used, the hardware will use 49, 51 and 48, 50 pins. + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin49Column number0pin48
Row number1pin51Column number1pin50
Row number2pin53Column number2pin52
Row number3pin55Column number3pin54
Row number4pin56Column number4pin57
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin86Column number0pin87
Row number1pin76Column number1pin77
Row number2pin85Column number2pin84
Row number3pin82Column number3pin83
Row number4pin74Column number4pin75
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin86(EG810MEU series not support)Column number0pin87(EG810MEU series not support)
Row number1pin76Column number1pin77
Row number2pin85(EG810MEU series not support)Column number2pin84(EG810MEU series not support)
Row number3pin82Column number3pin83
Row number4pin74Column number4pin75
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number1pin20Column number2pin105
Row number2pin16Column number3pin21
Row number3pin116Column number4pin1
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin83Column number0pin115
Row number1pin84Column number1pin78
Row number2pin113Column number2pin79
Row number3pin114Column number3pin80
Row number4pin81(EC200UXXAA series not support)Column number4/
Row number5pin82(EC200UXXAA series not support)Column number5/
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin105Column number0pin55
Row number1pin106Column number1pin129
Row number2pin107Column number2pin128
Row number3pin108Column number3pin127
Row number4pin104Column number4pin126
Row number5pin103Column number5pin125
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin39Column number0pin83
Row number1pin20Column number2pin28
Row number2pin27Column number3pin25
Row number3pin26Column number4pin1
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin53Column number0pin52
Row number1pin49Column number1pin54
Row number2pin55Column number2pin50
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin74Column number0pin75
Row number1pin76Column number1pin77
Row number2pin86Column number2pin87
Row number3pin82Column number3pin81
Row number4pin29Column number4pin28
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Row numberRow PINColumn numberColumn PIN
Row number0pin74Column number0pin75
Row number1pin76Column number1pin77
Row number2pin86Column number2pin87
Row number3pin82Column number3pin81
Row number4pin29(EG800K series not support)Column number4pin28(EG800K series not support)
+ +
+ +**Example:** + +```python +>>> # Creates a keypad object +>>> import machine +>>> keypad=machine.KeyPad(2,3) # Sets a matrix keyboard with 2 rows and 3 columes +>>> keypad=machine.KeyPad() # Default parameter. The default setting is a matrix keyboard with 4 rows and 4 columns +>>> keypad=machine.KeyPad(2) # Sets the row value to 2. Default column Value. The default column value is 4. A matrix keyboard with 2 rows and 4 columes is initialized. +``` + +## Methods + +### `keypad.init` + +```python +keypad.init() +``` + +This method initializes keypad settings. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `keypad.set_callback` + +```python +keypad.set_callback(usrFun) +``` + +This method sets callback function. After the external keyboard button is connected to the module, this callback function will be triggered when the external keyboard button is pressed and released. + +**Parameter:** + +- `usrFun` - Matrix keyboard callback function. Prototype: + + ``` + usrFun(result_list) + ``` + + Parameter of callback function: + + - `result_list[0]`: Key status (1 indicates the button is pressed and 0 indicates the button is released). + + - `result_list[1]`: Row number + + - `result_list[2]`: Column number + +> for example,the EC600M module, suppose the key connect pin 49 and pin 52,if press the key, the parameter of callback is [1,0,2],if release the key, the parameter of callback is [0,0,2]. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `keypad.deinit` + +```python +keypad.deinit() +``` + +This method deinitializes to release initialized resources and callback function settings. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +import machine +import utime +is_loop = 1 +keypad=machine.KeyPad() +keypad.init() +def userfun(l_list): + global is_loop + if l_list[0] != 1 : + is_loop = 0 + print('will exit') + print(l_list) +keypad.set_callback(userfun) +loop_num = 0 +while is_loop == 1 and loop_num < 10: + utime.sleep(5) + loop_num = loop_num +1 + print(" running..... ",is_loop,loop_num) +keypad.deinit() +print('exit!') +``` diff --git a/docs/API_reference/en/peripherals/machine.LCD.md b/docs/API_reference/en/peripherals/machine.LCD.md new file mode 100644 index 0000000000000000000000000000000000000000..7abe8535024eaa7898c06440d7baeb66736f0610 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.LCD.md @@ -0,0 +1,528 @@ +# LCD - LCD Driver + +This class controls LCD. + +> Supported module models are as follows: +> +> EC200U series module, EC600U series module, EC600N series module, EC800N series module, +> +> EC600M-CNLA, EC600M-CNLE +> +> EC800M-CNLA, EC800M-CNLE, EC800M-CNGA, EC800G-CNGA +> +> EG912N-ENAA, EG912U-GLAA +> +> EG915N-EUAG, EG915U-EUAB + +## Constructor + +### `machine.LCD` + +```python +class machine.lcd = LCD() +``` + +**Example:** + +```python +>>> from machine import LCD +>>> lcd = LCD() # Creates a LCD object +``` + +## Methods + +### `lcd.lcd_init` + +This method initializes LCD. + +#### Interface 1: The device connects to LCM interfaces of modules + +```python +lcd.lcd_init(lcd_init_data, lcd_width, lcd_hight, lcd_clk, data_line, line_num, lcd_type, lcd_invalid, lcd_display_on, lcd_display_off, lcd_set_brightness) +``` + +**Parameter:** + +| Parameter | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| lcd_init_data | bytearray | Write command for LCD initialization. | +| lcd_width | int | Width of LCD screen. The width cannot exceed 500 pixels. | +| lcd_hight | int | Height of LCD screen. The height cannot exceed 500 pixels. | +| lcd_clk | int | LCD SPI clock frequency:
6500: 6.5 MHz
13000: 13 MHz
26000: 26 MHz
52000: 52 MHz | +| data_line | int | Number of data lines. Parameter values are 1 and 2. | +| line_num | int | Number of lines. Parameter values are 3 and 4. | +| lcd_type | int | Screen type. 0-rgb; 1-fstn. | +| lcd_invalid | bytearray | Write command for LCD region settings. | +| lcd_display_on | bytearray | Write command for turning on the LCD screen. | +| lcd_display_off | bytearray | Write command for turning off the LCD screen. | +| lcd_set_brightness | bytearray | Write command for LCD screen brightness:
None indicates that LCD_BL_K controls brightness. | + +**Return Value:** + +`0` - Successful execution. + +`-1` - LCD initialized. + +`-2` - Parameter error. Parameter is empty or too large (more than 1000 pixels). + +`-3` - Failed cache request. + +`-5` - Parameter configuration error. + +#### Interface 2: The device connects to module SPI + +```python +lcd.lcd_init(lcd_init_data, lcd_width, lcd_hight, lcd_clk, data_line, line_num, lcd_type, lcd_invalid, lcd_display_on, lcd_display_off, lcd_set_brightness, lcd_interface, spi_port, spi_mode, cs_pin, dc_pin, rst_pin) +``` + +**Parameter:** + +| Parameter | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| lcd_init_data | bytearray | Write command for LCD initialization. | +| lcd_width | int | Width of LCD screen. The width cannot exceed 500 pixels. | +| lcd_hight | int | Height of LCD screen. The height cannot exceed 500 pixels. | +| lcd_clk | int | See machine.SPI 漏了超链接 for creating SPI objects parameter descriptions. | +| data_line | int | Number of data lines. Parameter values are 1 and 2. | +| line_num | int | Number of lines. Parameter values are 3 and 4. | +| lcd_type | int | Screen type. 0-rgb; 1-fstn. | +| lcd_invalid | bytearray | Write command for LCD region settings. | +| lcd_display_on | bytearray | Write command for turning on LCD screen. | +| lcd_display_off | bytearray | Write command for turning off LCD screen. | +| lcd_set_brightness | bytearray | Write command for LCD screen brightness:
None indicates that LCD_BL_K controls the brightness. | +| lcd_interface | int | LCD interface type. 0 - LCM; 1 - SPI | +| spi_port | int | Channel selection [0,1]. See machine.SPI 漏了超链接 for port description. | +| spi_mode | int | SPI work mode (Work mode 0 is commonly used):
CPOL: The level of clock signal of SCLK when SPI is idle (0: low level; 1: high level)
0 : CPOL=0, CPHA=0
1 : CPOL=0, CPHA=1
2 : CPOL=1, CPHA=0
3 : CPOL=1, CPHA=1 | +| cs_pin | int | CS pin. See [machine.Pin](machine.Pin.md) for descriptions of GPIO pin number. | +| dc_pin | int | DC pin. See [machine.Pin](machine.Pin.md) for descriptions of GPIO pin number. | +| rst_pin | int | RST pin. See [machine.Pin](machine.Pin.md) for descriptions of GPIO pin number. | + +**Return Value:** + +`0` - Successful execution. + +`-1` - LCD Initialized. + +`-2` - Parameter error. Parameter is empty or too large (more than 1000 pixels). + +`-3` - Failed cache request. + +`-5` - Parameter configuration error. + + +### `lcd.mipi_init` + +```python +lcd.mipi_init(initbuf, **kwargs) +``` + +This method initializes MIPI and passes parameters according to key-value pairs. Please set parameters according to initialization parameters provided by the screen manufacturer. + +> 1. Only EC200U and EC600U series modules support this function. +> 2. In the parameter list below, *initbuf* is a required parameter. Other parameters are optional parameters. If values are consistent with default values, you needn’t pass this parameter. + +**Parameter:** + +| Parameter | Type | Description | +| ----------- | --------- | ------------------------------------------------------------ | +| initbuf | bytearray | Required. Write command for passing MIPI. | +| width | int | Width of LCD screen. Default value: 480. Example: width = 400. | +| hight | int | Height of LCD screen. Default value: 854. Example: height = 800. | +| bpp | int | Bits per pixel. Default value: 16. | +| DataLane | int | Data channel. Default value: 2. | +| MipiMode | int | Mode:
0: DSI_VIDEO_MODE
1: DSI_CMD_MODE
Default value: 0 | +| PixelFormat | int | Pixel format:
0: RGB_PIX_FMT_RGB565
16: RGB_PIX_FMT_RGB888
32: RGB_PIX_FMT_XRGB888
48: RGB_PIX_FMT_RGBX888
Default value: 0 | +| DsiFormat | int | DSI format:
0: DSI_FMT_RGB565
1: DSI_FMT_RGB666
2: DSI_FMT_RGB666L
3: DSI_FMT_RGB888
Default value: 0 | +| TransMode | int | Transform mode:
0: DSI_CMD
1: DSI_PULSE
2: DSI_EVENT
3: DSI_BURST
Default value: 3 | +| RgbOrder | int | RGB order:
0: RGB
8: BGR
Default value: 8 | +| BllpEnable | bool | Enable blank low power. Default value: true. | +| HSync | int | Horizontal synchronization. Default value: 10. | +| HBP | int | Horizontal back porch. Default value: 10. | +| HFP | int | Horizontal front porch. Default value: 10. | +| VSync | int | Vertical Synchronization. Default value: 4. | +| VBP | int | Vertical back porch. Default value: 10. | +| VFP | int | Vertical front porch. Default value: 14. | +| FrameRate | int | Frame rate. Default value: 60. | +| TESel | bool | TE selection. Default value: false. | +| RstPolarity | int | Reset polarity. Default value: 1. | + +**Return Value:** + +`0` - Successful execution + +Error codes - Failed execution + +**Pin Description of MIPI Screen:** + +| Pin Name | EC600U Series Module | EC200U Series Module | +| -------- | -------------------- | -------------------- | +| CKN | PIN61 | PIN27 | +| CKP | PIN58 | PIN26 | +| D1N | PIN59 | PIN24 | +| D1P | PIN60 | PIN25 | +| D0N | PIN69 | PIN13 | +| D0P | PIN70 | PIN135 | +| FMARK | PIN62 | PIN119 | +| RESET | PIN64 | PIN120 | + +**Example:** + +```python +init_480X854 = ( +0x11,0,0, +0xFF,120,5,0x77,0x01,0x00,0x00,0x10, +0xC0,0,2,0xE9,0x03, +0xC1,0,2,0x11,0x02, +0xC2,0,2,0x31,0x08, +0xCC,0,1,0x10, +0xB0,0,16,0x00,0x0D,0x14,0x0D,0x10,0x05,0x02,0x08,0x08,0x1E,0x05,0x13,0x11,0xA3,0x29,0x18, +0xB1,0,16,0x00,0x0C,0x14,0x0C,0x10,0x05,0x03,0x08,0x07,0x20,0x05,0x13,0x11,0xA4,0x29,0x18, +0xFF,0,5,0x77,0x01,0x00,0x00,0x11, +0xB0,0,1,0x6C, +0xB1,0,1,0x43, +0xB2,0,1,0x07, +0xB3,0,1,0x80, +0xB5,0,1,0x47, +0xB7,0,1,0x85, +0xB8,0,1,0x20, +0xB9,0,1,0x10, +0xC1,0,1,0x78, +0xC2,0,1,0x78, +0xD0,0,1,0x88, +0xE0,100,3,0x00,0x00,0x02, +0xE1,0,11,0x08,0x00,0x0A,0x00,0x07,0x00,0x09,0x00,0x00,0x33,0x33, +0xE2,0,13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0xE3,0,4,0x00,0x00,0x33,0x33, +0xE4,0,2,0x44,0x44, +0xE5,0,16,0x0E,0x60,0xA0,0xA0,0x10,0x60,0xA0,0xA0,0x0A,0x60,0xA0,0xA0,0x0C,0x60,0xA0,0xA0, +0xE6,0,4,0x00,0x00,0x33,0x33, +0xE7,0,2,0x44,0x44, +0xE8,0,16,0x0D,0x60,0xA0,0xA0,0x0F,0x60,0xA0,0xA0,0x09,0x60,0xA0,0xA0,0x0B,0x60,0xA0,0xA0, +0xEB,0,7,0x02,0x01,0xE4,0xE4,0x44,0x00,0x40, +0xEC,0,2,0x02,0x01, +0xED,0,16,0xAB,0x89,0x76,0x54,0x01,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x10,0x45,0x67,0x98,0xBA, +0xFF,0,5,0x77,0x01,0x00,0x00,0x00, +0x3A,0,1,0x77, +0x36,0,1,0x00, +0x35,0,1,0x00, +0x29,0,0 +) +from machine import LCD +mipilcd = LCD() +mipilcd.mipi_init(initbuf=bytearray(init_480X854), TransMode=1) +``` + +### `lcd.lcd_clear` + +``` +lcd.lcd_clear(color) +``` + +This method clears LCD screen. + +**Parameter:** + +- `color` - String type in hexadecimal. The color used to clear the LCD screen. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `lcd.lcd_write` + +``` +lcd.lcd_write(color_buffer,start_x,start_y,end_x,end_y) +``` + +This method writes LCD screen in a specified area. + +**Parameter:** + +- `color_buffer` - Bytearray type. Cache of screen color value. +- `start_x` - Integer type. The start x coordinate. +- `start_y` - Integer type. The start y coordinate. +- `end_x` - Integer type. The end x coordinate. +- `end_y` - Integer type. The end y coordinate. + +**Return Value:** + +`0` - Successful execution. + +`-1` - LCD screen is not initialized. + +`-2` - Width and height setting errors. + +`-3 ` - Empty data cache. + +### `lcd.lcd_brightness` + +``` +lcd.lcd_brightness(level) +``` + +This method sets the screen brightness level. + +**Parameter:** + +- `level` - Integer type. Brightness level. The description is as follows:
*lcd_set_brightness* in *lcd.lcd_init()* will be called. If the parameter is None, the brightness is controlled by LCD_BL_K. Range: [0,5]. + +**Return Value:** + +`0 `- Successful execution + +`-1` - Failed execution + +### `lcd.lcd_display_on` + +``` +lcd.lcd_display_on() +``` + +This method turns on the screen display. *lcd_display_on* in *lcd.lcd_init()* will be called after you call this interface. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `lcd.lcd_display_off` + +```python +lcd.lcd_display_off() +``` + +This method turns off the screen display. *lcd_display_off* in *lcd.lcd_init()* will be called after you call this interface. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `lcd.lcd_write_cmd` + +``` +lcd.lcd_write_cmd(cmd_value, cmd_value_len) +``` + +This method writes commands. + +**Parameter:** + +- `cmd_value` - String type in hexadecimal. Command value. +- `cmd_value_len` - Integer type. Command value length. + +**Return Value:** + +`0` - Successful execution + +`Other Values` - Failed execution + +### `lcd.lcd_write_data` + +```python +lcd.lcd_write_data(data_value, data_value_len) +``` + +This method writes commands. + +**Parameter:** + +- `data_value` - String type in hexadecimal. Data value. +- `data_value_len` - Integer type. Data value length. + +**Return Value:** + +`0` - Successful execution + +`Other Values` - Failed execution + +### `lcd.lcd_show` +Modules supporting this method: EC600K/EC800K/EG800P series modules. +``` +lcd.lcd_show(file_name, start_x,start_y,width,hight) +``` + +This method displays images by reading files. + +> This file is a bin file generated by *Image2Lcd*. If the image header file is checked, you needn’t to enter width and height. + +**Parameter:** + +- `file_name ` - String type. Image name to be displayed. +- `start_x` - Integer type. The start x coordinate. +- `start_y` - Integer type. The start y coordinate. +- `width` - Integer type. Image width (If the image file contains header information, you can leave image width blank). +- `hight` - Integer type. Image height (If the image file contains header information, you can leave image height blank). + +**Return Value:** + +`0` - Successful execution + +`Other Values` - Failed execution + +### `lcd.lcd_show_jpg` +Modules supporting this method: EC600K/EC800K/EG800P series modules. +```python +lcd.lcd_show_jpg( file_name, start_x,start_y) +``` + +This method displays JPEG images by reading files. + +**Parameter:** + +- `file_name ` - String type. Image name needs to be displayed. +- `start_x` - Integer type. The start x coordinate. +- `start_y` - Integer type. The start y coordinate. + +**Return Value:** + +`0` - Successful execution + +`Other Values` - Failed execution + +**Example:** + +> An LCD screen is required. The following code takes st7789 as an example. + +```python +from machine import LCD + +# Follows the corresponding initialization example given by the LCD manufacturer +# First row: 2, 0, 120, 2 indicates the command of sleep. The middle digit is fixed as 0. 120 indicates the number of milliseconds of sleep. LCD will sleep for 120 ms after receiving this row of data. +# Second row: 0, 0, 0x11, 0 indicates the command of writing data to the register address. The middle digit indicates the length of data to be written later. 0 indicates no data is to be written. 0x11 indicates the register address. +# Third row: 0, 1, 0x36, 0 indicates the command of writing data to the register address. The middle digit indicates the length of data to be written later. 1 indicates one byte of data is to be written. 0x36 indicates the register address. +# Fourth row: 1, 1, 0x00, 1 indicates the command of writing data. The middle digit indicates the length of data to be written. 0x00 indicates the data. +# Then follow the format of the first four rows to enter initialization examples. +init_data = (2, 0, 120, + 0, 0, 0x11, + 0, 1, 0x36, + 1, 1, 0x00, + 0, 1, 0x3A, + 1, 1, 0x05, + 0, 0, 0x21, + 0, 5, 0xB2, + 1, 1, 0x05, + 1, 1, 0x05, + 1, 1, 0x00, + 1, 1, 0x33, + 1, 1, 0x33, + 0, 1, 0xB7, + 1, 1, 0x23, + 0, 1, 0xBB, + 1, 1, 0x22, + 0, 1, 0xC0, + 1, 1, 0x2C, + 0, 1, 0xC2, + 1, 1, 0x01, + 0, 1, 0xC3, + 1, 1, 0x13, + 0, 1, 0xC4, + 1, 1, 0x20, + 0, 1, 0xC6, + 1, 1, 0x0F, + 0, 2, 0xD0, + 1, 1, 0xA4, + 1, 1, 0xA1, + 0, 1, 0xD6, + 1, 1, 0xA1, + 0, 14, 0xE0, + 1, 1, 0x70, + 1, 1, 0x06, + 1, 1, 0x0C, + 1, 1, 0x08, + 1, 1, 0x09, + 1, 1, 0x27, + 1, 1, 0x2E, + 1, 1, 0x34, + 1, 1, 0x46, + 1, 1, 0x37, + 1, 1, 0x13, + 1, 1, 0x13, + 1, 1, 0x25, + 1, 1, 0x2A, + 0, 14, 0xE1, + 1, 1, 0x70, + 1, 1, 0x04, + 1, 1, 0x08, + 1, 1, 0x09, + 1, 1, 0x07, + 1, 1, 0x03, + 1, 1, 0x2C, + 1, 1, 0x42, + 1, 1, 0x42, + 1, 1, 0x38, + 1, 1, 0x14, + 1, 1, 0x14, + 1, 1, 0x27, + 1, 1, 0x2C, + 0, 0, 0x29, + 0, 1, 0x36, + 1, 1, 0x00, + 0, 4, 0x2a, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0xef, + 0, 4, 0x2b, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0xef, + 0, 0, 0x2c,) + +display_on_data = ( + 0, 0, 0x11, + 2, 0, 20, + 0, 0, 0x29, +) +display_off_data = ( + 0, 0, 0x28, + 2, 0, 120, + 0, 0, 0x10, +) +# Sets the parameters of LCD screen area +XSTART_H = 0xf0 +XSTART_L = 0xf1 +YSTART_H = 0xf2 +YSTART_L = 0xf3 +XEND_H = 0xE0 +XEND_L = 0xE1 +YEND_H = 0xE2 +YEND_L = 0xE3 +invalid_data = ( + 0, 4, 0x2a, + 1, 1, XSTART_H, + 1, 1, XSTART_L, + 1, 1, XEND_H, + 1, 1, XEND_L, + 0, 4, 0x2b, + 1, 1, YSTART_H, + 1, 1, YSTART_L, + 1, 1, YEND_H, + 1, 1, YEND_L, + 0, 0, 0x2c, +) + +lcd = LCD() +init_list = bytearray(init_data) +display_on_list = bytearray(display_on_data) +display_off_list = bytearray(display_off_data) +invalid_list = bytearray(invalid_data) + + +lcd.lcd_init(init_list, 240,240,13000,1,4,0,invalid_list,display_on_list,display_off_list,None) + +Color_buffer =(0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f) + +Color_buffer = bytearray(Color_buffer) + +lcd.lcd_write(Color_buffer,10,10,20,20) +lcd.lcd_clear(0xf800) # Red + +lcd.lcd_show("lcd_test.bin",0,0) #This lcd_test.bin file contains image header data. +lcd.lcd_show("lcd_test1.bin",0,0,126,220) #This lcd_test1.bin file does not contain image header data. +``` diff --git a/docs/API_reference/en/peripherals/machine.OneWire.md b/docs/API_reference/en/peripherals/machine.OneWire.md new file mode 100644 index 0000000000000000000000000000000000000000..018cdeb467aa1cb20747870ef4b90f656c3727d6 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.OneWire.md @@ -0,0 +1,87 @@ +# class OneWire – One-Wire Protocol + +This class provides One-Wire communication functionality. This feature is currently only supported on the EC200U/EC600U/EG912U/EG915U series. + +## Constructor + +### `machine.OneWire` + +```python +class machine.OneWire(GPIO) +``` + +**Parameter:** + +- `GPIO` - The gpio used, int type. + + +**Example:** + +```python +from machine import OneWire +obj=OneWire(OneWire.GPIO19)# Create a One-Wire object using GPIO19 +``` + +## Methods + +### `OneWire.reset` + +```python +OneWire.reset() +``` + +This method is used to reset the bus and detect if a device responds. It needs to be called before calling read/write methods. + +**Return Value:** + +Returns int value `0` indicating correct response, returns int value `-1` indicating no response. + +### `OneWire.read` + +```python +OneWire.read(len) +``` + +This method is used to read data. + +**Parameter:** + +- `len` - The length of data to read, int type. + +**Return Value:** + +Returns the read bytes object. + +### `OneWire.write` + +```python +OneWire.write(data) +``` + +This method is used to write data. + +**Parameter:** + +- `data` - The data to write, bytes type. + +**Return Value:** + +Returns int value `0`. + +**Example:** Read DS18B20 data + +> Needs to work with DS18B20! + +```python +from machine import OneWire + +obj=OneWire(OneWire.GPIO19) +data1=bytearray([0xcc,0x44]) +data2=bytearray([0xcc,0xbe]) + +obj.reset()#First reset bus and detect if slave device responds, then read/write +obj.write(data1) +obj.reset() +obj.write(data2) +obj.read(2)#The read data is the raw DS18B20 data, needs to be converted to actual temperature based on DS18B20 data format +``` diff --git a/docs/API_reference/en/peripherals/machine.Pin.md b/docs/API_reference/en/peripherals/machine.Pin.md new file mode 100644 index 0000000000000000000000000000000000000000..f89f93596757e5c045059924a842cf1b553971eb --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.Pin.md @@ -0,0 +1,8453 @@ +# Pin - Control I/O Pins + +This class provides methods of reading and writing GPIO. A pin object is used to control I/O pins (also known as GPIO - general-purpose input/output). The pin class has methods to set the mode of the pin (IN, OUT, etc) and methods to get and set the digital logic level. + +**Example:** + +```python +from machine import Pin + +# Creates a GPIO object +gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 1) + +# Gets the pin level +gpio1.read() + +# Sets the pin level +gpio1.write(0) +gpio1.write(1) + +# Sets input and output modes +gpio1.set_dir(Pin.IN) +gpio1.set_dir(Pin.OUT) + +# Gets input and output modes +gpio1.get_dir() +``` + +## Constructor + +### `machine.Pin` + +```python +class machine.Pin(GPIOn, direction, pullMode, level) +``` + +**Parameter:** + +- `GPIOn` - Integer type. GPIO number. Click here to view the mapping relationship between GPIO pin numbers and physical pins. +- `direction` - Integer type. I/O mode. `IN` - Input mode. `OUT` - Output mode. +- `pullMode` - Integer type. Pull selection mode. Descriptions are as follows:
PULL_DISABLE - Floating mode
PULL_PU - Pull-up mode
PULL_PD - Pull-down mode +- `level` - Integer type. Pin level. `0` - Set pin to low level. `1`- Set pin to high level. + +**Example:** + +```python +>>> # Creates a GPIO object +>>> from machine import Pin +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +``` + +**Mapping Relationship Between GPIO Pin Numbers and Physical Pins:** + +> Description of GPIO corresponding pin numbers: GPIO pin numbers provided in the document correspond to external pin numbers of the module. For example, for EC600M-CN module, GPIO1 corresponds to pin10, which is an external pin number of the module. See the provided hardware documents for external pin numbers of the module. + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin10
GPIO2Pin11
GPIO3Pin12
GPIO4Pin13
GPIO5Pin14
GPIO6Pin15
GPIO7Pin16
GPIO8Pin39
GPIO9Pin40
GPIO10Pin48
GPIO11Pin58
GPIO12Pin59
GPIO13Pin60
GPIO14Pin61
GPIO15Pin62
GPIO16Pin63
GPIO17Pin69
GPIO18Pin70
GPIO19Pin1
GPIO20Pin3
GPIO21Pin49
GPIO22Pin50
GPIO23Pin51
GPIO24Pin52
GPIO25Pin53
GPIO26Pin54
GPIO27Pin55
GPIO28Pin56
GPIO29Pin57
GPIO30Pin2
GPIO31Pin66
GPIO32Pin65
GPIO33Pin67
GPIO34Pin64
GPIO35Pin4
GPIO36Pin31
GPIO37Pin32
GPIO38Pin33
GPIO39Pin34
GPIO40Pin71
GPIO41Pin72
GPIO42Pin109
GPIO43Pin110
GPIO44Pin112
GPIO45Pin111
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4
GPIO2Pin5
GPIO3Pin6
GPIO4Pin7
GPIO5Pin18
GPIO6Pin19
GPIO7Pin25
GPIO8Pin26
GPIO9Pin42
GPIO10Pin1
GPIO11Pin40
GPIO12Pin41
GPIO13Pin64
GPIO14Pin65
GPIO15Pin66
GPIO16Pin86
GPIO17Pin20
GPIO18Pin21
GPIO19Pin34
GPIO20Pin35
GPIO21Pin36
GPIO22Pin37
GPIO23Pin38
GPIO24Pin39
GPIO25Pin98
GPIO26Pin85
GPIO27Pin87
GPIO28Pin88
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin61 (It cannot be used together with GPIO31.)
GPIO2Pin58 (It cannot be used together with GPIO32.)
GPIO3Pin34 (It cannot be used together with GPIO41.)
GPIO4Pin60 (It cannot be used together with GPIO34.)
GPIO5Pin69 (It cannot be used together with GPIO35.)
GPIO6Pin70 (It cannot be used together with GPIO36.)
GPIO7Pin123 (It cannot be used together with GPIO43.)
GPIO8Pin118
GPIO9Pin9 (It cannot be used together with GPIO47.)
GPIO10Pin1 (It cannot be used together with GPIO37.)
GPIO11Pin4 (It cannot be used together with GPIO38.)
GPIO12Pin3 (It cannot be used together with GPIO39.)
GPIO13Pin2 (It cannot be used together with GPIO40.)
GPIO14Pin54
GPIO15Pin57
GPIO16Pin56
GPIO17Pin12
GPIO18Pin33 (It cannot be used together with GPIO42.)
GPIO19Pin124 (It cannot be used together with GPIO44.)
GPIO20Pin122 (It cannot be used together with GPIO45.)
GPIO21Pin121 (It cannot be used together with GPIO46.)
GPIO22Pin48
GPIO23Pin39
GPIO24Pin40
GPIO25Pin49
GPIO26Pin50
GPIO27Pin53
GPIO28Pin52
GPIO29Pin51
GPIO30Pin59 (It cannot be used together with GPIO33.)
GPIO31Pin66 (It cannot be used together with GPIO1.)
GPIO32Pin63 (It cannot be used together with GPIO2.)
GPIO33Pin67 (It cannot be used together with GPIO30.)
GPIO34Pin65 (It cannot be used together with GPIO4.)
GPIO35Pin137 (It cannot be used together with GPIO5.)
GPIO36Pin62 (It cannot be used together with GPIO6.)
GPIO37Pin98 (It cannot be used together with GPIO10.)
GPIO38Pin95 (It cannot be used together with GPIO11.)
GPIO39Pin119 (It cannot be used together with GPIO12.)
GPIO40Pin100 (It cannot be used together with GPIO13.)
GPIO41Pin120 (It cannot be used together with GPIO3.)
GPIO42Pin16 (It cannot be used together with GPIO18.)
GPIO43Pin10 (It cannot be used together with GPIO7.)
GPIO44Pin14 (It cannot be used together with GPIO19.)
GPIO45Pin15 (It cannot be used together with GPIO20.)
GPIO46Pin13 (It cannot be used together with GPIO21.)
GPIO47Pin99 (It cannot be used together with GPIO9.)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin27 (It cannot be used together with GPIO31.)
GPIO2Pin26 (It cannot be used together with GPIO32.)
GPIO3Pin24 (It cannot be used together with GPIO33.)
GPIO4Pin25 (It cannot be used together with GPIO34.)
GPIO5Pin13 (It cannot be used together with GPIO17.)
GPIO6Pin135 (It cannot be used together with GPIO36.)
GPIO7Pin136 (It cannot be used together with GPIO44.)
GPIO8Pin133
GPIO9Pin3 (It cannot be used together with GPIO37.)
GPIO10Pin40 (It cannot be used together with GPIO38.)
GPIO11Pin37 (It cannot be used together with GPIO39.)
GPIO12Pin38 (It cannot be used together with GPIO40.)
GPIO13Pin39 (It cannot be used together with GPIO41.)
GPIO14Pin5
GPIO15Pin141
GPIO16Pin142
GPIO17Pin121 (It cannot be used together with GPIO5.)
GPIO18Pin65 (It cannot be used together with GPIO42.)
GPIO19Pin64 (It cannot be used together with GPIO43.)
GPIO20Pin139 (It cannot be used together with GPIO45.)
GPIO21Pin126 (It cannot be used together with GPIO46.)
GPIO22Pin127 (It cannot be used together with GPIO47.)
GPIO23Pin33
GPIO24Pin31
GPIO25Pin30
GPIO26Pin29
GPIO27Pin28
GPIO28Pin1
GPIO29Pin2
GPIO30Pin4
GPIO31Pin125 (It cannot be used together with GPIO1.)
GPIO32Pin124 (It cannot be used together with GPIO2.)
GPIO33Pin123 (It cannot be used together with GPIO3.)
GPIO34Pin122 (It cannot be used together with GPIO4.)
GPIO35Pin42
GPIO36Pin119 (It cannot be used together with GPIO6.)
GPIO37Pin134 (It cannot be used together with GPIO9.)
GPIO38Pin132 (It cannot be used together with GPIO10.)
GPIO39Pin131 (It cannot be used together with GPIO11.)
GPIO40Pin130 (It cannot be used together with GPIO12.)
GPIO41Pin129 (It cannot be used together with GPIO13.)
GPIO42Pin61 (It cannot be used together with GPIO18.)
GPIO43Pin62 (It cannot be used together with GPIO19.)
GPIO44Pin63 (It cannot be used together with GPIO7.)
GPIO45Pin66 (It cannot be used together with GPIO20.)
GPIO46Pin6 (It cannot be used together with GPIO21.)
GPIO47Pin23 (It cannot be used together with GPIO22.)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin27
GPIO2Pin26
GPIO3Pin24
GPIO4Pin25
GPIO5Pin5
GPIO6Pin135
GPIO7Pin136
GPIO8Pin68
GPIO9Pin3
GPIO10Pin40
GPIO11Pin37
GPIO12Pin38
GPIO13Pin39
GPIO14Pin67
GPIO15Pin13
GPIO18Pin65
GPIO19Pin64
GPIO20Pin139
GPIO22Pin127
GPIO27Pin28
GPIO28Pin1
GPIO29Pin2
GPIO30Pin4
GPIO35Pin42
GPIO36Pin119
GPIO43Pin62
GPIO44Pin63(Not supported by EC200ACN_LA)
GPIO45Pin66
GPIO46Pin6
GPIO47Pin23
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin27
GPIO2Pin26
GPIO3Pin24
GPIO4Pin25
GPIO5Pin5
GPIO6Pin135
GPIO7Pin136
GPIO8Pin68
GPIO9Pin3
GPIO10Pin40
GPIO11Pin37
GPIO12Pin38
GPIO13Pin39
GPIO14Pin67
GPIO15Pin13
GPIO18Pin65
GPIO19Pin64
GPIO20Pin139
GPIO22Pin127
GPIO27Pin28
GPIO28Pin1
GPIO29Pin2
GPIO30Pin4
GPIO35Pin42
GPIO43Pin62
GPIO44Pin63
GPIO45Pin66
GPIO46Pin6
GPIO47Pin23
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin56
GPIO13Pin57
GPIO14Pin58
GPIO15Pin80
GPIO16Pin81
GPIO17Pin76
GPIO18Pin77
GPIO19Pin82
GPIO20Pin83
GPIO21Pin86
GPIO22Pin87
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO27Pin19
GPIO28Pin20
GPIO29Pin21
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO36Pin16
GPIO37Pin78
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin3
GPIO2Pin4
GPIO3Pin5
GPIO4Pin6
GPIO5Pin16
GPIO6Pin20
GPIO7Pin21
GPIO8Pin22
GPIO9Pin23
GPIO10Pin25
GPIO11Pin28
GPIO12Pin29
GPIO13Pin30
GPIO14Pin31
GPIO15Pin32
GPIO16Pin33
GPIO17Pin2
GPIO18Pin8
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4
GPIO2Pin5
GPIO3Pin6
GPIO4Pin7
GPIO5Pin18
GPIO6Pin19
GPIO7Pin22
GPIO8Pin23
GPIO9Pin25
GPIO10Pin26
GPIO11Pin27
GPIO12Pin28
GPIO13Pin40
GPIO14Pin41
GPIO15Pin64
GPIO16Pin65
GPIO17Pin66
GPIO18Pin85
GPIO19Pin86
GPIO20Pin87
GPIO21Pin88
GPIO22Pin20
GPIO23Pin21
GPIO24Pin30
GPIO25Pin34
GPIO26Pin35
GPIO27Pin36
GPIO28Pin37
GPIO29Pin38
GPIO30Pin39
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4 (It cannot be used together with GPIO41.)
GPIO2Pin5 (It cannot be used together with GPIO36.)
GPIO3Pin6 (It cannot be used together with GPIO35.)
GPIO4Pin7 (It cannot be used together with GPIO24.)
GPIO5Pin18
GPIO6Pin19
GPIO7Pin1 (It cannot be used together with GPIO37.)
GPIO8Pin38
GPIO9Pin25
GPIO10Pin26
GPIO11Pin27 (It cannot be used together with GPIO32.)
GPIO12Pin28 (It cannot be used together with GPIO31.)
GPIO13Pin40
GPIO14Pin41
GPIO15Pin64
GPIO16Pin20 (It cannot be used together with GPIO30.)
GPIO17Pin21
GPIO18Pin85 (It cannot be reused when using the dual-SIM standby function.)
GPIO19Pin86 (It cannot be reused when using the dual-SIM standby function.)
GPIO20Pin30
GPIO21Pin88
GPIO22Pin36 (It cannot be used together with GPIO40.)
GPIO23Pin37 (It cannot be used together with GPIO38.)
GPIO24Pin16 (It cannot be used together with GPIO4.)
GPIO25Pin39
GPIO26Pin42 (It cannot be used together with GPIO27.)
GPIO27Pin78 (It cannot be used together with GPIO26.)
GPIO28Pin83 (It cannot be used together with GPIO33.)
GPIO29Pin84 (It cannot be reused when using the dual-SIM standby function.)
GPIO30Pin92 (It cannot be used together with GPIO16.)
GPIO31Pin95 (It cannot be used together with GPIO12.)
GPIO32Pin97 (It cannot be used together with GPIO11.)
GPIO33Pin98 (It cannot be used together with GPIO28.)
GPIO34Pin104
GPIO35Pin105 (It cannot be used together with GPIO3.)
GPIO36Pin106 (It cannot be used together with GPIO2.)
GPIO37Pin108 (It cannot be used together with GPIO4.)
GPIO38Pin111 (It cannot be used together with GPIO23.)
GPIO39Pin114
GPIO40Pin115 (It cannot be used together with GPIO22.)
GPIO41Pin116 (It cannot be used together with GPIO1.)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin56
GPIO13Pin57
GPIO14Pin58
GPIO15Pin80
GPIO16Pin81
GPIO17Pin76
GPIO18Pin77
GPIO19Pin82
GPIO20Pin83
GPIO21Pin86(EG810M_EU unsupported)
GPIO22Pin87(EG810M_EU unsupported)
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO27Pin19
GPIO28Pin20
GPIO29Pin21
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO34Pin38
GPIO35Pin39
GPIO36Pin16
GPIO37Pin78
GPIO38Pin68
GPIO39Pin69
GPIO40Pin74
GPIO41Pin75
GPIO42Pin84(EG810M_EU unsupported)
GPIO43Pin85(EG810M_EU unsupported)
GPIO44Pin25
GPIO47Pin79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4
GPIO2Pin5
GPIO3Pin6
GPIO4Pin7
GPIO5Pin18
GPIO6Pin19
GPIO7Pin1
GPIO8Pin16
GPIO9Pin25
GPIO10Pin26
GPIO11Pin27
GPIO12Pin28
GPIO13Pin40
GPIO14Pin41
GPIO15Pin64
GPIO16Pin20
GPIO17Pin21
GPIO18Pin30
GPIO19Pin34
GPIO20Pin35
GPIO21Pin36
GPIO22Pin37
GPIO23Pin38
GPIO24Pin39
GPIO25Pin42
GPIO26Pin78
GPIO27Pin83
GPIO28Pin92
GPIO29Pin95
GPIO30Pin96
GPIO31Pin97
GPIO32Pin98
GPIO33Pin103
GPIO34Pin104
GPIO35Pin105
GPIO36Pin106
GPIO37Pin107
GPIO38Pin114
GPIO39Pin115
GPIO40Pin116
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin10(I&PU)
GPIO2Pin11(57)(I&PU)(It cannot be used together with GPIO41)
GPIO3Pin12(56)(I&PU)(It cannot be used together with GPIO40)
GPIO4Pin13(I&PU)
GPIO5Pin14(I&PU)
GPIO6Pin15(I&PU)
GPIO7Pin16(I&PU)
GPIO8Pin39(I&PD)
GPIO9Pin40(I&PU)
GPIO10Pin48(I&PD)
GPIO11Pin58(I&PD)
GPIO12Pin59(I&PD)
GPIO13Pin60(I&PD)(It cannot be used together with GPIO36)
GPIO14Pin61(I&PD)
GPIO15Pin62(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO16Pin63(I&PD)(EC600ECN_LE&LQ Unavailable)
GPIO17Pin69(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO18Pin70(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO22Pin50(I&PD)
GPIO23Pin51(I&PD)
GPIO24Pin52(I&PD)
GPIO25Pin53(I&PD)
GPIO26Pin54(I&PD)
GPIO31Pin66(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO32Pin65(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO33Pin67(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO34Pin64(I&PU)(EC600ECN_LE&LQ Unavailable)
GPIO36Pin31(I&PU)(It cannot be used together with GPIO13)
GPIO37Pin32(I&PU)
GPIO38Pin33(I&PU)
GPIO39Pin34(I&PU)
GPIO40Pin71(I&PU)(It cannot be used together with GPIO3)
GPIO41Pin72(I&PU)(It cannot be used together with GPIO2)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30(I&PD)
GPIO2Pin31(I&PD)
GPIO3Pin32(I&PD)
GPIO4Pin33(I&PD)(It cannot be used together with GPIO25)
GPIO5Pin49(I&PD)(EC800ECN_LE&LQ&CG Unavailable)
GPIO6Pin50(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO7Pin51(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO8Pin52(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO9Pin53(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO10Pin54(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO11Pin55(I&PU)(EC800ECN_LE&LQ&CG Unavailable,It cannot be used together with Pin64)
GPIO12Pin56(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO13Pin57(67)(I&PU)(EC800ECN_LE&LQ&CG pin number 57 cannot be used)(It cannot be used together with GPIO34)
GPIO14Pin58(66)(I&PU)(EC800ECN_LE&LQ&CG Pin number 58 cannot be used)(It cannot be used together with GPIO35)
GPIO15Pin80(I&PU)(EC800ECN_LE&LQ&CG Unavailable,It cannot be used together with Pin63)
GPIO16Pin81(I&PU)(EC800ECN_LE&LQ&CG Unavailable,It cannot be used together with Pin62)
GPIO17Pin25(I&PD)
GPIO25Pin17(I&PU)(It cannot be used together with GPIO4)
GPIO26Pin18(I&PU)
GPIO27Pin19(I&PD)
GPIO28Pin20(I&PU)
GPIO29Pin21(I&PD)
GPIO30Pin22(I&PU)
GPIO31Pin23(I&PU)
GPIO32Pin28(I&PU)
GPIO33Pin29(I&PU)
GPIO34Pin38(I&PU)(It cannot be used together with GPIO13)
GPIO35Pin39(I&PU)(It cannot be used together with GPIO14)
GPIO36Pin16(I&PD)
GPIO37Pin78(I&PU)(EC800ECN_LE&LQ&CG Unavailable)
GPIO38Pin85(I&PD)(EC800ECN_LE&LQ&LC&CG Unavailable)
GPIO39Pin108(I&PD)(EC800ECN_LE&LQ&LC&CG Unavailable)
GPIO40Pin109(I&PD)(EC800ECN_LE&LQ&LC&CG Unavailable)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin56
GPIO13Pin57
GPIO14Pin58
GPIO15Pin80
GPIO16Pin81
GPIO17Pin25(AGPIO)
GPIO23Pin66(It cannot be used together with GPIO26)
GPIO24Pin67(It cannot be used together with GPIO25)
GPIO25Pin17(It cannot be used together with GPIO24)
GPIO26Pin18(It cannot be used together with GPIO23)
GPIO27Pin19(AGPIO, the driving ability is weak, it is recommended to use only as an input pin)
GPIO28Pin20(AGPIO)
GPIO29Pin21(AGPIO)
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO34Pin38
GPIO35Pin39
GPIO36Pin16(AGPIO)
GPIO37Pin78
GPIO38Pin85(AGPIO)
GPIO39Pin108(AGPIO, the driving ability is weak, it is recommended to use only as an input pin)
GPIO40Pin109(AGPIO, the driving ability is weak, it is recommended to use only as an input pin)
GPIO41Pin101
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin61(It cannot be used together with GPIO24)
GPIO2Pin58(It cannot be used together with GPIO25)
GPIO3Pin34
GPIO4Pin60
GPIO5Pin69(It cannot be used together with GPIO10)
GPIO6Pin70(It cannot be used together with GPIO11)
GPIO7Pin123
GPIO8Pin132
GPIO9Pin9
GPIO10Pin1(It cannot be used together with GPIO5)
GPIO11Pin4(It cannot be used together with GPIO6)
GPIO12Pin3
GPIO13Pin2
GPIO14Pin54
GPIO15Pin57
GPIO16Pin56
GPIO17Pin12
GPIO18Pin33
GPIO19Pin124(It cannot be used together with GPIO37)
GPIO20Pin104
GPIO21Pin103
GPIO22Pin48
GPIO23Pin39(It cannot be used together with GPIO46)
GPIO24Pin40(It cannot be used together with GPIO1)
GPIO25Pin49(It cannot be used together with GPIO2)
GPIO26Pin50(It cannot be used together with GPIO30)
GPIO27Pin53
GPIO28Pin52
GPIO29Pin51
GPIO30Pin59(It cannot be used together with GPIO26)
GPIO31Pin66
GPIO32Pin63
GPIO33Pin67
GPIO34Pin65
GPIO35Pin137
GPIO36Pin62
GPIO37Pin105(It cannot be used together with GPIO19)
GPIO38Pin106
GPIO39Pin107
GPIO40Pin126
GPIO41Pin120
GPIO42Pin16
GPIO43Pin10
GPIO44Pin14
GPIO45Pin64
GPIO46Pin13(It cannot be used together with GPIO23)
GPIO47Pin116
GPIO48Pin31
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30(It cannot be used together with GPIO45)
GPIO2Pin31(It cannot be used together with GPIO46)
GPIO3Pin32(It cannot be used together with GPIO47)
GPIO4Pin33(It cannot be used together with GPIO48)
GPIO5Pin49
GPIO6Pin50(It cannot be used together with GPIO50)
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin25
GPIO13Pin57(It cannot be used together with GPIO49)
GPIO14Pin58(It cannot be used together with GPIO20)
GPIO15Pin84
GPIO16Pin81
GPIO17Pin76(It cannot be used together with GPIO35)
GPIO18Pin77
GPIO19Pin82
GPIO20Pin83(It cannot be used together with GPIO14)
GPIO21Pin86(It cannot be used together with GPIO34)
GPIO22Pin87
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO27Pin19
GPIO28Pin20
GPIO29Pin21
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO34Pin38(It cannot be used together with GPIO21)
GPIO35Pin39(It cannot be used together with GPIO17)
GPIO36Pin16
GPIO37Pin78
GPIO38Pin85
GPIO39Pin68
GPIO40Pin69
GPIO41Pin80(It cannot be used together with GPIO44)
GPIO42Pin107
GPIO43Pin103
GPIO44Pin101(It cannot be used together with GPIO41)
GPIO45Pin79(It cannot be used together with GPIO1)
GPIO46Pin100(It cannot be used together with GPIO2)
GPIO47Pin108(It cannot be used together with GPIO3)
GPIO48Pin109(It cannot be used together with GPIO4)
GPIO49Pin75(It cannot be used together with GPIO13)
GPIO50Pin74(It cannot be used together with GPIO6)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4(It cannot be used together with GPIO40)
GPIO2Pin5(It cannot be used together with GPIO36)
GPIO3Pin6(It cannot be used together with GPIO35)
GPIO4Pin7(It cannot be used together with GPIO8)
GPIO5Pin18
GPIO6Pin19
GPIO7Pin1(It cannot be used together with GPIO19)
GPIO8Pin16(It cannot be used together with GPIO4)
GPIO10Pin26(EG912UGuLAA unsupported)
GPIO11Pin27(It cannot be used together with GPIO31)
GPIO12Pin28(It cannot be used together with GPIO29)
GPIO13Pin40
GPIO14Pin41
GPIO15Pin64(EG912UGLAA unsupported)
GPIO16Pin20(It cannot be used together with GPIO28)
GPIO17Pin21
GPIO18Pin30
GPIO19Pin108(It cannot be used together with GPIO7)
GPIO20Pin88(EG912UGLAA unsupported)
GPIO21Pin36(It cannot be used together with GPIO39)
GPIO22Pin37(It cannot be used together with GPIO30)
GPIO23Pin38
GPIO24Pin39
GPIO25Pin42(It cannot be used together with GPIO26)
GPIO26Pin78(It cannot be used together with GPIO25)
GPIO27Pin83(It cannot be used together with GPIO32)
GPIO28Pin92(It cannot be used together with GPIO16)
GPIO29Pin95(It cannot be used together with GPIO12)
GPIO30Pin111(It cannot be used together with GPIO22)
GPIO31Pin97(It cannot be used together with GPIO11)
GPIO32Pin98(It cannot be used together with GPIO27)
GPIO34Pin104
GPIO35Pin105(It cannot be used together with GPIO3)
GPIO36Pin106(It cannot be used together with GPIO2)
GPIO38Pin114
GPIO39Pin115(It cannot be used together with GPIO21)
GPIO40Pin116(It cannot be used together with GPIO1)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin10
GPIO2Pin11
GPIO3Pin12
GPIO4Pin13
GPIO5Pin14
GPIO6Pin15
GPIO7Pin16
GPIO8Pin39
GPIO9Pin40
GPIO10Pin48
GPIO11Pin58
GPIO12Pin59
GPIO13Pin60
GPIO14Pin61
GPIO15Pin62
GPIO16Pin63
GPIO17Pin69
GPIO18Pin70
GPIO19Pin1
GPIO20Pin3
GPIO21Pin49
GPIO22Pin50
GPIO23Pin51
GPIO24Pin52
GPIO25Pin53
GPIO26Pin54
GPIO27Pin55(boot pin, internal pull-up)
GPIO28Pin56
GPIO29Pin57
GPIO30Pin2
GPIO31Pin66
GPIO32Pin65
GPIO33Pin67
GPIO34Pin64
GPIO35Pin4
GPIO36Pin31
GPIO37Pin32
GPIO38Pin33
GPIO39Pin34
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54(The EG800KCN is unavailable)
GPIO11Pin55(The EG800KCN is unavailable)
GPIO12Pin56(The EG800KCN is unavailable)
GPIO13Pin57(The EG800KCN is unavailable)
GPIO14Pin58(The EG800KCN is unavailable)
GPIO15Pin80(The EG800KCN is unavailable)
GPIO16Pin81
GPIO17Pin76
GPIO18Pin77
GPIO19Pin82
GPIO20Pin83
GPIO21Pin86
GPIO22Pin87
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO27Pin19
GPIO28Pin20
GPIO29Pin21
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28(The EG800KCN is unavailable)
GPIO33Pin29(The EG800KCN is unavailable)
GPIO36Pin16
GPIO37Pin78
GPIO38Pin68
GPIO39Pin69
GPIO40Pin74
GPIO41Pin75
GPIO44Pin25
GPIO47Pin79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin20
GPIO13Pin19
GPIO14Pin21
GPIO15Pin80
GPIO16Pin81
GPIO17Pin76
GPIO18Pin77
GPIO19Pin82
GPIO20Pin83
GPIO21Pin86
GPIO22Pin87
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO36Pin16
GPIO37Pin78
GPIO38Pin68
GPIO39Pin69
GPIO40Pin74
GPIO41Pin75
GPIO44Pin25
GPIO47Pin79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin30
GPIO2Pin31
GPIO3Pin32
GPIO4Pin33
GPIO5Pin49
GPIO6Pin50
GPIO7Pin51
GPIO8Pin52
GPIO9Pin53
GPIO10Pin54
GPIO11Pin55
GPIO12Pin56
GPIO15Pin80
GPIO16Pin81
GPIO17Pin25(AGPIO pin status is not affected by sleep mode)
GPIO23Pin66
GPIO24Pin67
GPIO25Pin17
GPIO26Pin18
GPIO27Pin19
GPIO28Pin20(AGPIO pin status is not affected by sleep mode)
GPIO30Pin22
GPIO31Pin23
GPIO32Pin28
GPIO33Pin29
GPIO34Pin38
GPIO35Pin39
GPIO36Pin16(AGPIO pin status is not affected by sleep mode)
GPIO37Pin78
GPIO38Pin6(AGPIOWU can be used as WAKEUP and AGPIO types)
GPIO39Pin5(AGPIOWU can be used as WAKEUP and AGPIO types)
GPIO40Pin100(AGPIO pin status is not affected by sleep mode)
GPIO41Pin101(AGPIO pin status is not affected by sleep mode)
GPIO42Pin26
GPIO43Pin64
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pin number
Pin6
Pin7
Pin8
Pin9
Pin10
Pin12
Pin13
Pin14
Pin15
Pin16
Pin19
Pin20
Pin21
Pin22
Pin23
Pin29
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pin number
Pin6
Pin7
Pin8
Pin9
Pin14
Pin15
Pin16
Pin27
Pin28
Pin29
Pin30
Pin31
Pin34
Pin35
Pin37
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin12
GPIO2Pin13
GPIO3Pin41
GPIO4Pin42
GPIO5Pin21
GPIO6Pin22
GPIO7Pin23
GPIO8Pin24
GPIO9Pin26
GPIO10Pin43
GPIO11Pin44
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin12
GPIO2Pin13
GPIO3Pin41
GPIO4Pin42
GPIO5Pin21
GPIO6Pin22
GPIO7Pin23
GPIO8Pin24
GPIO9Pin26
GPIO10Pin43
GPIO11Pin44
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO numberPin number
GPIO1Pin4
GPIO2Pin5
GPIO3Pin6
GPIO4Pin7
GPIO5Pin18
GPIO6Pin19
GPIO7Pin1
GPIO8Pin38
GPIO9Pin25
GPIO10Pin26
GPIO11Pin27
GPIO12Pin28
GPIO13Pin40
GPIO14Pin41
GPIO15Pin64
GPIO16Pin20
GPIO17Pin21
GPIO18Pin34
GPIO19Pin35
GPIO20Pin30
GPIO21Pin22
GPIO22Pin36
GPIO23Pin37
GPIO24Pin16
GPIO25Pin39
GPIO26Pin23
GPIO27Pin78
GPIO28Pin83
GPIO29Pin107
GPIO30Pin92
GPIO31Pin95
GPIO32Pin97
GPIO33Pin98
GPIO34Pin104
GPIO35Pin105
GPIO36Pin106
GPIO37Pin103
GPIO38Pin96
GPIO39Pin114
GPIO40Pin115
GPIO41Pin116
+
+ +
+
+
+
+

Note:

+

1.I&PU: In the input mode, only the floating and pull-up modes are supported

+

2.I&PD: In the input mode, only floating and drop-down modes are supported

+

3.The ExtInt function of the EC600E does not support both rising and falling edges to trigger an interrupt

+
+
+ +
+
+

Note:

+

1.I&PU: In the input mode, only the floating and pull-up modes are supported

+

2.I&PD: In the input mode, only floating and drop-down modes are supported

+

3.EC800ECN_LE&LQ&CG Unavailable: The pin of this model module is suspended internally, so it cannot be used

+

4.Pin67, Pin66, Pin57, and Pin58 of the module share the same internal IO, that is, when the level of GPIO13 is changed, Pin57 and Pin67 will change simultaneously

+

5.On the module of EC800ECN_LE&LQ&CG model, Pin57 and Pin58 are suspended internally, so only Pin67 and Pin66 can be used as GPIO13 and 14

+

6. The ExtInt function of the EC800E does not support the simultaneous rise and fall of the ExTINt edge

+

7.Pin55, 80, and 81 cannot be used with Pin64, 63, and 62 (SIM2 pins), respectively

+
+
+ +
+
+

Note:

+

1.When AGPIO is in sleep mode, the level state remains unchanged, while the level of ordinary GPIO cannot be maintained during sleep

+

2.GPIO27, GPIO39, and GPIO40 have weak driving capabilities, so it is recommended to use them only as input pins

+
+
+ +
+
+

Note:

+

1.When AGPIO is in sleep mode, the level state remains unchanged, while the level of ordinary GPIO cannot be maintained during sleep

+

2.GPIO38, and GPIO39 have weak driving capabilities, so it is recommended to use them only as input pins

+
+
+ +
+
+

Note:

+

1.Pin37-GPIO11,Pin38-GPIO12,Pin39-GPIO13,Module that support GNSS function do not enable the multiplexing function of this pin and it need to be left open.

+

2.When using the (U)SIM2 function, Pin1, Pin2 and Pin4 can no longer be used as GPIOs.

+
+
+ +
+
+

Note:

+

1.There is a hardware conflict between GPIO27-Pin53, GPIO28-Pin52, GPIO29-Pin51 and Pin145 to Pin147. If the pins Pin145 to Pin147 of the (U)SIM2 interface are used, then pins Pin51 to Pin53 cannot be used as GPIO.

+
+
+ +
+ + +## Methods + +### `Pin.read` + +```python +Pin.read() +``` + +This method reads the pin level. + +**Return Value:** + +Pin level. `0` - low level. `1` - high level. + +### `Pin.write` + +``` +Pin.write(value) +``` + +This method sets the pin level. + +> Note: You need to ensure that the pin is in the output mode before you set the pin level. + +**Parameter:** + +- `value` - Integer type. Pin level. `0` - low level. `1` - high level. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> from machine import Pin +#GPIO Output Mode - Set Pin Level +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +>>> gpio1.write(1) +0 +# GPIO Input Mode - Reading Pin Level +>>> gpio1 = Pin(Pin.GPIO1, Pin.IN, Pin.PULL_DISABLE, 0) +>>> gpio1.read() +0 +``` + +### `Pin.set_dir` + +```python +Pin.set_dir(value) +``` + +This method sets I/O mode of the pin. + +**Parameter:** + +- `value` - Integer type. I/O mode of the pin. `0` - Input mode. `1` - Output mode. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `Pin.get_dir` + +```python +Pin.get_dir() +``` + +This method gets I/O mode of the pin. + +**Return Value:** + +I/O mode of pins. + +`0` - Input mode. + +`1` - Output mode. + +**Example:** + +```python +>>> from machine import Pin +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +>>> gpio1.get_dir() +1 +>>> gpio1.set_dir(Pin.IN) +0 +>>> gpio1.get_dir() +0 +``` + +## Constants +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO22GPIO22
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO22GPIO22
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO35GPIO35
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.GPIO48GPIO48
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.GPIO48GPIO48
Pin.GPIO49GPIO49
Pin.GPIO50GPIO50
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.INInput mode
Pin.OUTOutput mode
Pin.PULL_DISABLEFloating mode
Pin.PULL_PUPull-up mode
Pin.PULL_PDPull-down mode
+
diff --git a/docs/API_reference/en/peripherals/machine.RTC.md b/docs/API_reference/en/peripherals/machine.RTC.md new file mode 100644 index 0000000000000000000000000000000000000000..373d87d8382b0429c461f1e7bfb582c187d251e1 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.RTC.md @@ -0,0 +1,159 @@ +# RTC – Real Time Clock + +This class provides methods of getting and setting RTC. For BC25PA series module, it provides the feature of waking up modules from deep sleep and software power-off state. + +## Constructor + +### `machine.RTC` + +```python +class machine.RTC() +``` + +**Example:** + +```python +>>> # Creates a RTC object +>>> from machine import RTC +>>> rtc = RTC() +``` + +## Methods + +### `rtc.datetime` + +```python +rtc.datetime([year, month, day, week, hour, minute, second, microsecond]) +``` + +This method sets or gets RTC time. If this function contains parameters, this method sets the time otherwise this methods gets the time. When setting the time, you need not to set `week`. `microsecond` is reserved and it is not currently used and its default value is 0. + +**Parameter:** + +- `year` - Integer type. Year. +- `month` - Integer type. Month. Range: [1–12]. +- `day` - Integer type. Day. Range: [1–31]. +- `week` - Integer type. Week. Range: [0–6]. 0 indicates Sunday. 1 to 6 indicates Monday to Saturday respectively. This parameter is reserved when setting time and it only takes effect when getting the time. +- `hour` - Integer type. Hour. Range: [0–23]. +- `minute` - Integer type. Minute. Range: [0–59]. +- `second` - Integer type. Second. Range: [0–59]. +- `microsecond` - Integer type. Microsecond. This parameter is reserved and it is not currently used. Set to 0 when you set the time. + +**Return Value:** + +A tuple containing a date and time.
+ +`[year, month, day, week, hour, minute, second, microsecond]` + +Set RTC time: + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> from machine import RTC +>>> rtc = RTC() +>>> rtc.datetime() +(2020, 9, 11, 5, 15, 43, 23, 0) +>>> rtc.datetime([2020, 3, 12, 1, 12, 12, 12, 0]) +0 +>>> rtc.datetime() +(2020, 3, 12, 4, 12, 12, 14, 0) + +``` + +### `rtc.set_alarm` + +```python +rtc.set_alarm(data_e) +``` + +This method sets RTC expiration time. The registered callback function will be called when the time expires. + +**Parameter:** + +- `year` - Integer type. Year. +- `month` - Integer type. Month. Range: [1–12]. +- `day` - Integer type. Day. Range: [1–31]. +- `week` - Integer type. Week. Range: [0–6]. 0 indicates Sunday. 1 to 6 indicates Monday to Saturday respectively. This parameter is reserved when setting time and it only takes effect when getting the time. +- `hour` - Integer type. Hour. Range: [0-23]. +- `minute` - Integer type. Minute. Range: [0-59]. +- `second` - Integer type. Second. Range: [0-59]. +- `microsecond` - Integer type. Microsecond. This parameter is reserved and it is not currently used. Set to 0 when you set the time. + +**Return Value:** + + `0` - Successful execution + + `-1` - Failed execution + +> Note: This method supports EC600U, EC200U, EC600N, EC800N and BC25 series modules. + +**Example:** + +```python +>>> data_e=rtc.datetime() +>>> data_l=list(data_e) +>>> data_l[6] +=30 +>>> data_e=tuple(data_l) +>>> rtc.set_alarm(data_e) +0 +``` + +### `rtc.register_callback` + +```python +rtc.register_callback(fun) +``` + +This method registers callback function of RTC alarm. + +**Parameter:** + +- `fun` - Function type. Callback function of RTC alarm. + +**Return Value:** + + `0` - Successful execution + + `-1` - Failed execution + +> Note: This method supports EC600U, EC200U, EC600N, EC800N and BC25 series modules. + +### `rtc.enable_alarm` + +```python +rtc.enable_alarm(on_off) +``` + +This method enables and disables RTC alarm. + +**Parameter:** + +- `on_off` - Integer type. `1` means to enable RTC alarm and `0` means to disable RTC alarm. + +**Return Value:** + + `0` - Successful execution + + `-1` - Failed execution + +> This method supports EC600U, EC200U, EC600N, EC800N and BC25 series modules. For BC25 series module, only when the callback function is set can RTC alarm be enabled. + +**Example:** + +```python +from machine import RTC +rtc = RTC() +def callback(args): + print('RTC alarm') + +rtc.register_callback(callback) +rtc.set_alarm([2021, 7, 9, 5, 12, 30, 0, 0]) +rtc.enable_alarm(1) +``` + +> Only EC600U and EC200U series modules support automatic power-on. It means that if you power off the module after RTC alarm is set, the module will power on automatically when the alarm time expires. diff --git a/docs/API_reference/en/peripherals/machine.SPI.md b/docs/API_reference/en/peripherals/machine.SPI.md new file mode 100644 index 0000000000000000000000000000000000000000..de1133379d7a8c8900c4c5cc34b14544fa7a5e23 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.SPI.md @@ -0,0 +1,1139 @@ +# SPI – Serial Peripheral Interface Bus Protocol + +This class provides bus protocol of serial peripheral interface (SPI) . + +## Constructor + +### `machine.SPI` + +
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz
    526MHz
    652MHz

    +
  • +

    The 52MHz clock frequency has high requirements for hardware.

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0960kHz
    14.8MHz
    29.6MHz
    316MHz
    419.2MHz
    525MHz
    650MHz

    +
  • +

    The 50MHz clock frequency has high requirements for hardware.

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0100KHz
    1200KHz
    2300KHz
    3400KHz
    4500KHz
    5600KHz
    6700KHz7812.5KHz
    81.625MHz
    93.25MHz
    106.5MHz
    1113MHz
    1226MHz
    1352MHz

    +
  • +

    The 52MHz clock frequency has high requirements for hardware.

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz

    +
  • [group] - Select to use SPI on different pins, with a default value of 0.
    1This group of pins does not support mounting nor flash.

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0781.25KHz
    11.5625MHz
    23.125MHz
    35MHz
    46.25MHz
    510MHz
    612.5MHz
    720MHz
    825MHz
    933.33MHz

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0781.25KHz
    XXMHz (X in [1,39])

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    097.656kHz
    1100kHz
    2812.5kHz
    31.3MHz
    41.625MHz
    52MHz
    63.25MHz
    74.333MHz
    86.6MHz
    911.93MHz
    1013MHz
    1113.92MHz
    1216.7MHz
    1320.875MHz
    1427.83MHz

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0500kHz
    11MHz
    25MHz
    310MHz
    420MHz

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

Parameter:

+
    +
  • port - Integer type. Channel selection: [0,1].

    +
  • +
  • mode - SPI working mode.
    Clock polarity CPOL: The pin level of clock signal SCLK when SPI is idle (0: low level; 1: high level)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - Clock frequency.
    0500kHz
    1~30(1~30)*1MHz

    +
  • +
+
+ +
+ +**Example:** + +```python +>>> from machine import SPI +>>> # Creates a SPI object +>>> spi_obj = SPI(1, 0, 1) +``` + +**SPI Pin Correspondences:** + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin4 pin1 pin3 pin2
spi1 pin58 pin61 pin59 pin60
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin134 pin133 pin132 pin131
spi1 pin26 pin27 pin24 pin25
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin31 pin30 pin32 pin33
spi1 pin52 pin53 pin50 pin51
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin6 pin5 pin4 pin3
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin25 pin26 pin27 pin28
spi1 pin41 pin40 pin64 pin65
spi2 pin19 pin18 pin23 pin22
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0
group0
pin58 pin61 pin59 pin60
spi0
group1
pin4 pin1 pin3 pin2
spi1
group0
pin4 pin1 pin3 pin2
spi1
group1
pin65 pin67 pin66 pin63
spi2 pin49 pin54 pin53 pin52
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin25 pin26 pin64 pin88
spi1 pin5 pin4 pin6 pin7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0
group0
pin31 pin30 pin32 pin33
spi0
group1
pin52 pin53 pin50 pin51
spi1
group0
pin52 pin53 pin50 pin51
spi1
group1
pin69 pin68 pin85 pin84
spi2 pin76 pin77 pin78 pin16
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0
group0
pin31 pin30 pin32 pin33
spi0
group1
pin52 pin53 pin50 pin51
spi1
group0
pin52 pin53 pin50 pin51
spi1
group1(EG810M_EU unsupported)
pin69 pin68 pin85 pin84
spi2 pin76 pin77 pin78 pin16
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin25 pin26 pin27 pin28
spi1 pin5 pin4 pin6 pin7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin37 pin40 pin38 pin39
spi1 pin26 pin27 pin25 pin24
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin37 pin40 pin38 pin39
spi1 pin26 pin27 pin25 pin24
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin37 pin40 pin38 pin39
spi1 pin136 pin135 pin127 pin62
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0(EC600ECN_LE&LQ unsupported) pin65 pin67 pin66 pin64
spi1 pin69 pin71 pin70 pin72
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin28 pin39 pin29 pin38
spi1(EC800ECN_LE&LQ&CG unsupported) pin52 pin53 pin50 pin51
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin4 pin1 pin3 pin2
spi1(EC800ECN_LE&LQ&CG unsupported) pin53 pin52 pin54 pin51
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi1 pin79 pin101 pin100 pin108
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0(EG912UGLAA unsupported) pin25 pin26 pin64 pin88
spi1 pin5 pin4 pin6 pin7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi1 pin4 pin1 pin3 pin2
spi2 pin58 pin61 pin59 pin60
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin31 pin30 pin32 pin33
spi1 pin52 pin53 pin50 pin51
spi2 pin74 pin75 pin76 pin77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin31 pin30 pin32 pin33
spi1 pin52 pin53 pin50 pin51
spi2 pin74 pin75 pin76 pin77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin31 pin30 pin32 pin33
spi1 pin52 pin53 pin50 pin51
spi2 pin74 pin75 pin76 pin77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin66 pin29 pin67 pin28
spi1 pin64 pin49 pin63 pin62
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin21 pin22 pin29 pin23
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin29 pin30 pin37 pin31
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin41 pin42 pin43 pin44
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin41 pin42 pin43 pin44
+ + + + + + + + + + + + + + + + + + + + +
SPI CSCLKMOSIMISO
spi0 pin5 pin4 pin6 pin7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin49 pin29 pin101 pin28
spi1 pin52 pin53 pin50 pin51
+ + + + + + + + + + + + + + + + + + + + +
SPICSCLKMOSIMISO
spi0 pin86 pin85 pin88 pin87
+ +
+ +## Methods + +### `SPI.read` + +```python +SPI.read(recv_data, datalen) +``` + +This method reads data. + +**Parameter:** + +- `recv_data` - Bytearray type. An array used to receive data. +- `datalen` - Integer type. Length of the data to be read. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `SPI.write` + +```python +SPI.write(data, datalen) +``` + +This method writes data. + +**Parameter:** + +- `data` - Bytearray type. Data to be written. +- `datalen` - Integer type. Length of data to be written. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `SPI.write_read` + +```python +SPI.write_read(r_data, data, datalen) +``` + +This method writes and reads data. + +**Parameter:** + +- `r_data ` - Bytearray type. An array used to receive data. +- `data` - Bytearray type. Data to be sent. +- `datalen` - Integer type. Length of data to be read. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `SPI.close` + +```python +SPI.close() +``` + +This method close SPI. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +> Please use this function with the peripherals. + +```python +import log +from machine import SPI +import utime + + + +spi_obj = SPI(0, 0, 1) + +# Sets the log output level +log.basicConfig(level=log.INFO) +spi_log = log.getLogger("SPI") + + +if __name__ == '__main__': + r_data = bytearray(5) # Creates a buff for receiving data + data = b"world" # Tests data + + ret = spi_obj.write_read(r_data, data, 5) # Writes data and receives data to r_data + spi_log.info(r_data) + +``` diff --git a/docs/API_reference/en/peripherals/machine.SoftSPI.md b/docs/API_reference/en/peripherals/machine.SoftSPI.md new file mode 100644 index 0000000000000000000000000000000000000000..e93e908a2b08b8c6f00cd4e79c42669921637bd3 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.SoftSPI.md @@ -0,0 +1,137 @@ +# class SoftSPI – Software Implementation of SPI Bus Protocol + +This class provides bus protocol of Serial Peripheral Interface (SPI). + +> EC600E/EC800E,FCM362K module supports this feature. + +## Constructor + +### `machine.SoftSPI` + +```python +class machine.SoftSPI(gpio_clk, gpio_cs, gpio_mosi, [gpio_miso],[wire_type],[speed],[mode],[cs_active_lvl]) +``` + +**Parameter** + +- `gpio_clk` - Integer type. The GPIO corresponding to the CLK. +- `gpio_cs` - Integer type. The GPIO corresponding to the CS. +- `gpio_mosi` - Integer type. The GPIO corresponding to the MOSI. +- `[gpio_miso]` - Integer type. The GPIO corresponding to the MISO. For 3-wire SPI, this parameter can be omitted and the MOSI can be used for receiving and sending data. +- `[wire_type]` - Integer type. Set SPI to 3-wire SPI or 4-wire SPI. `WIRE_3`: 3-wire SPI. `WIRE_4`: 4-wire SPI. Default value: 4-wire SPI. +- `[speed]` - Integer type. Transmission speed. `0`: 50 kHz. `1`: 100 kHz. Default value: 100 kHz. +- `[mode]` - Integer type. SPI mode. Range: `0`–`3`. Default value: `0`.
`0` : CPOL=0, CPHA=0
`1` : CPOL=0, CPHA=1
`2`: CPOL=1, CPHA=0
`3`: CPOL=1, CPHA=1 +- `[cs_active_lvl]` - Integer type. CS active level. `LOW`: low level. `HIGH`: high level. Default value: low level. + +**Return Value** + +The object created - Successful execution + +Error - Failed execution + +**Example** + +```python +from machine import SoftSPI +# Create a 4-wire SPI object. CLK: GPIO14. CS: GPIO11. MOSI: GPIO12. MISO: GPIO13. SPI mode: 0. Transmission speed: 100 kHz. CS: low level. +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,gpio_miso= SoftSPI.GPIO13) +# Create a 4-wire SPI object. CLK: GPIO14. CS: GPIO11. MOSI: GPIO12. MISO: GPIO13. SPI mode: 1. Transmission speed: 50 kHz. CS: high level. +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi=SoftSPI.GPIO12,gpio_miso=SoftSPI.GPIO13, + speed=0,mode=1,cs_active_lvl=SoftSPI.HIGH) +# Create a 3-wire SPI object. CLK: GPIO14. CS: GPIO11. MOSI: GPIO12. SPI mode: 0. Transmission speed: 100 kHz. CS: low level. +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,wire_type= SoftSPI.WIRE_3) +# Create a 3-wire SPI object. CLK: GPIO14. CS: GPIO11. MOSI: GPIO12. SPI mode: 2. Transmission speed: 50 kHz. CS: high level. +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi=SoftSPI.GPIO12,wire_type=SoftSPI.WIRE_3, + speed=0,mode=2,cs_active_lvl=SoftSPI.HIGH) +``` + +## Methods + +### `SoftSPI.read` + +```python +SoftSPI.read(recv_data, datalen) +``` + +This method reads data. + +**Parameter** + +- `recv_data` - Bytearray type. An array used to receive data. +- `datalen` - Integer type. Length of the data to be read. + +**Return Value** + +`0` + +### `SoftSPI.write` + +```python +SoftSPI.write(data, datalen) +``` + +This method writes data. + +**Parameter** + +- `data` - Bytes type. Data to be written. +- `datalen` - Integer type. Length of data to be written. + +**Return Value** + +`0` + +### `SoftSPI.write_read` + +```python +SoftSPI.write_read(r_data, data, datalen) +``` + +This method writes and reads data. + +**Parameter** + +- `r_data ` - Bytearray type. An array used to receive data. +- `data` - Bytes type. Data to be sent. +- `datalen` - Integer type. Length of data to be read. + +**Return Value** + +`0` + +> For 3-wire SPI, in the communicating process, MOSI is set to the output mode first and data will be sent. And then MOSI is set to the input mode and the *datalen* bytes of data will be read. + +**Example** + +> Please use this method with the peripherals. + +Example for 4-wire SPI + +```python +from machine import SoftSPI + +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,gpio_miso= SoftSPI.GPIO13) + +if __name__ == '__main__': + r_data = bytearray(5) # Create a buffer for receiving data + data = b"world" # Test data + spi.write_read(r_data, data, 5) # Write and receive data + spi.read(r_data,5) # Receive data to r_data + spi.write(data,5)# Send data +``` + +Example for 3-wire SPI + +```python +from machine import SoftSPI + +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,wire_type= SoftSPI.WIRE_3) + +if __name__ == '__main__': + r_data = bytearray(5) # Create a buffer for receiving data + data = b"world" # Test data + spi.write_read(r_data, data, 5) # Write and receive data + spi.read(r_data,5) # Receive data to r_data + spi.write(data,5)# Send data +``` + diff --git a/docs/API_reference/en/peripherals/machine.Timer.md b/docs/API_reference/en/peripherals/machine.Timer.md new file mode 100644 index 0000000000000000000000000000000000000000..84ec8d1b6d24d3a199dfad41dae494ecbc24f04c --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.Timer.md @@ -0,0 +1,128 @@ +# Timer - Control Hardware Timers + +This class provides the method of controlling hardware timer. + +> Note: For Timer0 to Timer3, each of them can only execute one task at the same time and multiple objects cannot use the same timer. + +## Constructor + +### `machine.Timer` + +```python +class machine.Timer(Timern) +``` + +**Parameter:** + +- `Timern` - Integer type. Timer number. Timer0 to Timer3 are supported. + +**Example:** + +```python +>>> # Creates a Timer object +>>> from machine import Timer +>>> timer1 = Timer(Timer.Timer1) +``` + +## Methods + +### `timer.start` + +```python +timer.start(period, mode, callback) +``` + +This method enables the timer. + +**Parameter:** + +- `period` - Integer type. Interruption period. Unit: millisecond. The period is greater than or equal to 1. + +- `mode` - Integer type. Running mode.
`ONE_SHOT` - Single mode indicating the time is executed for only once.
`PERIODIC` - Periodic mode indicates periodic execution. + +- `callback` - Function type. Timer execution function. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> def fun(args): + print("###timer callback function###") +>>> timer1.start(period=1000, mode=timer1.PERIODIC, callback=fun) +0 +###timer callback function### +###timer callback function### +###timer callback function### +…… +``` + +### `timer.stop` + +```python +timer.stop() +``` + +This method disables the timer. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +import log +import utime +from machine import Timer +import checkNet + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement. +''' +PROJECT_NAME = "QuecPython_Timer_example" +PROJECT_VERSION = "1.0.0" + +# Sets the log output level +log.basicConfig(level=log.INFO) +Timer_Log = log.getLogger("Timer") + +num = 0 +state = 1 +# Note: EC100YCN series module supports Timer0 to Timer3. +t = Timer(Timer.Timer1) + +# Creates a execution function and enters an example of timer +def timer_test(t): + global num + global state + Timer_Log.info('num is %d' % num) + num += 1 + if num > 10: + Timer_Log.info('num > 10, timer exit') + state = 0 + t.stop() # Ends the example of this timer + + +if __name__ == '__main__': + t.start(period=1000, mode=t.PERIODIC, callback=timer_test) # Enables the timer +``` + +## Constants + +| Constant | Description | +| -------------- | ---------------------------------------------------------- | +| Timer.Timer0 | Timer 0 | +| Timer.Timer1 | Timer 1 | +| Timer.Timer2 | Timer 2 | +| Timer.Timer3 | Timer 3 | +| Timer.ONE_SHOT | Single mode indicating the time is executed for only once. | +| Timer.PERIODIC | Periodic mode indicates periodic execution. | + diff --git a/docs/API_reference/en/peripherals/machine.UART.md b/docs/API_reference/en/peripherals/machine.UART.md new file mode 100644 index 0000000000000000000000000000000000000000..08d3cb7e296f51d0ccf2c13172f74cf9da4a9cb3 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.UART.md @@ -0,0 +1,1590 @@ +# UART - Duplex Serial Communication Bus + +This class transmits data through the UART. + +## Constructor + +### `machine.UART` + +
+
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT
    UART4 - STDOUT PORT

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - The data bit only supports 8 bits, int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - Data bits [5-8], int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - Data bits [8], int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl, [group])
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - Data bits [5-8], int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • [group] - The UART is selected to be used on different pins, with the default value being 0, int type.

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT (BG95M3 is not supported.)

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - Data bits [5-8], int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

Parametric Description:

+
    +
  • UARTn - UART number, int type, UARTn description is as follows:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - Baud rate, int type, supports common baud rates such as48009600192003840057600115200230400.

  • +
  • databits - Data bits [5-8], int type.

  • +
  • parity - Parity (0-None, 1-even, 2-odd), int type.

  • +
  • stopbits - Stop bit [1 ~ 2], int type.

  • +
  • flowctl - Hardware control flow (0-FC_NONE, 1-FC_HW), int type.

    +
  • +
+
+ +
+ +**UART Pin Correspondences:** + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin124pin123NULLNULL
UART2pin32pin31pin34pin33
UART4pin103pin104NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin138pin137NULLNULL
UART2pin67pin68pin65pin64
UART4pin82pin81NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin12pin11NULLNULL
UART1pin63pin66NULLNULL
UART2pin67pin68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin12pin11NULLNULL
UART1pin26pin27NULLNULL
UART2pin67pin68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin12pin11NULLNULL
UART1pin63pin66NULLNULL
UART2pin67pin68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1pin50pin51NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin29pin28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin23pin22NULLNULL
UART1pin27pin28NULLNULL
UART2pin64pin65NULLNULL
UART4pin35pin34NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin71pin72NULLNULL
UART1(flowctl = 0)pin3pin2NULLNULL
UART1(flowctl = 1)pin33pin34NULLNULL
UART2pin32pin31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin27pin28NULLNULL
UART2pin35pin34pin37pin36
UART4pin19pin18NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1(flowctl = 0)pin50pin51NULLNULL
UART1(flowctl = 1)pin22pin23NULLNULL
UART2pin18pin17NULLNULL
UART4pin29pin28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1(flowctl = 0)pin50pin51NULLNULL
UART1(flowctl = 1)pin22pin23NULLNULL
UART2pin18pin17NULLNULL
UART4pin29pin28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin23pin22NULLNULL
UART1(flowctl = 0)pin27pin28NULLNULL
UART1(flowctl = 1)pin36pin37NULLNULL
UART2pin35pin34NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin71pin72NULLNULL
UART1pin70pin69NULLNULL
UART2pin32pin31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1pin29pin28NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin124pin123NULLNULL
UART2pin32pin31pin34pin33
UART4pin116pin9NULLNULL
UART5pin125pin126NULLNULL
UART6pin106pin105NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin29pin28NULLNULL
UART2pin18pin17NULLNULL
UART5pin23pin22NULLNULL
UART6pin86pin83NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin27pin28NULLNULL
UART2pin35pin34pin37pin36
UART4pin19pin18NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin71pin72NULLNULL
UART1(flowctl = 0)pin3pin2NULLNULL
UART1(flowctl = 1)pin33pin34NULLNULL
UART2pin32pin31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1(group = 0)pin50pin51NULLNULL
UART1(group = 1)pin22pin23NULLNULL
uart1(group = 2)pin29pin28NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1(group = 0)pin50pin51NULLNULL
UART1(group = 1)pin22pin23NULLNULL
uart1(group = 2)pin29pin28NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1(group = 0)pin50pin51NULLNULL
UART1(group = 1)pin22pin23NULLNULL
uart1(group = 2)pin29pin28NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
uart0pin39pin38NULLNULL
uart1pin29pin28NULLNULL
uart2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1pin22pin23NULLNULL
UART2pin18pin17pin23pin22
UART3pin29pin28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin27pin26NULLNULL
UART1pin20pin19NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART1pin35pin34NULLNULL
UART2pin28pin27NULLNULL
+ + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin21pin22NULLNULL
+ + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin22pin21NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin23pin22NULLNULL
UART1pin27pin28NULLNULL
UART2pin35pin34pin37pin38
UART4pin36pin37NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART0pin39pin38NULLNULL
UART1pin29pin28NULLNULL
UART2pin18pin17NULLNULL
+ + + + + + + + + + + + + + + + + + + +
UART numberTX pinRX pinRTS pinCTS pin
UART2pin35pin34NULLNULL
+ +
+ +
+
+
+

Attention:

+

Uart0 is not recommended

+

EC200ACN_LA,EC200AEU_V1HA,EC200AAU_V1HA,EC200ACN_V1DA module uart1 pin number is different from other models:

+

TX: Pin26

+

RX: Pin27

+
+
+ +
+
+

Attention:

+

Uart0 is not recommended

+
+
+ +
+
+

Attention:

+

Uart0 is not recommended

+
+
+ +
+
+

Attention:

+

Uart1 for EC800MCNGA, CNGB, and CNGD modules is not available

+
+
+ +
+
+

Attention:

+

Uart1 for EG810MCNGA, CNGB modules is not available

+
+
+ +
+
+

Attention:

+

The uart1 of the EG800KCN module is not available

+
+
+ +
+
+

Attention:

+

The uart4 of the EG915NEU_AG module is not available

+
+
+ +
+
+

Attention:

+

EC200UXXAA module uart4 is not available

+
+
+ +
+
+

Attention:

+

EC600ECN_LE&LQ module uart1 is not available

+
+
+ +
+
+

Attention:

+

EG912UGL_AA module uart4 is not available

+
+
+ +
+ +
+
+
+

To use UART4, you need to call modem.main_uart_enable_set(1) to enable UART4, and restart it as follows

+
+
    +
    import modem
    +# Get Main UART enabled status 1-enabled, 0-not enabled
    +modem.main_uart_enable_get()
    +# Set Main_UART enable state 1- enabled, 0- Not enabled, restart to take effect
    +modem.main_uart_enable_set(1)
    +
    +
+
+ +
+
+

When flowctl = 1, uart1 only maps uart1 to different pins and does not turn on the flow control function.

+
+
+ + +
+
+

UART2 is initialized after the interaction port will not be used, you need to execute uart2.close() in the code or restart the module to continue to use the interaction port.

+
+
+ +
+
+

UART1 is initialized after the interaction port will not be used, you need to execute uart1.close() in the code or restart the module to continue to use the interaction port.

+
+
+
+ +**Example:** + +```python +>>> # Creates a UART object +>>> from machine import UART +>>> uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0) +``` + +## Methods + +### `uart.any` + +```python +uart.any() +``` + +This method gets the size of the unread data in the receiving cache. + +**Return Value:** + +Size of data that is unread in the receiving cache. + +**Example:** + +```python +>>> uart.any() +20 # It indicates that there is 20 bytes of unread data in the receiving cache. +``` + +### `uart.read` + +```python +uart.read(nbytes) +``` + +This method reads data from the UART. + +**Parameter:** + +- `nbytes` - Integer type. Size of data to be read. + +**Return Value:** + +Size of data that has been read. + +### `uart.write` + +```python +uart.write(data) +``` + +This method sends data to the UART. + +**Parameter:** + +- `data` - Bytes type. Data to be sent. + +**Return Value:** + +Size of data that has been sent. + +### `uart.close` + +```python +uart.close() +``` + +This method disables the UART. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `uart.control_485` + +
+
+
uart.control_485(UART.GPIOn, direction)
+
+

This method is used to control the 485 communication direction, and the specified GPIO is pulled up and down before and after the serial port sends data to indicate the 485 communication direction.

+

Parametric Description:

+
    +
  • GPIOn - GPIO Pin number to control, refer to pin definition in Pin module, int type.

    +
  • +
  • direction - Pin level change, int type, described as follows:
    1It indicates that the pin level change is: the serial port is pulled up by low before sending data, and then pulled down by high after sending data
    0It indicates that the pin level change is: the serial port is pulled down by high before sending data, and then pulled up by low after sending data

    +
  • +
+

Return value Description:

+

Returns an integer value on success0,Returns an integer value on failure-1

+

Example:

+
from machine import UART
uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0)
art1.control_485(UART.GPIO24, 1) +
+
+ +
+

This API is not supported by this model

+
+ + +
+ +### `uart.set_callback` + +```python +uart.set_callback(fun) +``` + +This method sets the callback function of the UART. This callback function will be triggered when data is received on the UART. + +**Parameter:** + +- `fun` - Callback function of the UART. Prototype: + + ``` + fun(result_list) + ``` + + Parameter of the callback function: + + - `result_list[0]`:Whether the data is received successfully. + + 0 - Received successfully + + Others - Receiving failed + + - `result_list[1]`:Port for receiving data. + + - `result_list[2]`:How much data is returned. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +>>> from machine import UART +>>> uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0) +>>> +>>> def uart_call(para): +>>> print(para) +>>> uart1.set_callback(uart_call) +``` + +**Example:** + +```python +""" +Runnnig this routine, you need to connect the main port on the EVB to a PC by a USB-to-Serial Port Adapter, enable the main port by a UART tool on the PC and send data to this port. Then you can see the messages sent by PC. +""" +import _thread +import utime +import log +from machine import UART + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on your project requirements. +''' +PROJECT_NAME = "QuecPython_UART_example" +PROJECT_VERSION = "1.0.1" + +''' + * Parameter1: Port + Note: For EC100Y-CN and EC600S-CN modules, descriptions of UARTn are as follows: + UART0 - DEBUG PORT + UART1 – BT PORT + UART2 – MAIN PORT + UART3 – USB CDC PORT + * Parameter2:Baud rate + * Parameter3:Data bits (5—8) + * Parameter4:Parity (0:NONE 1:EVEN 2:ODD) + * Parameter5:Stop bits (1–2) + * Parameter6:Flow control (0: FC_NONE 1: FC_HW) +''' + + +# Sets the log output level +log.basicConfig(level=log.INFO) +uart_log = log.getLogger("UART") + +class Example_uart(object): + def __init__(self, no=UART.UART2, bate=115200, data_bits=8, parity=0, stop_bits=1, flow_control=0): + self.uart = UART(no, bate, data_bits, parity, stop_bits, flow_control) + self.uart.set_callback(self.callback) + + + def callback(self, para): + uart_log.info("call para:{}".format(para)) + if(0 == para[0]): + self.uartRead(para[2]) + + + def uartWrite(self, msg): + uart_log.info("write msg:{}".format(msg)) + self.uart.write(msg) + + def uartRead(self, len): + msg = self.uart.read(len) + utf8_msg = msg.decode() + uart_log.info("UartRead msg: {}".format(utf8_msg)) + return utf8_msg + + def uartWrite_test(self): + for i in range(10): + write_msg = "Hello count={}".format(i) + self.uartWrite(write_msg) + utime.sleep(1) + +if __name__ == "__main__": + uart_test = Example_uart() + uart_test.uartWrite_test() + + +# Examples of running results +''' +INFO:UART:write msg:Hello count=0 +INFO:UART:write msg:Hello count=1 +INFO:UART:write msg:Hello count=2 +INFO:UART:write msg:Hello count=3 +INFO:UART:write msg:Hello count=4 +INFO:UART:write msg:Hello count=5 +INFO:UART:write msg:Hello count=6 +INFO:UART:write msg:Hello count=7 +INFO:UART:write msg:Hello count=8 +INFO:UART:write msg:Hello count=9 + +INFO:UART:call para:[0, 2, 15] +INFO:UART:UartRead msg: my name is XXX + + +''' + +``` + +## Constants + +| Constant | Description | +| ---------- | ----------- | +| UART.UART0 | UART0 | +| UART.UART1 | UART1 | +| UART.UART2 | UART2 | +| UART.UART3 | UART3 | +| UART.UART4 | UART4 | + diff --git a/docs/API_reference/en/peripherals/machine.WDT.md b/docs/API_reference/en/peripherals/machine.WDT.md new file mode 100644 index 0000000000000000000000000000000000000000..81784587bd4edebaed576e3ee1c3f9975353270c --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.WDT.md @@ -0,0 +1,75 @@ +# class WDT – Watchdog Timer + +This class provides system restart operation when application program exception occurs. + +## Constructors + +### `machine.WDT` + +```python +class machine.WDT(period) +``` + +Creates a software watchdog object. + +**Parameter:** + +- `period` - Integer type. Set software watchdog detection time. Unit: second. + +**Return Value:** + +Returns the software watchdog object. + +## Methods + +### `wdt.feed` + +```python +wdt.feed() +``` + +This method feeds the watchdog. + +**Return Value:** + +Returns integer `0` when the execution is successful. + +### `wdt.stop` + +```python +wdt.stop() +``` + +This method disables the software watchdog. + +**Return Value:** + +Returns integer `0` when the execution is successful. + +**Example:** + +```python +from machine import WDT +from machine import Timer +import utime + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on your actual projects. +''' +PROJECT_NAME = "QuecPython_WDT_example" +PROJECT_VERSION = "1.0.0" + +timer1 = Timer(Timer.Timer1) + +def feed(t): + wdt.feed() + + +if __name__ == '__main__': + wdt = WDT(20) # Enables the watchdog and sets the timeout period + timer1.start(period=15000, mode=timer1.PERIODIC, callback=feed) # Feeds the watchdog + + # wdt.stop() + +``` diff --git a/docs/API_reference/en/peripherals/machine.md b/docs/API_reference/en/peripherals/machine.md new file mode 100644 index 0000000000000000000000000000000000000000..78fec064092fb055ae1eb2e6b50e38aa49b84753 --- /dev/null +++ b/docs/API_reference/en/peripherals/machine.md @@ -0,0 +1,29 @@ +# machine - Hardware + +This module contains features related to the hardware on a particular circuit board. Most of the features in this module allow direct and unrestricted access to and control of the hardware on the system. + +## Classes + +- [class Pin – Control I/O Pins](./machine.Pin.md) + +- [class UART – Duplex Serial Communication Bus](./machine.UART.md) + +- [class Timer – Control Hardware Timers](./machine.Timer.md) + +- [class ExtInt - External Interrupt](./machine.ExtInt.md) + +- [class RTC – Real Time Clock](./machine.RTC.md) + +- [class I2C – Two-wire Serial Protocol](./machine.I2C.md) + +- [class I2C_simulation - Software Implementation of I2C Protocol](./machine.I2C_simulation.md) + +- [class SPI – Serial Peripheral Interface Bus Protocol](./machine.SPI.md) + +- [class LCD - LCD Driver](./machine.LCD.md) + +- [class WDT – Watchdog Timer](./machine.WDT.md) + +- [class KeyPad - Matrix Keyboard](./machine.KeyPad.md) + +- [class OneWire - One-Wire Protocol](./machine.OneWire.md) diff --git a/docs/API_reference/en/peripherals/misc.ADC.md b/docs/API_reference/en/peripherals/misc.ADC.md new file mode 100644 index 0000000000000000000000000000000000000000..d208fbf198ae94301b03829d9164bbdae798bb47 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.ADC.md @@ -0,0 +1,1170 @@ +# ADC - Voltage Collection + +This class collects voltage signals. + +## Constructor + +### `misc.ADC` + +```python +class misc.ADC() +``` + +**Example:** + +```python +from misc import ADC +adc = ADC() +``` + +## Methods + +### `ADC.open` + +```python +ADC.open() +``` + +This method initializes ADC. + +**Return Value:** + + `0` - Successful execution + + `-1` - Failed execution + +### `ADC.read` + +```python +ADC.read(ADCn) +``` + +This method reads voltage values of a specified channel. Unit: `mV`. + +**Parameter:** + +- `ADCn` - Integer type. ADC channel. Click here to learn more for supported channels and corresponding pins. + +**Return Value:** + +If successful, a specified channel voltage value is returned. + + `-1` - Failed execution. + +**Example:** + +```python +>>>adc.read(ADC.ADC0) # Reads voltage value of ADC0 +613 +>>>adc.read(ADC.ADC1) # Reads voltage value of ADC1 +605 +``` + +**Mapping Relationship Between ADC Passages and Pysical Pins:** + +
+ + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number19
ADC1Pin number20
+ + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number19
ADC1Pin number20
ADC2Pin number113
ADC3Pin number114
+ + + + + + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number45
ADC1Pin number44
ADC2Pin number43
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number45
ADC1Pin number44
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number45
ADC1Pin number44
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number45
ADC1Pin number44
+ + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
ADC1Pin number2
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
ADC1Pin number2
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number19
ADC1Pin number20
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number19
ADC1Pin number20
ADC2Pin number113
ADC3Pin number114
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
ADC1Pin number2
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number19
ADC1Pin number20
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number8
ADC1Pin number7
ADC2Pin number6
+ + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number2
+ + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number2
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
ADC1Pin number2
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number9
ADC1Pin number96
+ + + + + + + + + + + + + + + + + + +
ADC numberPin correspondence
ADC0Pin number24
ADC1Pin number2
+ +
+ +### ADC.close + +```python +ADC.close() +``` + +**Return Value:** + + `0` - Successful execution + + `-1` - Failed execution + +## Constants + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
ADC.ADC2ADC channel 2
ADC.ADC3ADC channel 3
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
ADC.ADC2ADC channel 2
+ + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
+ + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
+ + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
ADC.ADC2ADC channel 2
+ + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
+ + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ + + + + + + + + + + + + + + + + + +
ConstantDescription
ADC.ADC0ADC channel 0
ADC.ADC1ADC channel 1
+ +
\ No newline at end of file diff --git a/docs/API_reference/en/peripherals/misc.PWM.md b/docs/API_reference/en/peripherals/misc.PWM.md new file mode 100644 index 0000000000000000000000000000000000000000..252bd481f14dc4be578eb6224a3ddb4a48ed4989 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.PWM.md @@ -0,0 +1,187 @@ +# PWM - Pulse Width Modulation + +This class provides the feature of PWM output. + +> Note: BC25 series module does not support this feature. + +## Constructor + +### `misc.PWM` + +```python +class misc.PWM(PWM.PWMn,PWM.ABOVE_xx, highTime, cycleTime) +``` + +**Parameter:** + +- `PWM.PWMn` - Integer type. PWM channel. Click here to learn more for supported channels and corresponding pins. + +- `PWM.ABOVE_xx` - Integer type. Time range. + + For EC200U, EC600U , EG915U and EG912U series modules:
PWM.ABOVE_MS ms-level time range: (0,10]
PWM.ABOVE_1US us-level time range: (0,10000]
PWM.ABOVE_10US us-level time range: (1,10000]
PWM.ABOVE_BELOW_US ns-level time range: [100,65535] +
FCM360W:
PWM.ABOVE_MS ms-level time range:[0,1]
PWM.ABOVE_1US us-level time range:[0,1638]
PWM.ABOVE_10US us-level time range:[0,1638]
PWM.ABOVE_BELOW_US ns-level time range: [2500,65535] + +- `highTime` - Integer type. High level time. + + For ms-level time, unit: ms.
For us-level time, unit: us.
For ns-level: it needs to be calculated by users.
Frequency = 13Mhz / cycleTime
Duty cycle = highTime/ cycleTime + +- `cycleTime` - Integer type. Cycle time. + + For ms-level time, unit: ms.
For us-level time, unit: us.
For ns-level: it needs to be calculated by users.
Frequency = 13Mhz / cycleTime
Duty cycle = highTime/ cycleTime + +> Frequency support range: EC600N/EC800N/EG912N/EC600M/EC800M/EG810M/EC200A/EC200AEUV1/EC600E/EC800E/EC600K/EC800K/EG915N: 1Hz - 1MHz, EC200U/EC600U/EG915U series: 100Hz - 1MHz, BG95 series: 293Hz - 600kHz. + +**Example:** + +```python + from misc import PWM + pwm1 = PWM(PWM.PWM1, PWM.ABOVE_MS, 1, 2) +``` + +### `misc.PWM_V2` + +```python +class misc.PWM_V2(PWM_V2.PWMn,frequency, duty) +``` + +**Parameter:** + +- `PWM_V2.PWMn` - Integer type. PWM channel. Click here to learn more for supported channels and corresponding pins. + +- `frequency` - float type. will be in a form of float (I.e. 100.0 indicates 100Hz) . + +- `duty` - Integer type. a input range 0~100. The 50 means the duty ratio is 50%. + + +> EC600U/EC200U/EG912U/EG915U para `duty` can't set to 0. + +**Example:** + +```python + from misc import PWM_V2 + pwm1 = PWM_V2(PWM_V2.PWM1, 100.0, 50)#set frequence to 100Hz,duty to 50% +``` + +**Mapping Relationship Between PWM Channels and Pysical Pins:** + +The corresponding pins of EC100Y series module for PWM0-PWM3 are as follows:
PWM0 – pin19
PWM1 – pin18
PWM2 – pin23
PWM3 – pin22
The corresponding pins of EC600S-CN and EC600N modules for PWM0-PWM3 are as follows:
PWM0 – pin52
PWM1 – pin53
PWM2 – pin70
PWM3 – pin69
The corresponding pins of EC800N module for PWM0-PWM3 are as follows:
PWM0 – pin79
PWM1 – pin78
PWM2 – pin16
PWM3 – pin49
The corresponding pin of EC200U series module for PWM0 is as follows:
PWM0 – pin135
The corresponding pin of EC600U series module for PWM0 is as follows:
PWM0 – pin70
The corresponding pins of EC600M module for PWM0-PWM3 are as follows:
PWM0 – pin57
PWM1 – pin56
PWM2 – pin70
PWM3 – pin69
The corresponding pin of EG915U series module for PWM0 is as follows:
PWM0 – pin20
The corresponding pins of EC800M/EG810M module for PWM0-PWM3 are as follows:
PWM0 – pin83
PWM1 – pin78
PWM2 – pin16
PWM3 – pin49
The corresponding pins of EG912N module for PWM0-PWM3 are as follows:
PWM0 – pin21
PWM1 – pin116
PWM2 – pin107
PWM3 – pin92
+ +The corresponding pins of EG912U module for PWM0 are as follow:
PWM0 – pin20
+ +The corresponding pins of BG95 module for PWM0-PWM1 are as follow:
PWM0 – pin66
PWM1 – pin85 + +The corresponding pins of EC200A/UC200A module for PWM0-PWM2 are as follow:
PWM0 – pin1
PWM1 – pin4
PWM2 – pin6 + +The corresponding pins of EC200AEUV1 module for PWM0-PWM2 are as follow:
PWM0 – pin65
PWM1 – pin64
PWM2 – pin6
PWM3 – pin4 + +The corresponding pins of EG915N module for PWM0-PWM3 are as follow:
PWM0 – pin25
PWM1 – pin26
PWM2 – pin104
PWM3 – pin18 + +The corresponding pins of EC800K/EG800K/EG800AK module for PWM0-PWM3 are as follow:
PWM1 – pin78
PWM2 – pin83 + +The corresponding pins of BG950S module for PWM0-PWM2 are as follow:
PWM0 – pin66
PWM1 – pin38
PWM2 – pin30 + +The corresponding pins of EG800Z module for PWM0-PWM14 are as follow:
PWM0 – pin20
PWM1 – pin33
PWM2 – pin32
PWM3 – pin31
PWM4 – pin30
PWM7 – pin16
PWM8 – pin49
PWM9 – pin22
PWM10 – pin26
PWM11 – pin25
PWM12 – pin54
PWM13 – pin101
PWM14 – pin100 + +## Methods + +### `PWM.open` + +```python +PWM.open() +``` + +This methods enables PWM output. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `PWM_V2.open` + +```python +PWM_V2.open([frequency],[duty]) +``` + +This methods enables PWM output.`frequency` and `duty` are default parameters,only allow input both or neither. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `PWM.close` + +``` +PWM.close() +``` + +This methods disables PWM output. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +### `PWM_V2.close` + +``` +PWM_V2.close() +``` + +This methods disables PWM output. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +from misc import PWM +import utime +if __name__ == '__main__': + pwm = PWM(PWM.PWM0, PWM.ABOVE_MS, 1, 2) # Initializes a PWM object + pwm.open() # Enables PWM output + utime.sleep(10) + pwm.close() # Disables PWM output +``` + +```python +from misc import PWM_V2 +import utime + +if __name__ == '__main__': + pwm = PWM_V2(PWM_V2.PWM0,100.0,50) #Initializes a PWM object,frequency is 100Hz,duty is 50% + pwm.open() # Enables PWM output + utime.sleep(10) + pwm.open(200.0,40)#Enables PWM output,and set frequecy to 200Hz,duty to 40% + utime.sleep(10) + pwm.close() #Disables PWM output +``` + + + +## Constants + +| Constant | Description | Module | +| -------- | ----------- | ------------------------------------------------------------ | +| PWM.PWM0 | PWM0 | EC600S / EC600N / EC100Y/EC600U/EC200U/EC800N/
EC600M/EG915U/EC800M/EG912N/EG912U/EG915N/BG950S/EC200AEUV1/EG800Z | +| PWM.PWM1 | PWM1 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EG915N/EC800K/EG800K/EG800AK/BG950S/EC200AEUV1 | +| PWM.PWM2 | PWM2 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EG915N/EC800K//EG800K/EG800AKBG950S/EC200AEUV1 | +| PWM.PWM3 | PWM3 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EG915N/EC200AEUV1 | +| PWM.PWM3 | PWM3 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EC600E/EC800E/EC600G/
EC800G/EC200AEUV1/EC600K/FCM360W/EG915N/EG800Z | +| PWM.PWM4 | PWM4 | EG800Z | +| PWM.PWM7 | PWM7 | EG800Z | +| PWM.PWM8 | PWM8 | EG800Z | +| PWM.PWM9 | PWM9 | EG800Z | +| PWM.PWM10 | PWM10 | EG800Z | +| PWM.PWM11 | PWM11 | EG800Z | +| PWM.PWM12 | PWM12 | EG800Z | +| PWM.PWM13 | PWM13 | EG800Z | +| PWM.PWM14 | PWM14 | EG800Z | \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/misc.Power.md b/docs/API_reference/en/peripherals/misc.Power.md new file mode 100644 index 0000000000000000000000000000000000000000..d69aceb4096fed07f208773edd22ac130c8ebfd0 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.Power.md @@ -0,0 +1,102 @@ +# power - Power Off and Reboot + +Module features: power off, reboot software, get the power-on reason, get the last power-off reason and get battery voltage. + +## Power Off + +### `Power.powerDown` + +```python +Power.powerDown() +``` + +This method powers off the module. + +**Example:** + +```python +from misc import Power + +Power.powerDown() +``` + +## Reboot + +### `Power.powerRestart` + +```python +Power.powerRestart() +``` + +This method reboots the module. + +## Get the Power-on Reason + +### `Power.powerOnReason` + +```python +Power.powerOnReason() +``` + +This method gets the power-on reason. + +**Return Value:** + +| Value | Description | +| ----- | ------------------------------------------------------------ | +| 0 | Failed to get the power-on reason or unknown power-on reason | +| 1 | Press PWRKEY to power on | +| 2 | Press RESET to reboot | +| 3 | Power-on triggered by VBAT | +| 4 | Power-on triggered by RTC | +| 5 | Reboot triggered by watchdog or power-on error | +| 6 | Power-on triggered by VBUS | +| 7 | Power-on triggered by charging | +| 8 | Wake up from PSM | +| 9 | Reboot after dump occurs | + +## Get the Last Power-off Reason + +### `Power.powerDownReason` + +``` +Power.powerDownReason() +``` + +This method gets the power-off reason. + +**Return Value:** + +| Value | Description | +| ----- | ------------------------------------------ | +| 0 | Unknown reason | +| 1 | Power off normally | +| 2 | Power off due to high power supply voltage | +| 3 | Power off due to low power supply voltage | +| 4 | Power off due to high temperature | +| 5 | Power-off triggered by watchdog | +| 6 | Power-off triggered by low VRTC voltage | + +> Note: BC25PA, EC200U and EC600U series modules do not support this method. + +## Get Battery Voltage + +### `Power.getVbatt` + +```python +Power.getVbatt() +``` + +This method gets the battery voltage. Unit: mV. + +**Return Value:** + +Integer type. Voltage value. + +**Example:** + +```python +>>> Power.getVbatt() +3590 +``` + diff --git a/docs/API_reference/en/peripherals/misc.PowerKey.md b/docs/API_reference/en/peripherals/misc.PowerKey.md new file mode 100644 index 0000000000000000000000000000000000000000..51b03989cdb76d2484fa7c6221e5cdda4df36361 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.PowerKey.md @@ -0,0 +1,90 @@ +# class PowerKey - PowerKey Callback and Registration + +This class provides the feature of triggering the callback function when registering the powerkey event. + +## Constructors + +### `misc.PowerKey` + +```python +class misc.PowerKey() +``` + +**Return Value:** + +Returns the created object. + +**Example:** + +```python +from misc import PowerKey +pk = PowerKey() +``` + +## Methods + +### `PowerKey.powerKeyEventRegister` + +```python +PowerKey.powerKeyEventRegister(usrFun, pwk_mode) # ECX00U/EG91XU series supports the optional 'pwk_mode' parameter + +PowerKey.powerKeyEventRegister(usrFun) # Other platforms only support 'usrFun' parameter +``` + +This method registers the callback function for the powerkey event. + +**Parameter:** + +- `usrfun` - Callback function whose prototype is usrfun (status). The parameter is status with `0` indicating to release and `1` indicating to press. The callback will be triggered when pressing or releasing the powerkey. + +- `pwk_mode` - (Supported only by ECX00U/EG91XU series) This parameter is optional. powerkey working mode, int type: 0 by default, 0 indicates that the callback function is triggered only when the key is released, and the key must be held down for at least 500ms. '1' means that when pressed and released, both trigger the callback function registered by the user. + +**Return Value:** + +`0` - Successful registration + +`-1 ` - Failed registration + + +> Note:
+> For ECX00N/ECX00M/EG810M series modules: The callback function will be triggered when pressing and releasing the powerkey. +> +> For ECX00U/EG91XU series: Optional parameters are used to control the powerkey working mode and switch between the two features: When the working mode is 0, the callback function will be triggered only when releasing the powerkey and the key have been pressed for at least 500 ms. When the working mode is 1, the callback function will be triggered when pressing and releasing the powerkey. +> +> For all the above platforms, powerkey long press no longer triggers shutdown after registering the user's callback function. + +**Example:** + +For ECX00N/ECX00M/EG810M series modules: + +```python +from misc import PowerKey + +pk = PowerKey() + +def pwk_callback(status): + if status == 0: + print('powerkey release.') + elif status == 1: + print('powerkey press.') + +pk.powerKeyEventRegister(pwk_callback) +``` + +For ECX00U/EG91XU series modules: + +```python +from misc import PowerKey + +pk = PowerKey() + +def pwk_callback(status): + if status == 0: + print('powerkey release.') + elif status == 1: + print('powerkey press.') + +pk.powerKeyEventRegister(pwk_callback, 0) # The callback will be triggered only when the power key is released + +pk.powerKeyEventRegister(pwk_callback, 1) # The callback function will be triggered when pressing and releasing the powerkey. +``` \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/misc.USB.md b/docs/API_reference/en/peripherals/misc.USB.md new file mode 100644 index 0000000000000000000000000000000000000000..7f52385aaaebb17283cf46d7a81dae6a3c0eee68 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.USB.md @@ -0,0 +1,75 @@ +# class USB - USB Plug-in/Out Detection + +This class provides USB plug-in/out detection. + +> Note: EC600S, EC600N, EC800N, EG912N, EC200U, EC600U, EG915U, EC600M, EC800M, EC200A series modules support this feature. + +## Constructors + +### `misc.USB` + +```python +class misc.USB() +``` + +**Example:** + +```python +from misc import USB +usb = USB() +``` + +## Methods + +### `USB.getStatus` + +```python +USB.getStatus() +``` + +This method gets the current USB connection status. + +**Return Value:** + +`-1` - Failed execution + +`0 ` - Currently not connected to USB + +`1 ` - USB connected + +### `usb.setCallback` + +``` +usb.setCallback(usrFun) +``` + +This method registers USB plug-in/out callback function. When USB is inserted or unplugged, a callback function will be triggered to notify you of the current USB status. + +**Parameter:** + +- `usrFun` - Callback function whose prototype is usrFun (conn_status). The parameter is conn_status with `0` indicating not connected and `1` indicating connected. + +**Return Value:** + +`0` - Successful registration + +`-1` - Failed registration + +> Note: please do not perform blocking operations in this callback function. + +**Example:** + +```python +from misc import USB + +usb = USB() + +def usb_callback(conn_status): + status = conn_status + if status == 0: + print('USB is disconnected.') + elif status == 1: + print('USB is connected.') +usb.setCallback(usb_callback) +``` + diff --git a/docs/API_reference/en/peripherals/misc.USBNET.md b/docs/API_reference/en/peripherals/misc.USBNET.md new file mode 100644 index 0000000000000000000000000000000000000000..9db9760c2c089965b86b06086a93b9809ea16815 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.USBNET.md @@ -0,0 +1,173 @@ +# USBNET - USB Network Card + +Module feature: USB network card. + +> Note: EC600S, EC600N, EC800N, EC200U, EC600U and EC600M series modules support this feature. + +## Set Work Type of USB Network Card + +### `USBNET.set_worktype` + +```python +USBNET.set_worktype(type) +``` + +**Parameter:** + +- `type` - USBNET working type. Integer type. Type_ECM: ECM mode. Type_RNDIS: RNDIS mode. + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +> Note: It takes effect after the module is rebooted. + +## Get Work Type of USB Network Card + +### `USBNET.get_worktype` + +```python +USBNET.get_worktype() +``` + +**Return Value:** + +If successful, it returns current work type of USBNET. If failed, it returns integer type `-1`; `1` indicates ECM mode. `3 ` indicates RNDIS mode. + +## Get USENET Current State + +### `USBNET.get_status` + +```python +USBNET.get_status() +``` + +**Return Value:** + +If successful, it returns the USBNET current state. If failed, it returns the integer `-1`; `0` indicates no connection. `1` indicates successful connection. + +## Enable USB Network Card + +### `USBNET.open` + +```python +USBNET.open() +``` + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +## Disable USB Network Card + +### `USBNET.close` + +``` +USBNET.close() +``` + +**Return Value:** + +`0` - Successful execution + +`-1` - Failed execution + +**Example:** + +```python +from misc import USBNET +from misc import Power + +#work on ECM mode default +USBNET.open() + +USBNET.set_worktype(USBNET.Type_RNDIS) + +#reset the module +Power.powerRestart() + + +#After restart +from misc import USBNET + +#work on RNDIS mode +USBNET.open() +``` + +## Get NAT Enabling Status + +### `USBNET.getNat` + +```python +USBNET.getNat(simid, pid) +``` + +Gets NAT enabling status of a specified network card. + +> Note:Currently only EC200U/EC600U/EC800G series support. +> Note:If NAT mode is enabled for the EC200U/EC600U series, the pid of the enabled route cannot perform IPv6 dial-up. +> Note:If NAT mode is enabled for the EC800G series, both IPv4 and IPv6 Pids of the enabled pid cannot dial up. + +**Parameter:** + +- `simid` - Integer type. Range: 0 and 1. Currently only `0` is supported. +- `pid` - Integer type. PDP index. Range: `1-7`. + +**Return Value:** + +If successful, it returns NAT enable situation. Integer type: 0 and 1. `0`: The NAT mode is not enabled. `1`: The NAT mode is enabled. + +If failed, it returns integer `-1`. + +**Example:** + +```python +from misc import USBNET +USBNET.getNat(0, 1) +0 +``` + +## NAT Settings + +### `USBNET.setNat` + +```python +USBNET.setNat(simid, pid, nat) +``` + +Sets NAT. After the NAT configuration is successful, restart the module and the configuration takes effect. When usbnet.set_worktype () is called, the nat value changes to 1, and NAT mode is enabled for this pid. Therefore, after USBnet is closed, you can call this interface to disable NAT mode and restore the dialing function of this pid. + +> Note:Currently only EC200U/EC600U/EC800G series support. +> Note:If NAT mode is enabled for the EC200U/EC600U series, the pid of the enabled route cannot perform IPv6 dial-up. +> Note:If NAT mode is enabled for the EC800G series, both IPv4 and IPv6 Pids of the enabled pid cannot dial up. + +**Parameter:** + +- `simid` - Integer type. Range: 0 and 1. Currently only `0` is supported. +- `pid` - Integer type. PDP index. Range: `1-7`. +- `Nat` - Integer type. Range: 0 and 1. `0`: The NAT mode is not enabled; `1`: The NAT mode is enabled. + +**Return Value:** + + `0` indicates successful setting. `-1` indicates setting failure. + +**Example:** + +```python +USBNET.setNat(0, 1, 0) +0 +``` + +## Constants + +### `USBNET.Type_ECM` + +ECM mode. + +### `USBNET.Type_RNDIS` + +RNDIS mode. \ No newline at end of file diff --git a/docs/API_reference/en/peripherals/misc.md b/docs/API_reference/en/peripherals/misc.md new file mode 100644 index 0000000000000000000000000000000000000000..e581db890838556ec0c4c73775ab9199ae305bc1 --- /dev/null +++ b/docs/API_reference/en/peripherals/misc.md @@ -0,0 +1,53 @@ +# misc- Miscellaneous Features + +Module feature: shutdown, software restart, PWM and ADC. + +## Diversity Antenna Configuration Interface + +### `misc.antennaSecRXOffCtrl` + +```python +misc.antennaSecRXOffCtrl(*args) +``` + +Configures and queries the diversity antennas. (EC200A series module supports this interface). + +**Parameter:** + +It is a variable parameter: +When the number of parameter is 0, query through: misc.antennaSecRXOffCtrl(); +When the number of parameter is 1, set through: misc.antennaSecRXOffCtrl(SecRXOff_set). + +- `SecRXOff_set` - Integer type. Range: 0/1. `0`: Do not close diversity antennas `1`: Close diversity antennas. + +**Return Value:** + +Query: If successful, it returns the diversity antenna configuration. If failed, it returns integer `-1`; + +Set: If successful, it returns integer `0`; If failed, it returns integer `-1`. + +**Example:** + +```python +import misc + +misc.antennaSecRXOffCtrl() +0 +misc.antennaSecRXOffCtrl(1) +0 +misc.antennaSecRXOffCtrl() +1 +``` + +## Classes + +- [class PowerKey – PowerKey Callback Registration](./misc.PowerKey.md) +- [class PWM – Pulse Width Modulation](./misc.PWM.md) +- [class ADC - Analog-to-digital Conversion](./misc.ADC.md) +- [class USB– USB Plug-in Detection](./misc.USB.md) + +## Submodules + +- [module Power – Shutdown and Software Restart](./misc.Power.md) + +- [module USBNET – USBnet](./misc.USBNET.md) \ No newline at end of file diff --git a/docs/API_reference/en/sidebar.yaml b/docs/API_reference/en/sidebar.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e541edbd6d6c052f44ed44354bc7c232fc7cf47f --- /dev/null +++ b/docs/API_reference/en/sidebar.yaml @@ -0,0 +1,227 @@ +items: +- label: Python Std library + file: stdlib/README.md + items: + - label: uos - Basic System Services + file: stdlib/uos.md + - label: gc - Control the Garbage Collector + file: stdlib/gc.md + - label: ubinascii - Binary/ASCII Conversions + file: stdlib/ubinascii.md + - label: ucollections - Collection and Container Types + file: stdlib/ucollections.md + - label: urandom - Generate Random Numbers + file: stdlib/urandom.md + - label: math - Mathematical Functions + file: stdlib/math.md + - label: usocket - socket Module + file: stdlib/usocket.md + - label: uio - Input/Output Streams + file: stdlib/uio.md + - label: ustruct - Pack and Unpack Primitive Data Types + file: stdlib/ustruct.md + - label: ujson - JOSN Encoding and Decoding + file: stdlib/ujson.md + - label: utime - Time Related Features + file: stdlib/utime.md + - label: sys - System Related Features + file: stdlib/sys.md + - label: uzlib - zlib Decompression + file: stdlib/uzlib.md + - label: _thread - Multi-threading + file: stdlib/_thread.md + - label: uhashlib - Hash Algorithm + file: stdlib/uhashlib.md + - label: ure - Regular expression + file: stdlib/ure.md +- label: Cellular Communication + file: iotlib/README.md + items: + - label: dataCall - Data Call + file: iotlib/dataCall.md + - label: sim - SIM Card Related Features + file: iotlib/sim.md + - label: sms - SMS Related Features + file: iotlib/sms.md + - label: voiceCall - Voice Call + file: iotlib/voiceCall.md + - label: net - Networks + file: iotlib/net.md + - label: checkNet - Network Detection + file: iotlib/checkNet.md + - label: ussd - USSD function + file: iotlib/ussd.md +- label: Peripherals + file: peripherals/README.md + items: + - label: machine - Hardware + file: peripherals/machine.md + items: + - label: Pin - Control I/O Pins + file: peripherals/machine.Pin.md + - label: UART - Duplex Serial Communication Bus + file: peripherals/machine.UART.md + - label: Timer - Control Hardware Timers + file: peripherals/machine.Timer.md + - label: ExtInt - External Interrupt + file: peripherals/machine.ExtInt.md + - label: RTC - Real Time Clock + file: peripherals/machine.RTC.md + - label: I2C - Two-wire Serial Protocol + file: peripherals/machine.I2C.md + - label: I2C_simulation - Software Implementation of I2C Protocol + file: peripherals/machine.I2C_simulation.md + - label: SPI - Serial Peripheral Interface Bus Protocol + file: peripherals/machine.SPI.md + - label: SoftSPI - Software Implementation of SPI Protocol + file: peripherals/machine.SoftSPI.md + - label: LCD - LCD Driver + file: peripherals/machine.LCD.md + - label: WDT - Watchdog Timer + file: peripherals/machine.WDT.md + - label: KeyPad - Matrix Keyboard + file: peripherals/machine.KeyPad.md + - label: OneWire - One-Wire Protocol + file: peripherals/machine.OneWire.md + - label: misc - Miscellaneous Features + file: peripherals/misc.md + items: + - label: Power - Power Off and Reboot + file: peripherals/misc.Power.md + - label: PowerKey - PowerKey callback registration + file: peripherals/misc.PowerKey.md + - label: PWM - Pulse width modulation + file: peripherals/misc.PWM.md + - label: ADC - Analog-to-digital conversion + file: peripherals/misc.ADC.md + - label: USB - USB plug and pull detection + file: peripherals/misc.USB.md + - label: USBNET - USB Network Card + file: peripherals/misc.USBNET.md + - label: ethernet - Ethernet Driver + file: peripherals/ethernet.md + items: + - label: W5500 - W5500 Driver + file: peripherals/ethernet.W5500.md + - label: DM9051 - DM9051 Driver + file: peripherals/ethernet.DM9051.md + - label: CH395 - CH395 Driver + file: peripherals/ethernet.CH395.md + - label: YT8512H - YT8512H Driver + file: peripherals/ethernet.YT8512H.md + +- label: Media Library + file: medialib/README.md + items: + - label: camera - Camera Driver + file: medialib/camera.md + items: + - label: CamPreview - Camera Preview + file: medialib/camera.CamPreview.md + - label: CamDecoder - Camera Scan Code + file: medialib/camera.CamDecoder.md + - label: CamCapture - Camera Capture + file: medialib/camera.CamCapture.md + - label: audio - Audio + file: medialib/audio.md + items: + - label: Audio - Audio Playback + file: medialib/audio.Audio.md + - label: Record - Audio Record + file: medialib/audio.Record.md + - label: qrcode - QR Code Display + file: medialib/qrcode.md +- label: System Library + file: syslib/README.md + items: + - label: modem - Device + file: syslib/modem.md + - label: example - Execute Python Scripts + file: syslib/example.md + - label: atcmd - Send AT Commands + file: syslib/atcmd.md + - label: log - Log Control and Output + file: syslib/log.md + - label: system - System Configuration + file: syslib/system.md + - label: Queue - Message queue + file: syslib/Queue.md + - label: sys_bus - Session bus + file: syslib/sys_bus.md + - label: osTimer - os timer + file: syslib/osTimer.md + - label: fota - Firmware Upgrade + file: syslib/fota.md + - label: app_fota - User File Upgrade + file: syslib/app_fota.md + - label: ql_fs - Advanced file operations + file: syslib/ql_fs.md + - label: securedata - Secure data + file: syslib/securedata.md + - label: pm - Power Management + file: syslib/pm.md + items: + - label: WakeUp - Wake-Up Interrupt + file: syslib/pm.WakeUp.md +- label: Wi-Fi + file: wifilib/README.md + items: + - label: WLAN - WLAN + file: wifilib/WLAN.md + - label: ESP8266 - Espressif ESP8266 module driver + file: wifilib/WLAN.ESP8266.md + - label: ASR5803W - ASR5803W driver + file: wifilib/WLAN.ASR5803W.md +- label: BT + file: btlib/README.md + items: + - label: ble - Bluetooth Low Energy + file: btlib/ble.md + - label: bt - Classic Bluetooth + file: btlib/bt.md +- label: Network Library + file: networklib/README.md + items: + - label: ussl - SSL algorithm + file: networklib/ussl.md + - label: request - Hyper Text Transfer Protocol (HTTP) + file: networklib/request.md + - label: umqtt - MQTT Protocol + file: networklib/umqtt.md + - label: uwebsocket - websocket client + file: networklib/uwebsocket.md + - label: uping - Sending ping packets + file: networklib/uping.md + - label: ntptime - Network Time Protocol (NTP) + file: networklib/ntptime.md + - label: ftplib - ftp client + file: networklib/ftp.md + - label: lwm2m - Light Weight Machine-To-Machine + file: networklib/Lwm2m.md +- label: Positioning Application + file: gnsslib/README.md + items: + - label: gnss - External GNSS Resolver + file: gnsslib/gnss.md + - label: quecgnss - Internal GNSS Resolver + file: gnsslib/quecgnss.md + - label: wifilocator - Wi-Fi Positioning + file: gnsslib/wifilocator.md + - label: wifiScan - Wi-Fi Scan + file: gnsslib/wifiScan.md +- label: IoT Connection + file: cloudlib/README.md + items: + - label: Aws - AWS IoT Core Connection + file: cloudlib/aws.md + - label: Azure - Azure IoT Connection + file: cloudlib/azure.md + - label: Aws S3 – AWS S3 Storage Client + file: cloudlib/aws_s3.md +- label: Component Library + file: componentlib/README.md + items: + - label: uasyncio - Aoroutine + file: componentlib/uasyncio.md +- label: ErrorCode + file: errcode/README.md diff --git a/docs/API_reference/en/stdlib/README.md b/docs/API_reference/en/stdlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e2416f59d512ec030769c8ee6a010737afd99ab7 --- /dev/null +++ b/docs/API_reference/en/stdlib/README.md @@ -0,0 +1,34 @@ +# QuecPython Standard Libraries + +> - QuecPython provides built-in modules that reflect the Python standard libraries (e.g. `os` , `time`) as well as QuecPython specific modules (e.g. `bluetooth` , `machine`).

+> - Most standard library modules realize equivalent Python modules, and in a few cases provide some QuecPython-specific extension modules (e.g. `array`,`os`).

+> - To allow for extension, built-in modules can be extended from Python codes loaded into the device. + +This article introduces QuecPython build-in modules (functions and libraries). + +You can view all the built-in libraries that can be imported by entering the following code on the REPL: + +```python +help('modules') +``` + +## List of QuecPython Standard Libraries + +- [uos - Basic System Services](./uos.md) +- [gc - Reclaimg Memory Fragments](./gc.md) +- [ubinascii - Conversion between Binary and ASCII](./ubinascii.md) +- [ucollections - Collection and Container Types](./ucollections.md) +- [urandom - Random Number Generation](./urandom.md) +- [math - Mathematical Operation](./math.md) +- [usocket - socket Module](./usocket.md) +- [uio - Input and Output Streams](./uio.md) +- [ustruct - Packing and Unpacking the Raw Data Type](./ustruct.md) +- [ujson - Encoding and Decoding JSON](./ujson.md) +- [utime - Time Related Features](./utime.md) +- [sys - System Related Features](./sys.md) +- [uzlib - zlib Decompression](./uzlib.md) +- [_thread - Multi-threading](./_thread.md) +- [uhashlib - Hash Algorithm](./uhashlib.md) +- [ure - Regular expression](./ure.md) + + \ No newline at end of file diff --git a/docs/API_reference/en/stdlib/_thread.md b/docs/API_reference/en/stdlib/_thread.md new file mode 100644 index 0000000000000000000000000000000000000000..e29f6782b3d9c7372c28ae66946858ee9532a393 --- /dev/null +++ b/docs/API_reference/en/stdlib/_thread.md @@ -0,0 +1,280 @@ +# _thread- Multi-threading + +`_thread` module contains features related to thread operations, and provides methods for creating and deleting threads, and interfaces related to mutex and semaphore. + +**Example** + +```python +''' +@Author: Baron +@Date: 2020-06-22 +@LastEditTime: 2020-06-22 17:16:20 +@Description: example for module _thread +@FilePath: example_thread_file.py +''' +import _thread +import log +import utime + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement +''' +PROJECT_NAME = "QuecPython_Thread_example" +PROJECT_VERSION = "1.0.0" + + +# Sets the log output level +log.basicConfig(level=log.INFO) +thread_log = log.getLogger("Thread") + +a = 0 +state = 1 +state1 = 1 +# Creates an instance of lock +lock = _thread.allocate_lock() + +def th_func(delay, id): + global a + global state,state1 + while True: + lock.acquire() # Acquires the lock + if a >= 10: + thread_log.info('thread %d exit' % id) + lock.release() # Releases the lock + if id == 1: + state = 0 + else: + state1 = 0 + break + a += 1 + thread_log.info('[thread %d] a is %d' % (id, a)) + lock.release() # Releases the lock + utime.sleep(delay) + +def th_func1(): + while True: + thread_log.info('thread th_func1 is running') + utime.sleep(1) + +if __name__ == '__main__': + for i in range(2): + _thread.start_new_thread(th_func, (i + 1, i)) # Creates a thread. An empty tuple is paased when the function has no parameters + + thread_id = _thread.start_new_thread(th_func1, ()) # Creates a thread. An empty tuple is paased when the function has no parameters + + while state or state1: + pass + + _thread.stop_thread(thread_id) # Deletes the thread + _thread.delete_lock(lock) # Deletes the lock + thread_log.info('thread th_func1 is stopped') +``` + +## Thread + +### `_thread.get_ident` + +```python +_thread.get_ident() +``` + +Requires the current thread number. + +**Return Value** + +- Returns the current thread number. + + +### `_thread.stack_size` + +```python +_thread.stack_size(size) +``` + +Setting or getting the stack size which is used to create a thread (Unit: byte) depends on whether `size` is provided. The stack size is 8448 bytes by default, with a minimum of 8192 bytes. + +**Parameter** + +- `size`- Sets the stack size which is used to create a thread when `size` is provided. + +**Return Value** + +- Returns the stack size which is used to create a thread when `size` is not provided. + +### `_thread.start_new_thread` + +```python +_thread.start_new_thread(function, args) +``` + +Creates a thread to receive the executing function and the parameter of the executed function, and passes an empty tuple if `function` has no parameters. + +**Parameter:** + +- `function`- The executing function of the thread. + +- `args`- The parameter of the executing function of the thread, which passes an empty tuple when the function has no parameters. + +**Return Value** + +- Returns the ID of the created thread. + +### `_thread.stop_thread` + +```python +_thread.stop_thread(thread_id) +``` + +Deletes a thread. The main thread cannot be deleted. + +**Parameter** + +- `thread_id`- The returned ID when the thread is created. If the value is 0, the current thread is deleted. + +### `_thread.get_heap_size` + +```python +_thread.get_heap_size() +``` + +Gets the remaining size of heap in the system. + +**Return Value** + +- Returns the remaining size of heap in the system. (Unit: byte) + +## Mutex + +### `_thread.allocate_lock` + +```python +_thread.allocate_lock() +``` + +Creates a mutex object. + +**Return Value** + +- Returns the created mutex object. + +**Example** + +```python +import _thread +lock = _thread.allocate_lock() +``` + +### `lock.acquire` + +```python +lock.acquire() +``` + +Acquires the lock. + +**Return Value** + +- True-Successful execution; False-Failed execution. + +### `lock.release` + +```python +lock.release() +``` + +Releases the lock. + +### `lock.locked` + +```python +lock.locked() +``` + +Returns the status of the lock. + +**Return Value** + +- True indicates the status of the lock has been required by some thread; False indicates the status of the lock has not been required by the thread. + +### `_thread.delete_lock` + +```python +_thread.delete_lock(lock) +``` + +Deletes the created mutex. + +**Parameter** + +- `lock`- The returned mutex object when the mutex is created. + +## Semphore + +### `_thread.allocate_semphore` + +```python +_thread.allocate_semphore(initcount) +``` + +Creates a semphore object. + +**Parameter** + +`initcount`- The initial count value and also the maximum value of the semaphore. + +**Return Value** + +- Returns the created semphore object. + +**Example:** + +``` +import _thread +semphore = _thread.allocate_semphore(1) +``` + +### `semphore.acquire` + +```python +semphore.acquire() +``` + +Acquires the semphore. + +**Return Value** + +- True-Successful execution; False-Failed execution. + +### `semphore.release` + +```python +semphore.release() +``` + +Releases the semphore. + +### `semphore.getCnt` + +```python +semphore.getCnt() +``` + +Gets the maximum value of the semaphore count and the current remaining count value. + +**Return Value** + +- `(maxCnt, curCnt)`-tuple: maxCnt is the maximum count value, and curCnt is the current remaining count value. + +### `_thread.delete_semphore` + +```python +_thread.delete_semphore(semphore) +``` + +Deletes the created semphore. + +**Parameter** + +`semphore`- The returned semphore object when the semphore is created. + diff --git a/docs/API_reference/en/stdlib/gc.md b/docs/API_reference/en/stdlib/gc.md new file mode 100644 index 0000000000000000000000000000000000000000..56c1088ec0480b8b8ddcf6d2f182ea382987739c --- /dev/null +++ b/docs/API_reference/en/stdlib/gc.md @@ -0,0 +1,70 @@ +# gc- Control the Garbage Collector + +`gc` module realizes the garbage collection of the memory, and subsets of the corresponding CPython module. See CPython file [gc](https://docs.python.org/3.5/library/gc.html#module-gc) for more detailed information. + +## Memory Reclamation + +### `gc.enable` + +```python +gc.enable() +``` + +Enables the mechanism for automatic reclaiming memory fragments. + +### `gc.disable` + +```python +gc.disable() +``` + +Disables the mechanism for automatic reclaiming memory fragments. + +### `gc.isenabled` + +```python +gc.isenabled() +``` + +Queries whether the mechanism for automatic reclaiming memory fragments is enabled. + +**Return Value** + +- True-The mechanism for automatic reclaiming memory fragments is enabled; + + False-The mechanism for automatic reclaiming memory fragments is disabled. + +### `gc.collect` + +```python +gc.collect() +``` + +Reclaims the memory fragments actively. + +## Memory Query + +### `gc.mem_alloc` + +```python +gc.mem_alloc() +``` + +Queries the applied memory size which has been applied. + +**Return Value** + +- Returns the applied memory size. Unit: byte. + +### `gc.mem_free` + +```python +gc.mem_free() +``` + +Queries the remaining available memory size. + +**Return Value** + +- Returns the remaining available memory size. Unit: byte. + diff --git a/docs/API_reference/en/stdlib/math.md b/docs/API_reference/en/stdlib/math.md new file mode 100644 index 0000000000000000000000000000000000000000..dc378e074ef58a69b43fe348186521f2bb550503 --- /dev/null +++ b/docs/API_reference/en/stdlib/math.md @@ -0,0 +1,805 @@ +# math - Mathematical Functions + +Math module provides mathematical operation functions, and realizes subsets of the corresponding CPython module. See CPython file [math](https://docs.python.org/3.5/library/math.html#module-math) for more detailed information. + +## Returning x to the yth Power + +### `math.pow` + +```python +math.pow(x, y) +``` + +Returns x to the yth power. + +**Parameter** + +* `x`: Any type of real numbers. +* `y`: Any type of real numbers. + +**Return Value** +Floating point. `x` to the `y`th power. + +**Example** + +``` +>>> import math +>>> math.pow(2, 3) +8.0 +``` + +## Returning the Arccosine Radian Value of x + +### `math.acos` + +```python +math.acos(x) +``` + +Returns the arccosine radian value of x. + +**Parameter** + +* `x`: Any type of real numbers that range from -1 to 1, including -1 and 1. If it is smaller than -1 or larger than 1, the error will be generated. + +**Return Value** +Floating point. The arccosine radian value of `x`. + +**Example** + +``` +>>> import math +>>> math.acos(0.6) +0.9272952 +``` + +## Returning the Arcsine Radian Value of x + +### `math.asin` + +```python +math.asin(x) +``` + +Returns the arcsine radian value of x. + +**Parameter** + +* `x`: Any type of real numbers that range from -1 to 1, including -1 and 1. If it is less than -1 or greater than 1, the error will be generated. + +**Return Value** +Floating point. The arcsine radian value of `x`. + +**Example** + +``` +>>> import math +>>> math.asin(-1) +-1.570796 +``` + +## Returning the Arctangent Radian Value of x + +### `math.atan` + +```python +math.atan(x) +``` + +Returns the arctangent radian value of x. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. The arctangent radian value of `x`. + +**Example** + +``` +>>> import math +>>> math.atan(-8) +-1.446441 +>>> math.atan(6.4) +1.4158 +``` + +## Returning the Arc-tangent Value of the Given x and y Coordinate Values + +### `math.atan2` + +```python +math.atan2(x, y) +``` + +Returns the arctangent value of the given X and Y coordinate values. + +**Parameter** + +* `x`: Any type of real numbers. +* `y`: Any type of real numbers. + +**Return Value** +Floating point. The arctangent value of the coordinate (`x` ,`y`). + +**Example** + +``` +>>> import math +>>> math.atan2(-0.50,0.48) +-0.8058035 +>>> math.atan2(7, 9) +0.6610432 +``` + +## Returning the Integer of A Number Obtained by Rounding up + +### `math.ceil` + +```python +math.ceil(x) +``` + +Returns the integer of a number obtained by rounding up. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Integer type. `x`: The minimum integer which is greater than or equal to the input parameter. + +**Example** + +``` +>>> import math +>>> math.ceil(4.1) +5 +``` + +## Putting the Plus or Minus Symbol of y in front of x + +### `math.copysign` + +```python +math.copysign(x, y) +``` + +Puts the plus or minus symbol of y in front of x. + +**Parameter** + +* `x`: Any type of real numbers. +* `y`: Any type of real numbers. + +**Return Value** +Floating point. The value after putting the plus or minus symbol of `y` in front of `x`. + +**Example** + +``` +>>> import math +>>> math.copysign(5, 0) +5.0 +>>> math.copysign(5, -4) +-5.0 +>>> math.copysign(5, 9) +5.0 +``` + +## Returning the Cosine Value of the x Radian + +### `math.cos` + +```python +math.cos(x) +``` + +Returns the cosine value of the x radian. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. The cosine value of the `x` radian which ranges from -1 to 1. + +**Example** + +```python +>>> import math +>>> math.cos(3) +-0.9899925 +``` + +## Converting the Radian to the Angle + +### `math.degrees` + +```python +math.degrees(x) +``` + +Converts the radian to the angle. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. The angle which is converted by radian `x`. + +**Example** + +``` +>>> import math +>>> math.degrees(5) +286.4789 +>>> math.degrees(math.pi/2) +90.0 +``` + +## Mathematical Constant `e` + +### `math.e` + +The mathematical constant `e` is a natural constant. + +## Returning e to the xth Power + +### `math.exp` + +```python +math.exp(x) +``` + +Returns e to the xth power. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. `e` to the `x`th power. + +**Example** + +``` +>>> import math +>>> math.exp(1) +2.718282 +>>> print(math.e) +2.718282 +``` + +## Returning the Absolute Value of a Number + +### `math.fabs` + +```python +math.fabs(x) +``` + +Returns the absolute value of a number. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. The absolute value of `x`. + +**Example** + +``` +>>> import math +>>> math.fabs(-3.88) +3.88 +``` + +## Returning the Integer of a Number Obtained by Rounding down + +### `math.floor` + +```python +math.floor(x) +``` + +Returns the integer of a number obtained by rounding down. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Integer type. `x`: The maximum integer which is less than or equal to the input parameter. + +**Example** + +``` +>>> import math +>>> math.floor(8.7) +8 +>>> math.floor(9) +9 +>>> math.floor(-7.6) +-8 +``` + +## Returning the Remainder of x/y + +### `math.fmod` + +```python +math.fmod(x, y) +``` + +Returns the remainder of x/y. + +**Parameter** + +* `x`: Any type of real numbers. +* `y`: Any type of real numbers. + +**Return Value** +Floating point. The remainder of `x`/`y`. + +**Example** + +``` +>>> import math +>>> math.fmod(15, 4) +3.0 +>>> math.fmod(15, 3) +0.0 +``` + +## Returning a Tuple Consisting of the Decimal and Integer Parts of x + +### `math.modf` + +```python +math.modf(x) +``` + +Returns a tuple consisting of the decimal and integer parts of x. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** +Floating point. The remainder of `x`/`y`. + +**Example** + +``` +>>> import math +>>> math.modf(17.592) +(0.5919991, 17.0) +``` + +## Returning a Tuple (m,e) + +### `math.frexp` + +```python +math.frexp(x) +``` + +Returns a tuple (m,e). + +**Parameter** + +* `x`: Floating point. + +**Return Value** +Returns a tuple `(m,e)` , and returns the mantissa and exponent of x in the form of (m,e) . m is a floating point, e is an integer, and x == m * 2**e. If x is 0, (0.0, 0) will be returned, otherwise 0.5 <= abs(m) < 1 will be returned. + +**Example** + +``` +>>> import math +>>> math.frexp(52) +(0.8125, 6) +``` + +## Determining Whether x Is a Finite Number + +### `math.isfinite` + +```python +math.isfinite(x) +``` + +Determines whether x is a finite number. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Determines whether `x` is a finite number. If `x` is a finite number, `True` will be returned, otherwise `False` will be returned. + +**Example** + +``` +>>> import math +>>> math.isfinite(8) +True +``` + +## Determining Whether x Is an Infinity Number or a Minus Infinity Number + +### `math.isinf` + +```python +math.isinf(x) +``` + +Determines whether x is an infinity number or a minus infinity number. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +If `x` is an infinity number or a minus infinity number, `True` will be returned, otherwise `False` will be returned. + +**Example** + +``` +>>> import math +>>> math.isinf(123) +False +``` + +## Determining Whether x Is Not a Number + +### `math.isnan` + +```python +pymath.isnan(x) +``` + +Determines whether x is not a number (NaN). + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +If `x` is not a number, `True` will be returned, otherwise `False` will be returned. + +**Example** + +``` +>>> import math +>>> math.isnan(23) +False +``` + +## Returning the Value of x*(2**i) + +### `math.ldexp` + +```python +math.ldexp(x, exp) +``` + +**Returns the value of x*(2^i)** + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Floating point. The value of `x`*(2**i). + +**Example** + +``` +>>> import math +>>> math.ldexp(2, 1) +4.0 +``` + +## Returning the Natural Logarithm of x + +### `math.log` + +```python +math.log(x) +``` + +Returns the natural logarithm of x. + +**Parameter** + +* `x` : Any type of real numbers. If it is less than 0, the error will be reported. + +**Return Value** + +Floating point. The natural logarithm of `x`. + +**Example** + +``` +>>> import math +>>> math.log(2) +0.6931472 +``` + +## Mathematical Constant pi + +### `math.pi` + +Mathematical constant pi (Pi, which is generally expressed as π). + +## Converting the Angle to the Radian + +### `math.radians` + +```python +math.radians(x) +``` + +Converts the angle to the radian. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Floating point. The radian which is converted by the angle `x`. + +**Example** + +``` +>>> import math +>>> math.radians(90) +1.570796 +``` + +## Returning the Sine Value of x Radian + +### `math.sin` + +```python +math.sin(x) +``` + +Returns the sine value of x radian. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Returns the sine value of `x` radian which ranges from -1 to 1. + +**Example** + +``` +>>> import math +>>> math.sin(-18) +0.7509873 +>>> math.sin(50) +-0.2623749 +``` + +## Returning the Square Root of the Number x + +### `math.sqrt` + +```python +math.sqrt(x) +``` + +Returns the square root of x. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Floating point. The square root of `x`. + +**Example** + +``` +>>> import math +>>> math.sqrt(4) +2.0 +>>> math.sqrt(7) +2.645751 +``` + +## Returning the Tangent Value of x Radian + +### `math.tan` + +```python +math.tan(x) +``` + +Returns the tangent value of x radian. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Floating point. The tangent value of `x` radian which ranges from -1 to 1. + +**Example** + +``` +>>> import math +>>> math.tan(9) +-0.4523157 +``` + +## Returning the Integer Part of x. + +### `math.trunc` + +```python +math.trunc(x) +``` + +Returns the integer part of x. + +**Parameter** + +* `x`: Any type of real numbers. + +**Return Value** + +Integer type. The integer part of x. + +**Example** + +``` +>>> import math +>>> math.trunc(7.123) +7 +``` + +**Example** + +```python +# The example of mathematical operation math() + +import math +import log +import utime + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement +''' +PROJECT_NAME = "QuecPython_Math_example" +PROJECT_VERSION = "1.0.0" + + +if __name__ == '__main__': + # Sets the log output level + log.basicConfig(level=log.INFO) + math_log = log.getLogger("Math") + + # The value of x**y + result = math.pow(2,3) + math_log.info(result) + # 8.0 + + # Takes the minimum integer that is greater than or equal to x. If x is an integer, x will be returned + result = math.ceil(4.12) + math_log.info(result) + # 5 + + # You can use 0 when putting the plus or minus symbol of y in front of x + result = math.copysign(2,-3) + math_log.info(result) + # -2.0 + + # x must be a radian when evaluating the cosine value of x + result = math.cos(math.pi/4) + math_log.info(result) + # 0.7071067811865476 + + # Converts x from the radian to the angle + result = math.degrees(math.pi/4) + math_log.info(result) + # 45.0 + + # e indicates a constaant + result = math.e + math_log.info(result) + # 2.718281828459045 + + # exp() returns math.e(the value is 2.71828) to the xth power + result = math.exp(2) + math_log.info(result) + # 7.38905609893065 + + # fabs() returns the abosulate value of x + result = math.fabs(-0.03) + math_log.info(result) + # 0.03 + + # floor() takes the maximum integer less than or equal to x. If x is an integer, x will be returned + result = math.floor(4.999) + math_log.info(result) + # 4 + + # fmod() gets the remainder of x/y. It is a floating point + result = math.fmod(20,3) + math_log.info(result) + # 2.0 + + # frexp() returns a tuple (m,e), the following is its formula method: Divide x by 0.5 and 1 respectively, then get a range of the value in which the value of 2e is in this range.e takes the maximum integer that meets the requirement. Then evaluates x/(2e), and the value of m will be got.If x is equal to 0, then both the value of m and e are 0.The absolute value of m ranges from (0.5,1), excluding 0.5 and 1 + result = math.frexp(75) + math_log.info(result) + # (0.5859375, 7) + + # isfinite() If x is a finite number, True will be returned. Otherwise False will be returned + result = math.isfinite(0.1) + math_log.info(result) + # True + + # isinf() If x is an infinity number or a minus infinity number, True will be returned. Otherwise False will be returned + result = math.isinf(234) + math_log.info(result) + # False + + # isnan() If x is not a number, True will be returned. Otherwise False will be returned. + result = math.isnan(23) + math_log.info(result) + # False + + # ldexp() returns the value of x*(2**i) + result = math.ldexp(5,5) + math_log.info(result) + # 160.0 + + # modf() returns a tuple consisting of the decimal and integer parts of x + result = math.modf(math.pi) + math_log.info(result) + # (0.14159265358979312, 3.0) + + # pi: Mathematical constant,Pi + result = math.pi + math_log.info(result) + # 3.141592653589793 + + # sin() evaluates the sine value of x(x is a radian) + result = math.sin(math.pi/4) + math_log.info(result) + # 0.7071067811865476 + + # sqrt() evaluates the square root of x + result = math.sqrt(100) + math_log.info(result) + # 10.0 + + # tan() returns the tangent value of x(x is a radian) + result = math.tan(math.pi/4) + math_log.info(result) + # 0.9999999999999999 + + # trunc() returns the integer part of x + result = math.trunc(6.789) + math_log.info(result) + # 6 + +``` diff --git a/docs/API_reference/en/stdlib/sys.md b/docs/API_reference/en/stdlib/sys.md new file mode 100644 index 0000000000000000000000000000000000000000..bb72fc72aa590b629e726148264c2d23cf17ed7e --- /dev/null +++ b/docs/API_reference/en/stdlib/sys.md @@ -0,0 +1,103 @@ +# sys - System Related Features + +> The new architecture code has upgraded the MPY version, and sys is changed to usys. It is recommended to import the module with the following methods. + +```python +try: + import usys as sys +except ImportError: + import sys +``` + +## Constant + +### `sys.argv` + +The list of variable parameters of enabling the current program. + +### `sys.byteorder` + +Byte order (‘little’ - little-endian, ‘big’ - big-endian). + +### `sys.implementation` + +Returns the current version information of MicroPython. MicroPython has following attributes: + +- name - Character string“ micropython” + +- version - Tuple (major, minor, micro), such as (1, 7, 0) + +- _mpy - The version information of mpy file. The parse method is below. mpy_cross needs to adapt to this version information when generating mpy. + +```python +import sys +sys_mpy = sys.implementation._mpy +arch = [None, 'x86', 'x64', + 'armv6', 'armv6m', 'armv7m', 'armv7em', 'armv7emsp', 'armv7emdp', + 'xtensa', 'xtensawin'][sys_mpy >> 10] +print('mpy version:', sys_mpy & 0xff) +print('mpy sub-version:', sys_mpy >> 8 & 3) +print('mpy flags:', end='') +if arch: + print(' -march=' + arch, end='') +print() +``` + +It is recommended to use this object to distinguish MicroPython from other Python implementations. + +### `sys.maxsize` + +The maximum value of QuecPython module integers which can retain on the current platform. If it is less than the maximum value in the platform, it is the maximum value represented by the MicroPython integer (this is the case for MicroPython ports that do not support the long integer). + +### `sys.modules` + +Returns the imported modules in the current Python in dictionary form. + +### `sys.platform` + +MicroPython Operation Platform. + +### `sys.stdin` + +Standard Input (Default: USB virtual serial port. Other serial ports are optional). + +### `sys.stdout` + +Standard Output (Default: USB virtual serial port. Other serial ports are optional). + +### `sys.version` + +String type. MicroPython version. + +### `sys.version_info` + +Integer tuple type. MicroPython version. + +## **Methods** + +### `sys.exit` + +```python +sys.exit(retval=0) +``` + +Exits the current program with the given parameters. + +**Parameter** + +* `retval` - Integer type. Exiting parameter. + +This function triggers a `SystemExit` exit. If a parameter is given, its value is assigned as a parameter to `SystemExit`. + +### `sys.print_exception` + +```python +sys.print_exception(exc, file=sys.stdout) +``` + +Prints the exception information to the file object. The generated file is sys.stdout by default, which is the standard output of the exception information. + +* `exc` - Exception object. + +* `file` - The specified output file. The generated file is sys.stdout by default. + diff --git a/docs/API_reference/en/stdlib/ubinascii.md b/docs/API_reference/en/stdlib/ubinascii.md new file mode 100644 index 0000000000000000000000000000000000000000..7cea17c8a069b6fda0b417ff8b038813cd8e6409 --- /dev/null +++ b/docs/API_reference/en/stdlib/ubinascii.md @@ -0,0 +1,65 @@ +# ubinascii - Binary/ASCII Conversions + +``` +This article introduces the use of QuecPython's ubinascii module and describes features of the latest version of the ubinascii module. +``` + +The module realizes the conversion between binary data and various ASCII encoding (bidirectional), and subsets of the corresponding CPython module. See CPython file [binascii](https://docs.python.org/3.5/library/binascii.html#module-binascii) for more detailed information. + +## Constructor + +### `ubinascii.a2b_base64` + +```python +ubinascii.a2b_base64(data) +``` + +This function decodes the data encoded by base64. When decoding, invalid characters inputed by base64 will be ignored, and the bytes object will be returned. + +### `ubinascii.b2a_base64` + +```python +ubinascii.b2a_base64(data) +``` + +Encodes binary data in base64 format and returns encoded data. The encoded data followed by a line break is represented as the bytes object. + +### `ubinascii.hexlify` + +```python +ubinascii.hexlify(data, [sep]) +``` + +Converts the binary data to the hexadecimal character string. + +**Example** + +```python +>>> import ubinascii +# No sep parameter +>>> ubinascii.hexlify('\x11\x22123') +b'1122313233' +>>> ubinascii.hexlify('abcdfg') +b'616263646667' +# The second parameter sep is specified, which will be used to separate two hexadecimal numbers +>>> ubinascii.hexlify('\x11\x22123', ' ') +b'11 22 31 32 33' +>>> ubinascii.hexlify('\x11\x22123', ',') +b'11,22,31,32,33' +``` + +### `ubinascii.unhexlify` + +```python +ubinascii.unhexlify(data) +``` + +Converts the hexadecimal character string to the binary character string. + +**Example** + +```python +>>> import ubinascii +>>> ubinascii.unhexlify('313222') +b'12"' +``` diff --git a/docs/API_reference/en/stdlib/ucollections.md b/docs/API_reference/en/stdlib/ucollections.md new file mode 100644 index 0000000000000000000000000000000000000000..ba9db3a93843198f0b158a0bc77ac3090634ae4c --- /dev/null +++ b/docs/API_reference/en/stdlib/ucollections.md @@ -0,0 +1,95 @@ + +# ucollections - Collection and Container Types + +Module features: ucollections module can create a container type that saves various objects. This module realizes subsets of the corresponding CPython module. See CPython file [collections](https://docs.python.org/3/library/collections.html) for more detailed information. + +## ucollections Methods +### `ucollections.namedtuple` + +```python +mytuple = ucollections.namedtuple(name, fields) +``` + +Creates a `namedtuple` container type with a specific name and a set of fields. `namedtuple` is a subclass of the tuple that allows its fields to be accessed by index. + +**Parameter** + +- `name` - String type. Type name of the new container. +- `fields` - Tuple type. The new container type contains fields of the subtype. + +**Example** + +```python +>>> import ucollections +>>> mytuple = ucollections.namedtuple("mytuple", ("id", "name")) +>>> t1 = mytuple(1, "foo") +>>> t2 = mytuple(2, "bar") +>>> print(t1.name) +foo +``` + +### `ucollections.deque` + +```python +ucollections.deque(iterable, maxlen, flag) +``` + +Creates a bidirectional queue for `deque`. + +**Parameter** + +- `iterable` - Tuple type. It must be an empty tuple. +- `maxlen` - Integer type. Specifies maxlen and limits the bidirectional queue to its maximum length. +- `flag` - Integer type. Optional parameter; 0 (default): Not check whether the queue overflows. If the queue continues to increase when it reaches the maximum length, the previous value will be discarded. 1: When the queue reaches the maximum specified length, IndexError: full will be displayed. + +**Return Value:** + +- deque object. + + + +## deque Object Methods + +### `deque.append` + +```python +sdeque.append(data) +``` + +Inserts values into the queue. + +**Parameter** + +- `data` - Basic data type. Values need to be added to the queue. + + + +### `deque.popleft` + +```python +deque.popleft() +``` + +Removes the data on the left side of `deque` and returns the removed data. If `deque` is empty, it will lead to an index error. + +**Return Value** + +- Returns the popped value. + +**Example** + +```python +from ucollections import deque + +>>> dq = deque((),5) +>>> dq.append(1) +>>> dq.append(['a']) +>>> dq.append('a') + +>>> dq.popleft() +1 +>>> dq.popleft() +['a'] +>>> dq.popleft() +'a' +``` \ No newline at end of file diff --git a/docs/API_reference/en/stdlib/uhashlib.md b/docs/API_reference/en/stdlib/uhashlib.md new file mode 100644 index 0000000000000000000000000000000000000000..8f5aa4afe0ef96a48b3ed0c3277b3912b4b81173 --- /dev/null +++ b/docs/API_reference/en/stdlib/uhashlib.md @@ -0,0 +1,87 @@ +# uhashlib - Hash Algorithm + +``` +This article introduces the use of QuecPython's uhashlib module and describes features of the latest version of the uhashlib module. +``` + +This module realizes the hash algorithm of the binary data. + +> Note: Only supports SHA256, SHA1, MD5 currently. + +**Example** + +```python +import uhashlib +import ubinascii + +hash_obj = uhashlib.sha256() # Creates the hash object +hash_obj.update(b"QuecPython") +res = hash_obj.digest() +# b"\x1e\xc6gq\xb3\xa9\xac>\xa4\xc4O\x00\x9eTW\x97\xd4.\x9e}Bo\xff\x82u\x89Th\xfe'\xc6\xcd" +# Converts to hexadecimal +hex_msg = ubinascii.hexlify(res) +# b'1ec66771b3a9ac3ea4c44f009e545797d42e9e7d426fff8275895468fe27c6cd' +``` + + +## Constructor + +### `uhashlib.sha256` + +```python +class uhashlib.sha256(bytes) +``` + +Creates a SHA256 hash object. + +**Parameter** + +- `bytes` - Bytes type. Optional parameter. Bytes data can be passed when creating a SHA256 hash object or via hash_obj.update(). + +### `uhashlib.sha1` + +```python +class uhashlib.sha1(bytes) +``` + +Creates a SHA1 hash object. + +**Parameter** + +- `bytes` - Bytes type. Optional parameter. Bytes data can be passed when creating a SHA256 hash object or via hash_obj.update(). + +### `uhashlib.md5` + +```python +class uhashlib.md5(bytes) +``` + +Creates a MD5 hash object. + +**Parameter** + +- `bytes` - Bytes type. Optional parameter. Bytes data can be passed when creating a SHA256 hash object or via hash_obj.update(). + + +## Methods + +### hash_obj.update() + +```python +hash_obj.update(bytes) +``` + +Adds more bytes data to the hash. + +**Parameter** + +- `bytes` - Bytes type. Need to be encrypted. + +### hash_obj.digest() + +```python +hash_obj.digest(bytes) +``` + +Returns the hash of all data passed by the hash algorithm. The type of data is bytes. No more data can be sent into the hash after this method is called. + diff --git a/docs/API_reference/en/stdlib/uio.md b/docs/API_reference/en/stdlib/uio.md new file mode 100644 index 0000000000000000000000000000000000000000..0aecbfbc82a0f20cf688af16f65847716b3b93a0 --- /dev/null +++ b/docs/API_reference/en/stdlib/uio.md @@ -0,0 +1,51 @@ +# uio - Input/Output Streams + +`uio` contains additional types of stream (file-like) objects and helper functions. This feature implements a subset of the corresponding CPython feature, as described below. For more information, refer to the original CPython documentation: [io](https://docs.python.org/3.5/library/io.html#module-io). + +> Support IOBase, BytesIO, FileIO, StringIO, TextIO. + +**Example** + +```python +fd = uio.open('/usr/test.py', mode='r', encoding='UTF-8') +fd.close() +``` + +## Open File + +### `uio.open` + +```python +uio.open(name, mode='r', **kwarg) +``` + +Opens a file. This is an alias for the built-in `open()` function. + +**Parameter** + +* `name`: String type. File name. + +* `mode`: String type. Open mode. + +|Open Mode|Description| +| ---- | ---- | +| 'r' |Open a file for reading.| +| 'w' |Open a file for writing only. Overwrites the file if the file exists.| +| 'a' |Opens a file for appending. The file pointer is at the end of the file, so the content is added to the end.| + +* `**kwarg`: Variable-length parameter list. + +**Return Value** +uio object – Successful execution + +Error – Failed execution + +## Close File + +### `uio.close` + +```python +uio.close() +``` + +Closes the open files. \ No newline at end of file diff --git a/docs/API_reference/en/stdlib/ujson.md b/docs/API_reference/en/stdlib/ujson.md new file mode 100644 index 0000000000000000000000000000000000000000..32801100168046976e3e4d53028370928f9b5a4a --- /dev/null +++ b/docs/API_reference/en/stdlib/ujson.md @@ -0,0 +1,44 @@ +# ujson - JOSN Encoding and Decoding +`ujson` module realizes the convertion between the Python data object and the JSON data format, and subsets of the corresponding CPython module. See CPython file [json](https://docs.python.org/3.5/library/json.html#module-json) for more detailed information. + + +## Encoding JSON Data + +Encodes `Python` object to JSON character string. + +### `ujson.dump` + +```python +ujson.dump(obj, stream) +``` + +Serializes `obj` data object, converts it to `JSON` character string, and writes it to the specified `stream`. + +### `ujson.dumps` + +```python +ujson.dumps(obj) +``` + +Converts the data in dictionary type of `obj` to `JSON` character string. + +## Decoding JSON Data + +Decodes JSON data to `Python` object. + +### `ujson.load` + +```python +ujson.load(stream) +``` + +Parses the specified `stream` into `JSON` character string and deserializes it into `Python` object, finally returns the object. + +### `ujson.loads` + +```python +ujson.loads(str) +``` + +Parses `JSON` character string `str` and returns a `Python` object. + diff --git a/docs/API_reference/en/stdlib/uos.md b/docs/API_reference/en/stdlib/uos.md new file mode 100644 index 0000000000000000000000000000000000000000..78958afea8c8feb9a267365f5049e7266a2f8ffd --- /dev/null +++ b/docs/API_reference/en/stdlib/uos.md @@ -0,0 +1,572 @@ +# uos - Basic System Services + +`uos` module contains file system access and mounting building, and realizes subsets of the corresponding CPython module. See CPython file [os](https://docs.python.org/3.5/library/os.html#module-os) for more detailed information. + +## Deleting the File + +### `uos.remove` + +```python +uos.remove(path) +``` + +Deletes the file. + +**Parameter** + +* `path` - String type. The file name. + +## Changing the Current Directory + +### `uos.chdir` + +```python +uos.chdir(path) +``` + +Changes the current directory. + +**Parameter** + +* `path` - String type. The directory name. + +## Getting the Current Path + +### `uos.getcwd` + +```python +uos.getcwd() +``` + +Gets the current path. + +**Return Value** + +The return value is in string type, which indicates the current path. + +## Listing the Specified Directory File + +### `uos.listdir` + +```python +uos.listdir( [dir] ) +``` + +If the parameter is not provided, the current directory file will be listed. Otherwise the specified directory file will be listed. + +**Parameter** + +* `dir` - String type. An optional parameter indicates the directory name. Default directory: ‘/’ . + +**Return Value** + +The return value is in tuple type, which indicates listing all existing objects under the path (directories and files). + +**Example** + +```python +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’] +``` + +## Creating A Directory + +### `uos.mkdir` + +``` +uos.mkdir(path) +``` + +Creates a directory. + +**Parameter** + +* `path` indicates the name of the directory to be created. It is in the relative path of the directory. + +**Example** + +```python +>>> uos.mkdir('testdir') +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’, 'testdir'] +``` + +## Renaming the File + +### `uos.rename` + +```python +uos.rename(old_path, new_path) +``` + +Renames the file. + +**Parameter** + +* `old_path` - String type. The old file or directory name. +* `new_path` - String type. The new file or directory name. + +**Example** + +```python +>>> uos.rename('testdir', 'testdir1') +``` + +## Deleting the Specified Directory + +### `uos.rmdir` + +```python +uos.rmdir(path) +``` + +Deletes the specified directory. + +**Parameter** + +* `path` - String type. The directory name. It is in the relative path of the directory. + +**Example** + +```python +>>> uos.rmdir('testdir') +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’] +``` + +## Listing the Parameters of the Current Directory + +### `uos.ilistdir` + +```python +uos.ilistdir( [dir] ) +``` + +This function returns an iterator that generates the 3-tuple corresponding to the listed entry. + +**Parameter** + +* `dir` - String type. An optional parameter indicating the directory name. If the parameter is not provided, the current directory will be listed by default. Otherwise the directory specified by dir will be listed. + +**Return Value** + +This function returns an iterator that generates the 3-tuple corresponding to the listed entry. + +The tuple has the form of `(name, type, inode[, size])`: + +* `name` - String type. The name of the entry. If dir is a byte object, the name is in byte type; +* `type` - Integer type. The type of the entry. 0x4000 indicates the directory, 0x8000 indicates the regular file; +* `inode` is an integer corresponding to the index node of the file, and may be 0 for file systems that don’t have such a notion; +* Some modules may return a 4-tuple that includes the entry's size. For file entries, size is an integer representing the size of the file. If it is unknown, the value will be -1. Its meaning is currently undefined for the directory entry. + +## Getting the Status of the File or Directory + +### `uos.stat` + +```python +uos.stat(path) +``` + +Gets the status of the file or directory. + +**Parameter** + +* `path` - String type. The name of the file or directory. + +**Return Value** + +The return value is a tuple with the form of: + +`(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)` + +* `mode` – inode protection mode +* `ino` – inode node number +* `dev` – inode device +* `nlink` – inode number of links +* `uid ` – User ID of the owner +* `gid` – Group ID of the owner +* `size` – Size of the file. Unit: byte +* `atime` – Last access time +* `mtime` – The last modification time +* `ctime` – "ctime" reported by the operating system. On some systems it is the latest time of meta-data changing, on others it is the creation time. See the document of the module for details. + +## Getting the Status of the File System + +### `uos.statvfs` + +```python +uos.statvfs(path) +``` + +Gets the status of the file system. + +**Parameter** + +* `path` - String type. The name of the file or directory. + +**Return Value** + +Returns a tuple with the file system information: + +`(f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax)` + +* `f_bsize` – Block size of the file system. Unit: byte. +* `f_frsize` – Fragment size. Unit: byte. +* `f_blocks` – Number of data blocks in the file system. +* `f_bfree` – Number of available blocks. +* `f_bavai` – Number of available blocks for non-administrator. +* `f_files` – Number of file inodes. +* `f_ffree` – Number of available file inodes. +* `f_favail` – Number of available file inodes for administrator. +* `f_flag` – Mounting flags. +* `f_namemax` – The maximum length of the file. Unit: byte. + +**Example** + +```python +>>> import uos +>>> res = uos.statvfs("main.py") +>>> print(res) +(4096, 4096, 256, 249, 249, 0, 0, 0, 0, 255) +``` + +## Getting the Information of the Underlying System or Its Operating System + +### `uos.uname` + +```python +uos.uname() +``` + +Gets the information of the underlying system or its operating system. + +**Return Value** + +The form of the return value of this interface differs from that of the official Micropython interface. This interface returns a tuple with the form of: + +`(sysname, nodename, release, version, machine)` + +* `sysname` – String type. The name of the underlying system. +* `nodename` – String type. Network name (it can be the same as sysname). +* `release` – String type. The version of the underlying system. +* `version` – String type. MicroPython version and build date. +* `machine` – String type. Identifier of the underlying hardware (such as the main board and CPU). +* `qpyver` – String type. Short QuecPython version number. + +**Example** + +```python +>>> import uos +>>> uos.uname() +('sysname=EC600S-CNLB', 'nodename=EC600S', 'release=1.12.0', 'version=v1.12 on 2020-06-23', 'machine=EC600S with QUECTEL', 'qpyver=V0001') +>>> uos.uname()[0].split('=')[1] # The value of sysname can be obtained in this way +'EC600S-CNLB' +``` + +### `uos.uname2` + +```python +uos.uname2() +``` + +Gets the information of the underlying system or its operating system. + +**Return Value** + +The form of the return value of this interface is the same as that of the official Micropython interface. Please note the difference from the return value of uos.uname(). The return value with the form of: + +`(sysname, nodename, release, version, machine, qpyver)` + +* `sysname` – String type. The name of the underlying system. +* `nodename` – String type. Network name (it can be the same as sysname). +* `release` – String type. The version of the underlying system. +* `version` – String type. MicroPython version and build date. +* `machine` – String type. Identifier of the underlying hardware (such as the mainboard and CPU). +* `qpyver` – String type. QuecPython short version number. + +**Example** + +```python +>>> import uos +>>> uos.uname2() +(sysname='EC600S-CNLB', nodename='EC600S', release='1.12.0', version='v1.12 on 2020-06-23', machine='EC600S with QUECTEL', qpyver='V0001') +>>> uos.uname2().sysname # The value of sysname can be obtained directly in this way +'EC600S-CNLB' +>>> uos.uname2().machine +'EC600S with QUECTEL' +``` + +## Returning A Bytes Object with *n* Random Bytes + +### `uos.urandom` + +```python +uos.urandom(n) +``` + +Returns a bytes object with *n* random bytes. If the module is equipped with a hardware random number generator, the object will be generated by the hardware random number generator. + +**Parameter** + +* `n` - Integer type. Number of random bytes. + +**Return Value** + +A bytes object with *n* random bytes. + +**Example** + +```python +>>> import uos +>>> uos.urandom(5) +b'\xb3\xc9Y\x1b\xe9' +``` + +## Registering the Storage Device - SPI - SD Card + +> Only EC600N and EC800N series modules support this feature currently. + +### `uos.VfsFat` + +```python +uos.VfsFat(spi_port, spimode, spiclk, spics) +``` + +Initializes the SD card through SPI prototype and SD card communication. + +**Parameter** + +* `spi_port` - Integer type. Channel selection [0,1]. +* `spimode` - Integer type. SPI work mode (mode 0 is the most commonly used):
+|Parameter|Work Mode| +| ---- | ---- | +| 0 |CPOL=0, CPHA=0| +| 1 | CPOL=0, CPHA=1| +| 2 |CPOL=1, CPHA=0| +| 3 |CPOL=1, CPHA=1| +> Clock polarity CPOL: The pin level of the clock signal SCLK when SPI is idle. (0: low level when idle; 1: high level when idle). + +* `spiclk` - Integer type. + +|Parameter|Clock Frequency| +| ---- | ---- | +| 0 |812.5 KHz| +| 1 |1.625 MHz| +| 2 |3.25 MHz| +| 3 |6.5 MHz| +| 4 |13 MHz| + +* `spics` - Integer type. Assigns the CS pin as any GPIO. Hardware CS can connect this specified pin or the default SPI CS pin. + +> 1-n: Assigns Pin.GPIO1 - Pin.GPIOn as the CS pin. + +**Return Value** + +If the execution is successful, VfsFat object will be returned. If the execution is failed, it will be stuck. + +**Example** + +```python +>>> cdev = uos.VfsFat(1, 0, 4, 1) +``` + +## Registering the Storage Device - SDIO - SD Card + +> Only EC600U,EC200A and EC200U series modules support this feature currently. + +### `uos.VfsSd` + +```python +uos.VfsSd(str) +``` + +Initializes the SD card through SDIO prototype. + +* `str`– String type. Inputs "sd_fs". + +**Return Value** + +If the execution is successful, vfs object will be returned. If the execution is failed, the error will be reported. + +**Pin Description** + +| Module | Pin | +| ------ | ------------------------------------------------------------ | +| EC600U | CMD: Pin 48
DATA0: Pin 39
DATA1: Pin 40
DATA2: Pin 49
DATA3: Pin 50
CLK: Pin 132 | +| EC200U | CMD: Pin 33
DATA0: Pin 31
DATA1: Pin 30
DATA2: Pin 29
DATA3: Pin 28
CLK: Pin 32 | +| EC200A | CMD: Pin 33
DATA0: Pin 31
DATA1: Pin 30
DATA2: Pin 29
DATA3: Pin 28
CLK: Pin 32 | + +**Example** + +```python +>>> from uos import VfsSd +>>> udev = VfsSd("sd_fs") +``` + +## Setting the Pin for SD Card Detection + +### `uos.set_det` + +```python +uos.set_det(vfs_obj.GPIOn,mode) +``` + +Assigns the pin and mode for detecting the insertion and removal of the SD card. + +**Parameter** + +* `vfs_obj.GPIOn` - Integer type. GPIO pin number for detecting the insertion and removal of the SD card. Please refer to the definition of [Pin](../QuecPython类库/machine.Pin.md) module. +* `mode` - Integer type.
0: After the SD card is inserted, the detection port is in low level. After the SD card is removed, the detection port is in high level.
1: After the SD card is inserted, the detection port is in high level. After the SD card is removed, the detection port is in low level. + +**Return Value** + +`0` - Successful execution; `-1` - Failed execution. + +**Example** + +```python +>>> from uos import VfsSd +>>> udev = VfsSd("sd_fs") +>>> uos.mount(udev, '/sd') +>>> udev.set_det(udev.GPIO10,0)#Uses GPIO10 as the pin to detect the SD card. After the SD card is inserted, the detection port is in low level. After the SD card is removed, the detection port is in high level (actual usage depends on the hardware) +``` + +## Setting the Callback Function of Inserting And Removing the SD Card + +### `uos.set_callback` + +```python +uos.set_callback(fun) +``` + +Sets the user callback function when the card is inserted or removed. + +**Parameter** + +* `fun` - Function type. When the card is inserted or removed, `[ind_type]` will be called. +* `ind_type` - Event type. 0: Removing the card; 1: Inserting the card. + +**Return Value** + +`0` - Successful execution; `-1` - Failed execution. + +**SD Card (SDIO port) Example** + +> Only EC600U,EC2OOA and EC200U series modules support this feature currently. + +**Example** + +```python +from uos import VfsSd +import ql_fs +udev = VfsSd("sd_fs") +uos.mount(udev, '/sd') +udev.set_det(udev.GPIO10,0) +#Reads and writes the file +f = open('/sd/test.txt','w+') +f.write('1234567890abcdefghijkl') +f.close() +uos.listdir('/sd') +f = open('/sd/test.txt','r') +f.read() +f.close() +#The callback function of inserting and removing the card +def call_back(para): + if(para == 1): + print("insert") + print(uos.listdir('/usr')) + print(ql_fs.file_copy('/usr/1.txt','/sd/test.txt'))#Copies test.txt from the SD card to 1.txt in usr + print(uos.listdir('/usr')) + elif(para == 0): + print("plug out") + +udev.set_callback(call_back) +``` + +## Registering the Storage Device littleFS - SPI NOR FLASH + +> Only ECx00M&EG810M&ECx00U&EG91xU series platform is supported. Only 4-wire spi nor flash is supported. ECx00U&EG91xU spi_clk = 3 is not recommended. + +### `uos.VfsLfs1` + +```python +uos.VfsLfs1(readsize,progsize,lookahead,pname,spi_port,spi_clk) +``` + +Communicates with the external NOR FLASH through SPI. The storage device is mounted as the littleFS file system through SPI. ECx00U&EG91xU spi clk = 3 is not recommended. + +**Parameter** + +* `readsize` - Integer type. Reserved. It is not used yet. +* `progsize` - Integer type. Reserved. It is not used yet. +* `lookahead` - Integer type. Reserved. It is not used yet. +* `pname` - String type. The partition name is fixed to "ext_fs". It will be expanded later. +* `spi_port` - Integer type. See SPI chapter for supported ports. +* `spi_clk` - Integer type.
+|Parameter|Clock Frequency| +| ---- | ---- | +| 0 |6.25 MHz| +| 1 |12.5 MHz| +| 2 |25 MHz| +| 3 |50 MHz| +| 4 |3.125 MHz| +| 5 |1.5625 MHz| +| 6 |781.25 KHz| +**Return Value** + +VfsLfs1 object - Successful execution; OSError 19 - Failed execution. + +**Example** + +```python +>>>ldev = uos.VfsLfs1(32, 32, 32, "ext_fs",1,0) +>>>uos.mount(ldev,'/ext') +>>>f = open('/ext/test.txt','w+') +>>>f.write('hello world!!!') +>>>f.close() + +>>>uos.listdir('ext') + +>>>f = open('/ext/test.txt','r') +>>>f.read() +>>>f.close() + +``` + +## Mounting the File System + +### `uos.mount` + +```python +uos.mount(vfs_obj, path) +``` + +Mounts the file system in substantial form (such as littleFS or FATFS ) to the virtual file system(VFS). + +**Parameter** + +* `vfs_obj` - vfs object. The object of the file system. +* `path` - String type. The root directory of the file system. + +**Example** + +```python +>>> cdev = uos.VfsFat(1, 0, 4, 1) +>>> uos.mount(cdev, '/sd') +``` + +**SD Card (SPI port) Example** + +> Only EC600N, EC800N, EC600U and EC200U series module support this feature currently. + +```python +>>> cdev = uos.VfsFat(1, 0, 4, 1) +>>> uos.mount(cdev, '/sd') +>>> f = open('/sd/test.txt','w+') +>>> f.write('0123456') +>>> f.close() +>>> uos.listdir('/sd') +>>> f = open('/sd/test.txt','r') +>>> f.read() +>>> f.close() +``` diff --git a/docs/API_reference/en/stdlib/urandom.md b/docs/API_reference/en/stdlib/urandom.md new file mode 100644 index 0000000000000000000000000000000000000000..78a388300d4a3ca2ec8a75d1cc88521ea0907ecb --- /dev/null +++ b/docs/API_reference/en/stdlib/urandom.md @@ -0,0 +1,266 @@ +# urandom - Generate Random Numbers + +urandom module provides the tool for random number generation. + +## Generating Elements in Object obj Randomly + +### `urandom.choice` + +```python +urandom.choice(obj) +``` + +Generates elements in object obj randomly. The type of obj is string. + +**Parameter** + +* `obj` - String type. + +**Return Value** + +String type. Some random element in `obj`. + +**Example** + +``` +>>> import urandom +>>> urandom.choice("QuecPython") +'t' +``` + +## Generating A Decimal Number in the Range of k bits Randomly + +### `urandom.getrandbits` + +```python +urandom.getrandbits(k) +``` + +Generates a decimal number in the range of k bits randomly. + +**Parameter** + +* `k` - Integer type. Indicates the range.(Unit: bit) + +**Return Value** + +Integer type. A random decimal number in the range of k bits. + +**Example** + +``` +>>> import urandom +>>> urandom.getrandbits(1) #1 bit binary, ranging from 0 to 1 (decimal: 0–1) +1 +>>> urandom.getrandbits(1) +0 +>>> urandom.getrandbits(8) #8 bit binary,ranging from 0000 0000 to 1111 11111 (decimal:0–255) +224 +``` + +## Generating An Integer Between start And end Randomly + +### `urandom.randint` + +``` +urandom.randint(start, end) +``` + +Generates an integer between start and end. + +**Parameter** + +* `start` - Integer type. The minimum value in the interval. +* `end` - Integer type. The maximum value in the interval. + +**Return Value** + +Integer type. A random integer between `start ` and `end`. + +**Example** + +``` +>>> import urandom +>>> urandom.randint(1, 4) +4 +>>> urandom.randint(1, 4) +2 +``` + +## Generating A Floating Point Between 0 and 1 Randomly + +### `urandom.random` + +```python +urandom.random() +``` + +Generates a floating point between 0 and 1. + +**Return Value** + +Floating point. The floating point between 0 and 1. + +**Example** + +``` +>>> import urandom +>>> urandom.random() +0.8465231 +``` + +## Generating A Positive Integer Ascending to step And Between start and end Randomly + +### `urandom.randrange` + +```python +urandom.randrange(start, end, step) +``` + +Generates a positive integer ascending to step and between start and end randomly. + +**Parameter** + +* `start` - Integer type. The minimum value in the interval. +* `end` - Integer type. The maximum value in the interval. +* `step` - Integer type. The length of ascending. + +**Return Value** + +Integer type. A random integer between `start ` and `end`. + +**Example** + +``` +>>> import urandom +>>> urandom.randrange(0, 8, 2) +0 +>>> urandom.randrange(0, 8, 2) +6 +``` + +## Specifying the Seed of A Random number + +### `urandom.seed` + +```python +urandom.seed(sed) +``` + +Specifies the seed of a random number, generally used in conjunction with other random number generation functions. + +**Parameter** + +* `sed` - Integer type. + +**Example** + +```python +>>> import urandom +>>> urandom.seed(20) #Specifies the seed of a random number +>>> for i in range(0, 15): #Generates the random sequence in the range of 0–15 +... print(urandom.randint(1, 10)) +... +8 +10 +9 +10 +2 +1 +9 +3 +2 +2 +6 +1 +10 +9 +6 +``` + +## Generating A Floating Point Between start And end Randomly + +### `urandom.uniform` + +```python +urandom.uniform(start, end) +``` + +**Parameter** + +* `start` - Any type of real numbers. The minimum value in the interval. +* `end` - Any type of real numbers. The maximum value in the interval. + +**Return Value** + +Floating point. A random number between `start ` and `end`. + +**Example** + +``` +>>> import urandom +>>> urandom.uniform(3, 5) +3.219261 +>>> urandom.uniform(3, 5) +4.00403 +``` + +**Example** + +```python +''' +@Author: Baron +@Date: 2020-06-22 +@LastEditTime: 2020-06-22 17:16:20 +@Description: example for module urandom +@FilePath: example_urandom_file.py +''' +import urandom as random +import log +import utime + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement +''' +PROJECT_NAME = "QuecPython_Random_example" +PROJECT_VERSION = "1.0.0" + +log.basicConfig(level=log.INFO) +random_log = log.getLogger("random") + + +if __name__ == '__main__': + # urandom.randint(start, end) + # random between 1–4 + num = random.randint(1, 4) + random_log.info(num) + + # random between 0–1 + num = random.random() + random_log.info(num) + + # urandom.unifrom(start, end) + # Generates a floating point between start and end + num = random.uniform(2, 4) + random_log.info(num) + + # urandom.randrange(start, end, step) + # 2-bit binary,the range is [00–11] (0–3) + num = random.getrandbits(2) + random_log.info(num) + + # 8-bit binary,the range is [0000 0000–1111 11111] (0–255) + num = random.getrandbits(8) + random_log.info(num) + + # urandom.randrange(start, end, step) + # Generates an ascending positive integer from start to end randomly + num = random.randrange(2, 8, 2) + random_log.info(num) + + # urandom.choice(obj) + # Generates the number of elements in the object randomly + num = random.choice("QuecPython") + random_log.info(num) + +``` diff --git a/docs/API_reference/en/stdlib/ure.md b/docs/API_reference/en/stdlib/ure.md new file mode 100644 index 0000000000000000000000000000000000000000..bdbddef3183b701b44a785b30354cee24bea1799 --- /dev/null +++ b/docs/API_reference/en/stdlib/ure.md @@ -0,0 +1,128 @@ +# ure – Regular Expression + +This feature matches data by regular expression. + +>Currently, only a few operators are supported. + +**Example** + +```python +import ure + +res = ''' +$GNRMC,133648.00,A,3149.2969,N,11706.9027,E,0.055,,311020,,,A,V*18 +$GNGGA,133648.00,3149.2969,N,11706.9027,E,1,24,1.03,88.9,M,,M,,*6C +$GNGLL,3149.2969,N,11706.9027,E,133648.00,A,A*7A +$GNGSA,A,3,31,26,11,194,27,195,08,09,03,193,04,16,1.41,1.03,0.97,1*31 +''' + +r = ure.search("GNGGA(.+?)M", res) +print(r.group(0)) +``` + +## Compile and Generate Regular Expression + +### `ure.compile` + +```python +ure.compile(regex) +``` + +Compiles a regular expression and generates a regular-expression object, used by *ure.match()* and *ure.search()*. + +**Parameter** + +- `regex` – String type. A regular expression. + + +## Match Regular Expression + +### `ure.match` + +```python +ure.match(regex, string) +``` + +Matches the compiled regular expression against *string*. Match always happens from the start position in a string. + +**Parameter** + +- `regex` – String type. A regular expression. +- `string` – The string to be matched. + +**Return Value** + +- A matched object – Successful execution +- None – Failed execution + +## Search Regular Expression + +### `ure.search` + +```python +ure.search(regex, string) +``` + +Searches for the compiled regular expression in *string* and returns the first successful match. + +**Parameter** + +- `regex` – String type. A regular expression. +- `string` – The string in which you search for the compiled regular expression + +**Return Value** + +- A matched object – Successful execution +- None – Failed execution + + +## Match Single String + +### `match.group` + +```python +match.group(index) +``` + +Matches objects as returned by *ure.match()* and *ure.search()*. + +**Parameter** + +- `index` – Integer type. The index of the groups of the match. In a regular expression, *match.group()* proposes the string captured by grouping. *index* is 0 for the entire match. *index* is captured by the compiled regular expression and an error occurs when the group does not exist. + +**Return Value** + +- The string matching the entire regular expression. + + +## Constants + +### Supported Operators +- `‘.’` – Character type. Match any character. +- `‘[]’` – Character type. Match set of characters. Individual characters and ranges are supported, including negated sets. +- `‘^’` – Character type. Match the start of the string. +- `‘$’` – Character type. Match the end of the string. +- `‘?’` – Character type. Match zero or one of the previous sub-pattern. +- `‘*’` – Character type. Match zero or more of the previous sub-pattern. +- `‘+’` – Character type. Match one or more of the previous sub-pattern. +- `‘??’` – Character type. Non-greedy version of `?`, match zero or one. +- `‘*?’` – Character type. Non-greedy version of `*`, match zero or more. +- `‘+?’` – Character type. Non-greedy version of `+`, match one or more. +- `‘\|’` – Character type. Match either the left-hand side or the right-hand side sub-patterns of this operator. +- `‘\d’` – Character type. Match digit. +- `‘\D’` – Character type. Match non-digit. +- `‘\s’` – Character type. Match whitespace. +- `‘\S’` – Character type. Match non-whitespace. +- `‘\w’` – Character type. Match "word characters" (ASCII only). +- `‘\W’` – Character type. Match "word characters" (ASCII only). + + +### Not Supported Operators +- `‘{m,n}’` – Counted repetitions. +- `‘(?P...)’` – Named groups. +- `‘(?:...)’` – Non-capturing groups. +- `‘\b’` – More advanced assertions. +- `‘\B’` – More advanced assertions. +- `‘\r’` – Special character escapes – use Python’s own escaping instead. +- `‘\n’` – Special character escapes – use Python’s own escaping instead. + diff --git a/docs/API_reference/en/stdlib/usocket.md b/docs/API_reference/en/stdlib/usocket.md new file mode 100644 index 0000000000000000000000000000000000000000..6a63937dd41741db25f83ed399eaee0afb178e68 --- /dev/null +++ b/docs/API_reference/en/stdlib/usocket.md @@ -0,0 +1,438 @@ +# usocket - Socket Module + +``` +This article introduces the use of QuecPython's usocket module and describes features of the latest version of the usocket module. +``` + +This module provides access to the BSD socket interface, and realizes subsets of the corresponding CPython module. See CPython file [socket](https://docs.python.org/3.5/library/socket.html#module-socket) for more detailed information. + +**Example** + +```python +# Imports the usocket module +import usocket +import log +import utime +import checkNet + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on project requirement +''' +PROJECT_NAME = "QuecPython_Socket_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# Sets the log output level +log.basicConfig(level=log.INFO) +socket_log = log.getLogger("SOCKET") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + socket_log.info('Network connection successful!') + + # Creates a socket instance + sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) + # Parses the name of domain + sockaddr=usocket.getaddrinfo('www.tongxinmao.com', 80)[0][-1] + # Establishes the connection + sock.connect(sockaddr) + # Sents messages to the server + ret=sock.send('GET /News HTTP/1.1\r\nHost: www.tongxinmao.com\r\nAccept-Encoding: deflate\r\nConnection: keep-alive\r\n\r\n') + socket_log.info('send %d bytes' % ret) + # Receives meaasges from the server + data=sock.recv(256) + socket_log.info('recv %s bytes:' % len(data)) + socket_log.info(data.decode()) + + # Closes the connection + sock.close() + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) +``` + + +## Constructors + +### `usocket.socket` + +```python +class usocket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) +``` + +Creates a socket object based on the specified address family, socket type, and protocol type parameters. Note that it is not necessary to specify *proto* in most cases, nor is it recommended, because some MicroPython ports may omit the `IPPROTO_*` constant. + +**Parameter** + +- `af` - The address family (please refer to the Constants). + +- `type` - The socket type (please refer to the Constants). + +- `proto` - The protocol number (please refer to the Constants). + + +Example: +```python +import usocket +# Creates a TCP-based stream socket +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) +# Creates a UDP-based datagram socket +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) +# Creates a TCP-based server socket +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.IPPROTO_TCP_SER) +# Creates a TCP-based client socket(It should be used with bind, and the socket address can be customized) +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.TCP_CUSTOMIZE_PORT) +``` + +### `usocket.getaddrinfo` + +```python +usocket.getaddrinfo(host, port, family=0) +``` + +Parses the domain name of DNS. Parses the domain name of the host (host) and port (port) into a 5-tuple sequence used to create the socket. The structure of the tuple is below: +`(family, type, proto, canonname, sockaddr)` + +**Parameter** + +- `host` - The domain name of the host. +- `port` - The port. +- `family` - Address family, optional parameter: + - `usocket.AF_INET` - Returns only IPv4 addresses + - `usocket.AF_INET6` - Returns only IPv6 addresses + - Not specified or set to 0 - Returns all address types (IPv4 + IPv6) + +**Return Value** + +- `family` - The address family (please refer to Constants). +- `type` - The socket type (please refer to Constants). +- `proto` - The protocol number (please refer to Constants). +- `canonname` - The domain name of the host. +- `sockaddr` - The list containing addresses and port numbers. + + +Example: +```python +import usocket + +# Return all address types (IPv4 + IPv6) +result1 = usocket.getaddrinfo('iservice.10010.com', 443) +# Only return IPv4 addresses +result2 = usocket.getaddrinfo('iservice.10010.com', 443, usocket.AF_INET) +# Only return IPv6 addresses +result3 = usocket.getaddrinfo('iservice.10010.com', 443, usocket.AF_INET6) +``` + +## Methods + +### `socket.bind` + +```python +socket.bind(address) +``` + +This method binds the socket to the specified address. The socket must not yet be bound. + +> **Note:** 1. When the socket is a server, it must be bound to fix the address of the server. 2. When the socket is a client, it should be bound to address to specify the socket for data processing (It should be used with usocket.TCP_CUSTOMIZE_PORT). + +**Parameter** + +- `address` - The list or tuple containing addresses and port numbers. + +Example: +``` +#Binds the specified address +socket.bind(("192.168.0.1",80)) +#Binds dial-up IP address, and the port can be customlized (When the port is 0, it will be automatically allocated) +socket.bind(("",0)) +``` + +### `socket.listen` + +```python +socket.listen(backlog) +``` + +This method allows the socket server to listen to the client connection and specify the maximum connection number of the client. + +**Parameter** + +- `backlog` - The maximum number for accepting the socket, at least 0. + +### `socket.accept` + +```python +socket.accept() +``` + +This method allows the socket server to accept the connection request. If successful, a tuple, which contains the new socket, client address and client port, will be returned. The form is : `(conn, address, port)`. + +**Return Value** + +- `conn` - The new socket object which is used to interact with the client. +- `address` - The client address connected to the server. +- `port` - The client port connected to the server. + +### `socket.connect` + +```python +socket.connect(address) +``` + +This method allows the socket to connect the server of the specified address parameter. + +**Parameter** + +- `address` - The list or tuple containing addresses and port numbers. + +Example: +``` +# Connects the specified address +socket.connect(("192.168.0.1",80)) +``` + +### `socket.read` + +```python +socket.read( [ size ] ) +``` + +This method reads size byte data from the socket and returns a byte object. If size is not specified, all readable data will be read from the socket until there is no more data to be read. At this time, this function is the same as `socket.readall()` . + +### `socket.readinto` + +```python +socket.readinto(buf, [ , nbytes ]) +``` + +This method reads bytes from the socket into the buffer buf. If nbytes is specified, the most maximum bytes can be read is the number of nbytes. If nbytes is not specified, len(buf) bytes can be read at most. The return value is the actual number of read bytes. + +```python +socket.readline() +``` + +This method reads data from a socket by line and stops reading when a newline character is encountered, and returns the read line. + +### `socket.write` + +```python +socket.write(buf) +``` + +This method allows the socket to send the data in buffer, and buf is the data to be sent. Then the actual sent bytes number is returned. + +### `socket.send` + +```python +socket.send(bytes) +``` + +This method allows the socket to send data and returns the the actual sent bytes number. + +**Parameter** + +- `bytes` - The data in bytes type. + +### `socket.sendall` + +```python +socket.sendall(bytes) +``` + +This method allows the socket to send all data to the socket. Unlike `send()`, this method attempts to send all the data block by block. +Note: The operation of this method on the non-blocking socket is indeterminate, so in MicroPython, it is recommended to use `write()`. The `write()` method has the same "No-short-writing" policy to block the socket, and will return the number of bytes sent on the non-blocking socket. + +**Parameter** + +- `bytes` - The data in bytes type. + +### `socket.sendto` + +```python +socket.sendto(bytes, address) +``` + +This method allows the socket to send data to the specified *address*, and returns the actual sent bytes number. + +**Parameter** + +- `bytes` - The data in bytes type. +- `address` - The list or tuple containing addresses and port numbers. + +### `socket.recv` + +```python +socket.recv(bufsize) +``` + +This method receives the data from the socket. The return value is a byte object which indicates the received data. The maximum data size received at a time is determined by bufsize. + +**Parameter** + +- `bufsize` - The maximum data size received at a time. + +### `socket.recvfrom` + +```python +socket.recvfrom(bufsize) +``` + +This method receives the data from the socket. The return value is a tuple which contains the byte object and address. The form of the return value is: `(bytes, address)`. + +**Parameter** + +- `bufsize` - The maximum data size received at a time. + +**Return Value** + +- `bytes` -The byte object that receives the data. +- `address` -The address of the socket that sends the data. + +### `socket.close` + +```python +socket.close() +``` + +This method marks the socket as closed and releases all resources. + +### `socket.setsockopt` + +```python +socket.setsockopt(level, optname, value) +``` + +This method sets the value of the socket option. + +**Parameter** + +- `level` - The level of the socket option. +- `optname` - The feature option of the socket. +- `value` - It can be either an integer or an object in bytes type which represents the buffer. + +Example: +``` +#Sets the port multiple is enabled +socket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1) +#Sets intervals of the TCP keep-alive packet.The unit of the value parameter is minute,ranging from 1 to 120 +socket.setsockopt(usocket.SOL_SOCKET, usocket.TCP_KEEPALIVE, 1) +``` + +### `socket.setblocking` + +```python +socket.setblocking(flag) +``` + +This method sets the socket as either blocking mode or non-blocking mode. This method is a simplification of `settimeout()`. + +**Parameter** + +- `flag` - Sets whether the socket mode is blocking (default mode: blocking mode). + +Example: +``` +#Sets the socket as the blocking mode +`socket.setblocking(True)` equals to `socket.settimeout(None)` +#sets the socket as the non-blocking mode +`socket.setblocking(False)` equals to `socket.settimeout(0)` +``` + +### `socket.settimeout` + +```python +socket.settimeout(value) +``` + +This method sets timeouts of the send and received data of the socket. Unit: second. + +**Parameter:** + +- `value` - It can be a non-negative floating point which represents second or None. If the parameter value is 0, the socket will be set to non-blocking mode, otherwise the socket will be in blocking mode. + +### `socket.makefile` + +```python +socket.makefile(mode='rb') +``` + +This method returns the file object associated with the socket. The type of the return value is related to the specified parameter. The mode parameter only supports binary pattern (rb and wb). + +### `socket.getsocketsta` + +```python +socket.getsocketsta() +``` + +This method gets the status of TCP socket. + +> **Note: **1. BG95 series module does not support this API. 2. After calling `socket.close()` , -1 will be returned if `socket.getsocketsta()` is called, because the created object resources and other things have been released. + +**Return Value** + +| Status Value | Status | Description | +| ------------ | ----------- | ------------------------------------------------------------ | +| 0 | CLOSED | The socket is created but not used. | +| 1 | LISTEN | The socket is listening to the connection. | +| 2 | SYN_SENT | The socket is trying to establish a connection actively. That is, ACK has not been received after sending the SYN. | +| 3 | SYN_RCVD | The socket is in the initial synchronization status of the connection. That is, the SYN sent from the opposite has been received, but the ACK of the sent SYN has not been received. | +| 4 | ESTABLISHED | The socket has successfully established the connection. | +| 5 | FIN_WAIT_1 | The socket is closed and the TCP connection is closing. That is, the FIN is sent actively, but the ACK or FIN sent from the party closed passively has not been received. | +| 6 | FIN_WAIT_2 | The local socket is closed and the remote socket is waiting to be closed. That is, the ACK corresponding to the sent FIN is received in the FIN_WAIT_1 status. | +| 7 | CLOSE_WAIT | The remote socket is closed and the local socket is waiting to be closed. The passively closed party receives the FIN. | +| 8 | CLOSING | The local socket is closed and the remote socket is closing. The close confirmation is suspended. That is, the FIN sent from the passively closed party has been received in FIN_WAIT_1 status. | +| 9 | LAST_ACK | The remote socket is closed , and the close confirmation of the local socket is being waited. The passively closed party sends the FIN in CLOSE_WAIT status. | +| 10 | TIME_WAIT | The remote socket is closed and the local socket is waiting to be closed. That is, the four-way wavehand FIN, ACK, FIN, and ACK are complete. The TCP connection is disconnected after 2MSL time. | + + +## Constants + +### usocket.AF_INET + +IPV4 type. Address family. + +### usocket.AF_INET6 + +IPV6 type. Address family. + +### usocket.SOCK_STREAM + +socket type. A TCP-based stream socket. + +### usocket.SOCK_DGRAM + +socket type. A UDP-based datagram socket + +### usocket.SOCK_RAW + +socket type. A raw socket + +### usocket.IPPROTO_TCP + +Protocol number. TCP protocol. + +### usocket.IPPROTO_UDP + +Protocol number. UDP protocol. + +### usocket.IPPROTO_TCP_SER + +Protocol number. TCP server. + +### usocket.TCP_CUSTOMIZE_PORT + +Protocol number. TCP client can customize address. + +### usocket.SOL_SOCKET + +The level of the socket option. + +### usocket.SO_REUSEADDR + +The socket feature option. The port multiple is enabled. + +### usocket.TCP_KEEPALIVE + +The socket feature option. Sets intervals of the TCP keep-alive packet. diff --git a/docs/API_reference/en/stdlib/ustruct.md b/docs/API_reference/en/stdlib/ustruct.md new file mode 100644 index 0000000000000000000000000000000000000000..48cd3eae5c45772a923eac51ce812edf56553618 --- /dev/null +++ b/docs/API_reference/en/stdlib/ustruct.md @@ -0,0 +1,198 @@ + +# ustruct - Pack and Unpack Primitive Data Types + +Module feature: `ustruct` module realizes subsets of the corresponding CPython module. See CPython file [struct](https://docs.python.org/3.5/library/struct.html#module-struct) for detailed information. + + +## Format String + +The format string is the mechanism used to specify the expected layout when packing and unpacking data. Format strings are built through the format character of the specified data type that to be packed or unpacked. In addition, there are special characters that control byte order, size, and alignment. + + +### Byte Order, Size, and Alignment + +By default, C types are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). According to the following table, the first character of the format string can be used to indicate the byte order, size, and alignment of the packed data: + +| Character | Byte **Order ** | Size | Alignment | +| --------- | ---------------------- | -------- | --------- | +| `@` | native | native | native | +| `=` | native | standard | none | +| `<` | little-endian | standard | none | +| `>` | big-endian | standard | none | +| `!` | network (= big-endian) | standard | none | + +> If the first character is not one of the format string, it is assumed to be '@' . + + +### **List of Format Character** + +| Format | C Type | Python Type | Standard Size | +| ------ | -------------------- | ----------- | ------------- | +| `b` | `signed char` | integer | 1 | +| `B` | `unsigned char` | integer | 1 | +| `h` | `short` | integer | 2 | +| `H` | `unsigned short` | integer | 2 | +| `i` | `int` | integer | 4 | +| `I` | `unsigned int` | integer | 4 | +| `l` | `long` | integer | 4 | +| `L` | `unsigned long` | integer | 4 | +| `q` | `long long` | integer | 8 | +| `Q` | `unsigned long long` | integer | 8 | +| `f` | `float` | float | 4 | +| `d` | `double` | float | 8 | +| `P` | `void *` | integer | 4 | + + +## `ustruct` Methods + +### `ustruct.calcsize` + +```python +ustruct.calcsize(fmt) +``` + +Returns the number of bytes for storing `fmt`. + +**Parameter** + +- `fmt` - Format character type. See the list of format character above for details. + +**Example:** + +```python +>>> import ustruct +>>> ustruct.calcsize('i') +4 +>>> ustruct.calcsize('f') +4 +>>> ustruct.calcsize('d') +8 +``` + + + +### `ustruct.pack` + +```python +ustruct.pack(fmt, v1, v2, ...) +``` + +Compresses parameters v1, v2, ... according to the format string `fmt`. + +**Parameter** + +- `fmt` - Format character type. See the list of format character above for details. +- `v1`, `v2`, `...` - The variable name or value which requires data conversion. + +**Return Value** + +- Returns the byte object of the encoded parameter. + +**Example** + +```python +>>> import ustruct + +>>> ustruct.pack('ii', 7, 9) # Packs two integers +b'\x07\x00\x00\x00\t\x00\x00\x00' + +``` + +### `ustruct.unpack` + +```python +ustruct.unpack(fmt, data) +``` + +Decompresses the data according to the format string `fmt` . The return value is a tuple. + +**Parameter** + +- `fmt` - Format character type. See the list of format character above for details. +- `data` - Data needs to be decompressed. + +**Return Value** + +- Returns the tuple containing the decompression value (even if it contains only one value). + +**Example** + +```python +>>> import ustruct + +>>> ustruct.unpack('ii', b'\x07\x00\x00\x00\t\x00\x00\x00') # Decompresses two previous packed integers +(7, 9) + +``` + + + +### `ustruct.pack_into` + +```python +ustruct.pack_into(fmt, buffer, offset, v1, v2, ...) +``` + +Packs values v1, v2, … into a buffer starting with `offset` according to the format string `fmt`. If you counts from the end of the buffer, the value of `offset` may be negative. + +**Parameter** + +- `fmt` - Format character type. See the list of format character above for details. +- `buffer` - Buffer for writing data. +- `offset` - Starting position for writing data. +- `v1`, `v2`, `...` - Data needs to be written in the buffer. + +**Example** + +```python +>>> import ustruct + +# Defines the format string +>>> fmt = "3sB" +# Defines a character string and an integer +>>> name = "Tom" +>>> age = 25 + +# Packs two values in the specified format and writes them to an empty buffer in bytes type +>>> buf = bytearray(8) # Create a buffer of 8 bytes +>>> ustruct.pack_into(fmt, buf, 0, name.encode(), age) # Encodes "name" as bytes type and writes in three characters (three bytes), followed by a integer "age" (one byte) + +>>> print(buf) # Output: bytearray(b'Tom\x19\x00\x00\x00') +bytearray(b'Tom\x19\x00\x00\x00\x00') +``` + + +### `ustruct.unpack_from` + +```python +ustruct.unpack_from(fmt, data, offset=0) +``` + +Parses the decompressed data starting from `offest` according to the format string `fmt`. If you counts from the end of the buffer, the value of offset may be negative. + +**Parameter** + +- `fmt` - Format character type. See the list of format character above for details. +- `data` - Data buffer. (The unit of the buffer size is byte.) +- `offset` - (Optional) Starting position of decompression. 0 is by default. + +**Return Value** + +- Returns the tuple containing the decompression value (even if it contains only one value). + +**Example** + +```python +>>> import ustruct + +# Defines the format string +>>> fmt = "3sB" +# Defines the byte sequence which needs to unpack +>>> data = bytearray(b'Tom\x19\x00\x00\x00\x00') + +# Unpacks from the first byte of the byte sequence +>>> result = ustruct.unpack_from(fmt, data, 0) +>>> print(result) # Output: (b'Tom', 25) +(b'Tom', 25) + +``` \ No newline at end of file diff --git a/docs/API_reference/en/stdlib/utime.md b/docs/API_reference/en/stdlib/utime.md new file mode 100644 index 0000000000000000000000000000000000000000..945d084a8107903769e8dfc5c2b3cb0e93106164 --- /dev/null +++ b/docs/API_reference/en/stdlib/utime.md @@ -0,0 +1,259 @@ +# utime - Time Related Features + +`utime ` module gets the current time, measures the time interval and provides the feature of sleep, and realizes subsets of the corresponding CPython module. See CPython file [time](https://docs.python.org/3.5/library/time.html#module-time) for more detailed information. + +**Example** + +```python +''' +@Author: Baron +@Date: 2020-06-17 +@LastEditTime: 2020-06-17 17:06:08 +@Description: example for module utime +@FilePath: example_utime_loacltime_file.py +''' +import utime +import log + + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on your actual project +''' +PROJECT_NAME = "QuecPython_localtime_example" +PROJECT_VERSION = "1.0.0" + + +# Set the log output level +log.basicConfig(level=log.INFO) +time_log = log.getLogger("LocalTime") + +if __name__ == '__main__': + # Gets the local time and returns the tuple + tupe_t = utime.localtime() + time_log.info(tupe_t) + # Returns the current timestamp. The parameter is tuple + t = utime.mktime(utime.localtime()) + time_log.info(t) + # Sleep example + for i in [0, 1, 2, 3, 4, 5]: + utime.sleep(1) # Sleep(unit: m) + time_log.info(i) + + for i in [0, 1, 2, 3, 4, 5]: + utime.sleep_ms(1000) # Sleep(unit: ms) + time_log.info(i) +``` + + + +## The Current Time + +### `utime.localtime` + +```python +utime.localtime(secs) +``` + +Converts a time in seconds to a time in date format and returns it, or returns the local RTC time when `secs` is provided. + +**Parameter** + +- `secs` - Integer type. The time in seconds. + +**Return Value** + +- `(year, month, mday, hour, minute, second, weekday, yearday)` - Tuple type. Contains year, month, day, hour, minute, second, week, the day of the year. Returns the converted time when `secs` is provided. Returns the local RTC time when `secs` is not provided. The meaning of return values is below: + +| Tuple Members | Range | Meaning | +| ------------- | ------------------ | -------------------------- | +| year | Integer type | Year | +| month | Integer type, 1–12 | Month | +| mday | Integer type, 1–31 | Day, the date of the month | +| hour | Integer type, 0–23 | Hour | +| minute | Integer type, 0–59 | Minute | +| second | Integer type, 0–59 | Second | +| weekday | Integer type, 0–6 | Week | +| yearday | Integer type | The day of the year | + +**Example** + +```python +>>> import utime +>>> utime.localtime() +(2020, 9, 29, 8, 54, 42, 1, 273) +>>> utime.localtime(646898736) +(2020, 7, 1, 6, 5, 36, 2, 183) +``` + +### `utime.mktime` + +```python +utime.mktime(date) +``` + +Converts a time in date format stored in the tuple to a time in seconds and returns it. + +**Parameter** + +- `date `- Tuple type. The time in date format. Format: (year, month, mday, hour, minute, second, weekday, yearday). + +**Return Value** + +- Integer type. The time in seconds. + +**Example** + +```python +>>> import utime +>>> date = (2020, 9, 29, 8, 54, 42, 1, 273) +>>> utime.mktime(date) +1601340882 +``` + +### `utime.time` + +```python +utime.time() +``` + +Returns seconds since the device was enabled. + +**Return Value** + +- Integer type. The time in seconds. + +### `utime.getTimeZone` + +```python +utime.getTimeZone() +``` + +Gets the current time zone. + +**Return Value** + +- Unit: hour. Range: [-12, 12]. Negative values indicate the western time zone, positive values indicate the eastern time zone, and 0 indicates the zero time zone. + +### `utime.setTimeZone` + +```python +utime.setTimeZone(offset) +``` + +Sets the time zone. After the time zone is set, the local time will change to the time in the corresponding time zone. + +**Parameter** + +- Unite: hour. Range: [-12, 12]. Negative values indicate the western time zone, positive values indicate the eastern time zone, and 0 indicates the zero time zone. + +## Measuring the Time Interval + +### `utime.ticks_ms` + +```python +utime.ticks_ms() +``` + +Returns an ascending millisecond counter. It will recount when the value exceeds 0x3FFFFFFF. + +**Return Value** + +- Millisecond count value. The count value itself has no specific meaning and is only suitable for `ticks_diff()`. + +### `utime.ticks_us` + +```python +utime.ticks_us() +``` + +Returns an ascending microsecond counter. It will recount when the value exceeds 0x3FFFFFFF. + +**Return Value** + +- Microsecond count value. The count value itself has no specific meaning and is only suitable for `ticks_diff()`. + +### `utime.ticks_cpu` + +```python +utime.ticks_cpu() +``` + +Returns an ascending CPU counter. The unit depends on the underlying clock of the hardware platform. + +**Return Value** + +- Count value. The count value itself has no specific meaning and is only suitable for `ticks_diff()`. + +### `utime.ticks_diff` + +```python +utime.ticks_diff(ticks1, ticks2) +``` + +Calculates the time interval between calling ` ticks_ms` , `ticks_us`, or `ticks_cpu` for the first time and the second time. Because the count value of `ticks_xxx` may be looped, it cannot be directly subtracted so `ticks_diff` should be called. Generally,`ticks_diff` should be called in the event loop with a timeout. + +**Parameter** + +- `ticks1`- Tick value obtained by calling ` ticks_ms`, `ticks_us`, or `ticks_cpu` for the second time. +- `ticks2`- Tick value obtained by calling ` ticks_ms`, `ticks_us`, or `ticks_cpu` for the first time. + +**Return Value** + +- Time interval. The time interval between calling ` ticks_ms`, `ticks_us`, or `ticks_cpu` for the first time and the second time. The unit is the same as that of the passed `ticks2` and `ticks1`. + +**Note** + +The order of `ticks2` and `ticks1` cannot be reversed, otherwise the result cannot be determined. This function should not be used to calculate long intervals, that is, the tick difference between `ticks2` and `ticks1` cannot cannot exceeds 0x1FFFFFFF, otherwise the result cannot be determined. + +**Example** + +```python +import utime +start = utime.ticks_us() +while pin.value() == 0: + if utime.ticks_diff(utime.ticks_us(), start) > 500: + raise TimeoutError +``` + +## Sleep + +### `utime.sleep` + +```python +utime.sleep(seconds) +``` + +The given seconds of sleep. + +**Parameter** + +- `seconds`- The duration of sleep. Unit: second. + +### `utime.sleep_ms` + +```python +utime.sleep_ms(ms) +``` + +The given millisecond of sleep. + +**Parameter** + +`ms` - The duration of sleep. Unit: millisecond. + +### `utime.sleep_us` + +```python +utime.sleep_us(us) +``` + +The given microsecond of sleep. + +**Parameter** + +`us`- The duration of sleep. Unit: microsecond. + +**Note** + +Calling `utime.sleep`, `utime.sleep_ms` and `utime.sleep_us` will cause the program to block. + diff --git a/docs/API_reference/en/stdlib/uzlib.md b/docs/API_reference/en/stdlib/uzlib.md new file mode 100644 index 0000000000000000000000000000000000000000..b8f9c4969e2902e65c8daae9b49ecd56cc834ff5 --- /dev/null +++ b/docs/API_reference/en/stdlib/uzlib.md @@ -0,0 +1,31 @@ +# uzlib - zlib Decompression + +``` +This article introduces the use of QuecPython's uzlib module and describes features of the latest version of the uzlib module. +``` + +The module uses the binary data compressed by [DEFLATE Algorithm](https://en.wikipedia.org/wiki/DEFLATE) to decompress (generally used in the zlib library and the gzip archiver). This module realizes subsets of the corresponding CPython module. See CPython file [zlib](https://docs.python.org/3.5/library/zlib.html#module-zlib) for more detailed information. + + +> Note: 1. Compression has not been realized. 2. Before decompressing, the available space in the module should be checked to ensure that there is enough space to decompress. + + +## Constructor + +### `uzlib.decompress` + +```python +uzlib.decompress(data, wbits=0, bufsize=0) +``` + +Returns the compressed bytes object. `wbits` is the window size of DEFLATE dictionary when decompressing. (8–15, the dictionary size is the power of 2 of `wbits` value). If this value is positive, `data` is assumed to be the zlib stream (with the zlib header). If the value is negative, `data` is assumed to be the original DEFLATE stream. `bufsize` is for compatibility with CPython and will be ignored. + + +### `uzlib.DecompIO` + +```python +class uzlib.DecompIO(stream, wbits=0) +``` + +Creates a `stream` decorator that allows data to be transparently compressed in another stream. This indicates the data can be greater than the compressive stream of available heap size. In addition to the values described above, wbits can have values 24.. 31 (16 + 8.. 15), which indicates that the input stream has the gzip header. + diff --git a/docs/API_reference/en/syslib/Queue.md b/docs/API_reference/en/syslib/Queue.md new file mode 100644 index 0000000000000000000000000000000000000000..cd9a3c4d6a936d9494b04186b93a7fc6d9a0bacd --- /dev/null +++ b/docs/API_reference/en/syslib/Queue.md @@ -0,0 +1,123 @@ +# Queue - Message Queue + +This feature is used for inter-thread communication. + + +## Constructor + +### `queue.Queue` + +```python +class queue.Queue(maxsize=100) +``` + +**Parameter** + +`maxsize` - Integer type. The maximum queue length. Default value: 100. + +**Example** + +```python +>>> from queue import Queue +>>> q = Queue(100) +``` + + + +## Put Data into Queue + +### `Queue.put` + +Puts data into the queue. + +```python +Queue.put(data=None) +``` + +**Parameter** + +* `data` - Data or signal put into the queue. Optional parameter. If this parameter is omitted, *data=None* will be configured by default. + +**Return Value** + +True - Successful execution + +False - Failed execution + + + +## Get Data + +### `Queue.get` + +Gets data from the queue by blocking the queue. + +```python +Queue.get() +``` + +**Return Value** + +Data in the queue. + +None - The data in the queue is empty. + + + +## Query Whether Queue Is Empty + +### `Queue.empty` + +```python +Queue.empty() +``` + +**Return Value** + +True - Empty + +False - Not empty + + + +## Query Data Length in Queue + +### `Queue.size` + +```python +Queue.size() +``` + +**Return Value** + +Integer type. The current data length. + +**Example** + +```python +import _thread +from queue import Queue + +# Initialize the queue. The default length is 100. +q = Queue() + + +def get(): + while True: + # Get data by blocking the queue + data = q.get() + print("data = {}".format(data)) + +# Unblock the queue with a thread +_thread.start_new_thread(get, ()) + +# Put data into the queue +text = "hello world" +q.put(text) + +# Get the data length in the queue +q.size() + +# Determine whether the queue is empty +q.empty() +``` \ No newline at end of file diff --git a/docs/API_reference/en/syslib/README.md b/docs/API_reference/en/syslib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e3d03867e97d08bb60ed66aed145bc7f84221dd2 --- /dev/null +++ b/docs/API_reference/en/syslib/README.md @@ -0,0 +1,21 @@ +# QuecPython system features + +> QuecPython System Function Library includes QuecPython module system function related components + +This article describes the modules in the QuecPython system function library. + +## QuecPython system feature library list + +- [modem - Device related](./modem.md) +- [example - Executing Python script](./example.md) +- [log-log output](./log.md) +- [atcmd - Send AT command](./atcmd.md) +- [system - Environment configuration](./system.md) +- [queue-message Queue](./Queue.md) +- [sys_bus - session bus](./sys_bus.md) +- [osTimer-os timer](./osTimer.md) +- [fota - Firmware upgrade](./fota.md) +- [app_fota - User file upgrade](./app_fota.md) +- [ql_fs - Advanced file operations](./ql_fs.md) +- [securedata - Security data area](./securedata.md) +- [pm - Low power related functions](./pm.md) diff --git a/docs/API_reference/en/syslib/app_fota.md b/docs/API_reference/en/syslib/app_fota.md new file mode 100644 index 0000000000000000000000000000000000000000..f2cebc3475f3ceaaa49687dffa78ae1419b97f17 --- /dev/null +++ b/docs/API_reference/en/syslib/app_fota.md @@ -0,0 +1,93 @@ +# app_fota - User File Upgrade + +The `app_fota` module is used for user file upgrades. + +**Example**: + +```python +import app_fota +from misc import Power + +fota = app_fota.new() +download_list = [{'url': 'http://www.example.com/app.py', 'file_name': '/usr/app.py'}, {'url': 'http://www.example.com/test.txt', 'file_name': '/usr/text.txt'}] +fota.bulk_download(download_list) # Download +fota.set_update_flag() # Set update flag +Power.powerRestart() # Restart +``` + +## Initialization + +### `app_fota.new` + +```python +app_fota.new() +``` + +Creates an app_fota object. + +**Return Value:** + +- app_fota object. + +**Example**: + +```python +import app_fota +fota = app_fota.new() +``` + +## Download + +### `fota.download` + +```python +fota.download(url, file_name) +``` + +Downloads a single file. + +**Parameter:** + +- `url`-String type. The URL of the file to be downloaded. +- `file_name`-String type. The absolute path of the local file to be upgraded. + +**Return Value**: + +- `0`-Successful execution; `-1`-Failed execution. + +### `fota.bulk_download` + +```python +fota.bulk_download(info=[]) +``` + +Downloads bulk files. + +**Parameter:** + +- `info`-List type. The bulk download lists. Each elements of the list is a dictionary containing `url` and `file_name`. + +**Return Value**: + +- Returns the list of failed downloads in list type when the download fails. +- Returns NULL when the download succeeds. + +**Example**: + +```python +download_list = [{'url': 'http://www.example.com/app.py', 'file_name': '/usr/app.py'}, {'url': 'http://www.example.com/test.txt', 'file_name': '/usr/text.txt'}] +fota.bulk_download(download_list) +``` + +In the example above, assuming that it fails to download `http://www.example.com/test.txt`, the return value is `[{url: 'http://www.example.com/test.txt', file_name: '/usr/text.txt'}]`. + +## Set Upgrade Flag + +### `fota.set_update_flag` + +```python +fota.set_update_flag() +``` + +Sets the upgrade flag. After the upgrade flag is set, call the restart interface to restart the module. After that, the upgrade process can be started. You can enter the application once the upgrade completes. + diff --git a/docs/API_reference/en/syslib/atcmd.md b/docs/API_reference/en/syslib/atcmd.md new file mode 100644 index 0000000000000000000000000000000000000000..6be9625b09f84f7c540762b4b5899fccdcf728fe --- /dev/null +++ b/docs/API_reference/en/syslib/atcmd.md @@ -0,0 +1,52 @@ +# atcmd - Send AT Commands + +This module provides a method for sending AT commands, allowing the QuecPython module to send AT commands through Python code. + + + +## Send AT Commands + +### `atcmd.sendSync` + +``` +atcmd.sendSync(atcmd,resp,include_str,timeout) +``` + + Sends an AT command to the module. + +**Parameter** + +* `atcmd` - String type. The AT command to be sent, and '\r\n' should be included. +* `resp` - String type. The string content returned by the AT command. +* `include_str` - String type. Keyword. The specific values are shown in the table below: + +| Value | Description | +| ------------------- | ------------------------------------------------------------ | +| `Empty string` | Gets all data returned by the AT command (excluding result data such as 'OK') and puts the data into the `resp` parameter. | +| `None-empty string` | Filter data containing the keyword and puts the data into the `resp` parameter. | + +* `timeout` - Integer type. Timeout. Unit: second. + +**Return Value** + +Returns an integer value. `0` indicates successful execution and other values indicate failed execution. + +**Example:** + +```python +>>> import atcmd +>>> resp=bytearray(50) +>>> atcmd.sendSync('at+cpin?\r\n',resp,'',20) +0 +>>> print(resp) +bytearray(b'\r\n+CPIN: READY\r\n\n\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') + +atcmd.sendSync('at+cpin\r\n',resp,'',20) +1 +>>> print(resp) +bytearray(b'\r\nERROR\r\n\n +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +``` + +More example of AT command for EC200U&EG915U Series can be view by download [this](https://forums.quectel.com/uploads/short-url/dV5cK9eteeQmwyGPgfWB351oZde.pdf) \ No newline at end of file diff --git a/docs/API_reference/en/syslib/example.md b/docs/API_reference/en/syslib/example.md new file mode 100644 index 0000000000000000000000000000000000000000..e9d821ca230160e13884c100d4432b9c9b450281 --- /dev/null +++ b/docs/API_reference/en/syslib/example.md @@ -0,0 +1,47 @@ +# example - Execute Python Scripts + +This document introduces how to execute Python scripts on the command line or in the code. + +### `example.exec` + +```python +example.exec(filePath) +``` + +Executes the specified Python script file. + +**Parameter** + +* `filePath` - String type. Absolute path for Python script file execution. + +**Example** + +```python +# Assuming there is a test.py file + +def myprint(): + count = 10 + while count > 0: + count -= 1 + print('##### test #####') + +myprint() + +#Uploads test.py to the module, enters the command line and executes the following codes +>>> uos.listdir('/usr/') +['apn_cfg.json', 'test.py'] +>>> import example +>>> example.exec('/usr/test.py') +# Execution results are as follows + +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +``` diff --git a/docs/API_reference/en/syslib/fota.md b/docs/API_reference/en/syslib/fota.md new file mode 100644 index 0000000000000000000000000000000000000000..0a78f322a87b9974d423925ab6ab09ff4b8d88b7 --- /dev/null +++ b/docs/API_reference/en/syslib/fota.md @@ -0,0 +1,315 @@ +# fota - Firmware Upgrade + +`fota` provides the feature of firmware upgrade. + +**Examples:** + +```python +# OTA Upgrade. The module will restart automatically after the upgrade package is downloaded. + +import fota +import utime +import log +import checkNet + +# Sets the log output level +log.basicConfig(level=log.INFO) +fota_log = log.getLogger("Fota") + +PROJECT_NAME = "QuecPython_fota_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +def result(args): + print('download status:',args[0],'download process:',args[1]) + +def run(): + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + fota_obj = fota() # Creates a FOTA object + fota_log.info("httpDownload...") + # Methods of DFOTA upgrades + res = fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) + # Methods of mini FOTA + #res = fota_obj.httpDownload(url1="http://www.example.com/fota1.bin",url2="http://www.example.com/fota2.bin") + if res != 0: + fota_log.error("httpDownload error") + return + fota_log.info("wait httpDownload update...") + utime.sleep(2) + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +if __name__ == '__main__': + fota_log.info("run start...") + run() +``` + +```python +# OTA Upgrade. The module won't restart automatically after the upgrade package is downloaded. + +import fota +from misc import Power + +fota_obj = fota(reset_disable=1) + +def result(args): + print('download status:',args[0],'download process:',args[1]) + +fota_obj.httpDownload(url1="http://www.example.com/dfota.bin",callback=result) # Expects that the module won't restart after the upgrade package is downloaded. +Power.powerRestart() # Restarts the module manually for the upgrade +``` + +```python +# Local upgrade + +import fota +import utime +import log +from misc import Power +import uos + +''' +The following two global variables are necessary. You can modify the values of these two global variables based on your project requirements. +''' +PROJECT_NAME = "QuecPython_Fota_example" +PROJECT_VERSION = "1.0.0" + +# Sets the log output level +log.basicConfig(level=log.INFO) +fota_log = log.getLogger("Fota") + +# For this example, the file of upgrade package is required like FOTA packages of .bin files and it shall be stored in the file system. + +def run(): + fota_obj = fota() # Creates a FOTA object + file_size = uos.stat("/usr/FotaFile.bin")[6] # Gets the total number of bytes of the file + print(file_size) + with open("/usr/FotaFile.bin", "rb")as f: # Opens .bin files (The upgrade package needs to be made.) in the rb mode + while 1: + c = f.read(1024) # read + if not c: + break + fota_obj.write(c, file_size) # Writes data of .bin files and total bytes of the file + + fota_log.info("fota image flush...") + res = fota_obj.flush() # Refresh + if res != 0: + fota_log.error("flush error") + return + fota_log.info("fota image verify...") + res = fota_obj.verify() # Verify + if res != 0: + fota_log.error("verify error") + return + fota_log.info("power_reset...") + utime.sleep(2) + Power.powerRestart() # Restarts the module + + +if __name__ == '__main__': + fota_log.info("run start...") + run() +``` + + + +## Initialization + +### FOTA + +```python +fota(reset_disable=) +``` + +Creates a FOTA object. + +**Parameter:** + +- `reset_disable` - Optional parameter. Whether to disable the feature that the module restarts automatically after the upgrade package is downloaded. 1–Disable; Omitted/0–Enable + +**Return Value:** + +- A FOTA object. + +**Note:** + +EC600N/EC800N/EG912N/EC600M/EC800M/EG810M series module does not support to disable the feature that the module restarts automatically after the upgrade package is downloaded. + +**Example:** + +```python +import fota +fota_obj = fota() # The module will restart automatically after the upgrade package is downloaded. +# fota_obj = fota(reset_disable=1) # The module won't restart automatically after the upgrade package is downloaded. +``` + +## OTA Upgrade + +This interface can realize the whole process of upgrade package download and firmware upgrade. + +### fota_obj.httpDownload + +```python +fota_obj.httpDownload(url1=, url2=, callback=) +``` + +Download, write and verify the upgrade package and restart the module to complete the upgrade. + +**Parameter:** + +- `url1` - String type. Optional parameter. URL of the upgrade package. This URL can be in HTTP or FTP format. Note: Only EC200A series module supports the URL in FTP format. +- `url2` - String type. Optional parameter. URL of the upgrade package of the second stage in mini FOTA upgrades. Note: This parameter needs to be passed only in mini FOTA upgrades and it is prohibited to be passed in DFOTA upgrades. Mini FOTA upgrade is a special firmware upgrade method for small storage modules and it is divided into two stages. DFOTA upgrades only have one stage. Only EC600N/EC800N/EG912N/EC600M/EC800M/EG810M series module supports mini FOTA upgrades. +- `callback` - Function type. Optional parameter. This callback function displays the download progress and status. Note: In mini FOTA upgrades, the callback function is not supported. Parameter descriptions of callback function are as follows. + +| Parameter | Type | Description | +| --------- | ---- | ------------------------------------------------------------ | +| args[0] | int | Download status. 0/1/2 – Successful download; Other values – Failed download. | +| args[1] | int | Download progress. (Note: For EC600N/EC800N/EG912N series module, it indicates percentage when the download status is successful and indicates error codes when the download status is failed. ) | + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + + Note: For EC600N/EC800N/EG912N/EC600M/EC800M/EG810M/BC25 series module, return values only indicate successful or failed execution of this interface. The upgrade status and results are returned in callback. For other series modules, 0 indicates successful download and verification. -1 indicates failed download and verification. + +**Example:** + +```python +def result(args): + print('download status:',args[0],'download process:',args[1]) + +# DFOTA upgrades over HTTP +fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) +# DFOTA upgrades over FTP +fota_obj.httpDownload(url1="ftp://user:password@ip:port/fota.bin",callback=result) # You need to enter the FTP server information you actually use for "user", "password", "ip" and "port". +#m Mini FOTA +fota_obj.httpDownload(url1="http://www.example.com/fota1.bin",url2="http://www.example.com/fota2.bin") +``` + +### fota_obj.apn_set + +```python +fota_obj.apn_set(fota_apn=,ip_type=,fota_user=,fota_password=) +``` + +Sets APN information used in FOTA download. + +**Parameter:** + +- `fota_apn` - String type. Optional parameter. APN. +- `ip_type` - Integer type. Optional parameter. IP type: 0-IPv4; 1-IPv6. +- `fota_user` - String type. Optional parameter. Username. +- `fota_password` - String type. Optional parameter. Password. + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + +**Example:** + +```python +fota_obj.apn_set(fota_apn="CMNET",ip_type=0,fota_user="abc",fota_password="123") +``` + +**Note:** + +Only BG95 series module supports this interface. + +### fota_obj.download_cancel + +```python +fota_obj.download_cancel() +``` + +Cancels the FOTA upgrade package download in progress. + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + +**Example:** + +```python +import fota +import _thread +import utime + +def th_func(): + utime.sleep(40) # The time depends on the size of the upgrade package. Make sure to cancel the FOTA upgrade package download before the download is complete. + fota_obj.download_cancel() + +def result(args): + print('download status:',args[0],'download process:',args[1]) + +fota_obj = fota() +_thread.start_new_thread(th_func, ()) +fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) +``` + +**Note:** + +Only BG95 series module supports this interface. + +## Local Upgrade + +You can call the following interfaces to write upgrade package data to flash, verify upgrade package content and restart the module to complete the upgrade. + +### fota_obj.write + +```python +fota_obj.write(bytesData, file_size) +``` + +Writes data stream of the upgrade package. + +**Parameter:** + +- `bytesData` - Bytes type. The content data of the upgrade package. +- `file_size` - Integer type. Total size of upgrade package files. Unit: byte. + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + +### fota_obj.flush + +```python +fota_obj.flush() +``` + +Refreshes data in the RAM to flash. Because the size of the upgrade package files is not necessarily an integer multiple of the RAM size in the code, `fota_obj.flush` needs to be called to write data in the RAM to flash after the last call of `fota_obj.write`. + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + +### fota_obj.verify + +```python +fota_obj.verify() +``` + +Verifies the upgrade package. + +**Return Value:** + +- `0` - Successful execution + + `-1` - Failed execution + +**Note:** + +EC600NCNLC/EC600NCNLF/EG912N/EC600U/EC200U/EG915U/EG912U/EC800G/EC600E/EC800E series module supports the features related to local upgrade. + diff --git a/docs/API_reference/en/syslib/log.md b/docs/API_reference/en/syslib/log.md new file mode 100644 index 0000000000000000000000000000000000000000..fe0e2344c11798c6df6788c92ff1417fa5313f00 --- /dev/null +++ b/docs/API_reference/en/syslib/log.md @@ -0,0 +1,188 @@ +# log - Output Log + +A log is a tool used to record the runtime state of an application in program development, as well as help developers diagnose and troubleshoot problems. Developers can quickly identify the root causes of problems and better understand the behaviors and performance of applications by viewing logs. `log` feature can output different log levels, including the DEBUG level, WARNING level, and ERROR level. + + + +## Log Level + +### `log.DEBUG` + +Constant of log level. The most detailed information is recorded at the DEBUG level and this level is usually used in development and debugging. + +### `log.INFO` + +Constant of log level. The information recorded at the INFO level indicates that everything is running normally. + +### `log.WARNING` + +Constant of log level. The information recorded at the WARNING level indicates that something unexpected has occurred or potentially harmful events, but the application can continue to function normally. + +### `log.ERROR` + +Constant of log level. The information recorded at the ERROR level indicates that an application is no longer able to execute certain functions due to some serious problems. + +### `log.CRITICAL` + +Constant of log level. The information recorded at the CRITICAL level indicates a critical error in the application that may stop the application from running. + +## Set Log + +### `log.basicConfig` + +Sets the log output level. Default level: log.INFO. The system will only output logs whose levels are greater than or equal to that level. + +```python +log.basicConfig(level) +``` + +**Parameter** + +* `level` - Log level. + +**Return Value** + +None + +**Example** + +```python +import log +log.basicConfig(level=log.INFO) +``` + +### `log.set_output` + +Destination where the logs are output. Currently only uart and usys.stdout are supported. + +```python +log.set_output(out) +``` + +**Parameter** + +* `out` - The destination where the logs are output. Set the parameter to a specified serial port or the interaction port. Default value: the interaction port. + +**Return Value** + +None + +**Example** + +```python +import log +log.basicConfig(level=log.INFO) +Testlog = log.getLogger("TestLog") + +# Output the log through the debug UART +from machine import UART +uart = UART(UART.UART0, 115200, 8, 0, 1, 0) + +log.set_output(uart) + +Testlog.info("this is a Test log") # The logs will be output through the specified UART. + +# Output the log through the interaction port +import usys +log.set_output(usys.stdout) + +Testlog.info("this is a Test log") # The logs will be output through the interaction port. +``` + +## Output Log + +### `log.getLogger` + +Gets the log object which supports logs of different levels. + +```python +Testlog = log.getLogger(name) +``` + +**Parameter** + +* `name` - String type. The topic of the current log object + +**Return Value** + +* A log handle (log object) with the method of outputting logs. + +### `log.debug` + +Outputs the DEBUG-level logs. + +```python +Testlog.debug(msg) +``` + +**Parameter** + +* `msg` - String type. The content of logs. + +### `log.info` + +Outputs the INFO-level logs. + +```python +Testlog.info(msg) +``` + +**Parameter** + +* `msg` - String type. The content of logs. + +### `log.warning` + +Outputs the WARNING-level logs. + +```python +Testlog.warning(msg) +``` + +**Parameter** + +* `msg` - String type. The content of logs. + +### `log.error` + +Outputs the ERROR-level logs. + +```python +Testlog.error(msg) +``` + +**Parameter** + +* `msg` - String type. The content of logs. + +### `log.critical` + +Outputs the CRITICAL-level logs. + +```python +Testlog.critical(msg) +``` + +**Parameter** + +* `msg` - String type. The content of logs. + +**Example** + +```python +import log + +# Set the log output level. +log.basicConfig(level=log.INFO) +# Get the logger object. If "name" is not specified, the default value "root" will be configured. If the "name" is set to the same value multiple times, the same logger object will be returned. +Testlog = log.getLogger("Quec") + +Testlog.error("Test error message!!") +Testlog.debug("Test debug message!!") +Testlog.critical("Test critical message!!") +Testlog.info("Test info message!!") +Testlog.warning("Test warning message!!") +``` + + + diff --git a/docs/API_reference/en/syslib/modem.md b/docs/API_reference/en/syslib/modem.md new file mode 100644 index 0000000000000000000000000000000000000000..11f8694496ec206302f396691dd04241d17a10bd --- /dev/null +++ b/docs/API_reference/en/syslib/modem.md @@ -0,0 +1,110 @@ +# modem - Device + +The modem module provides the method of reading device information. + +## Get Device IMEI + +### `modem.getDevImei` + +```python +modem.getDevImei() +``` + +Gets the device IMEI. + +**Return Value** + +If successful, it returns the device IMEI in string type. If failed, it returns the integer value `-1`. + +**Example** + +```python +>>> import modem +>>> modem.getDevImei() +'866327040830317' +``` + +## Get Device Model + +### `modem.getDevModel` + +```python +modem.getDevModel() +``` + +Gets the device model. + +**Return Value** + +If successful, it returns the device model in string type. If failed, it returns the integer value `-1`. + +**Example** + +```python +>>> modem.getDevModel() +'EC100Y' +``` + +## Get Device Serial number + +### `modem.getDevSN` + +```python +modem.getDevSN() +``` + +Gets the device serial number. + +**Return Value** + +If successful, it returns the device serial number in string type. If failed, it returns the integer value `-1`. + +**Example** + +```python +>>> modem.getDevSN() +'D1Q20GM050038341P' +``` + +## Get Firmware Version + +### `modem.getDevFwVersion` + +```python +modem.getDevFwVersion() +``` + +Gets the device firmware version. + +**Return Value** + +If successful, it returns the device firmware version in string type. If failed, it returns the integer value `-1`. + +**Example** + +```python +>>> modem.getDevFwVersion() +'EC100YCNAAR01A01M16_OCPU_PY' +``` + +## Get Device Manufacture ID + +### `modem.getDevProductId` + +```python +modem.getDevProductId() +``` + +Gets the device manufacture ID. + +**Return Value** + +If successful, it returns the device manufacture ID in string type. If failed, it returns the integer value `-1`. + +**Example** + +```python +>>> modem.getDevProductId() +'Quectel' +``` + diff --git a/docs/API_reference/en/syslib/osTimer.md b/docs/API_reference/en/syslib/osTimer.md new file mode 100644 index 0000000000000000000000000000000000000000..1822f7cfaed22a1a53feea6e827ff7148a59aba1 --- /dev/null +++ b/docs/API_reference/en/syslib/osTimer.md @@ -0,0 +1,70 @@ +# osTimer - OS Timer + +The module provides a timer interface for the underlying OS. The OS timer timeout will trigger the bound callback function. + +**Example** + +```python +import osTimer + +def test_cb(arg): + print("osTimer Expired!!") +# Create an OS timer +timer = osTimer() +# Start the timer. The parameters are time, loop or not, and callback function. +timer.start(10000,1,test_cb) +# Stop the timer +timer.stop() +``` + + +## Create Timer + +### `osTimer` + +```python +osTimer() +``` + +Creates an OS timer object. + +> Compared with [machine.Timer](./machine.Timer.md), there is no limit on the number of created timers. + +## Start Timer + +### `osTimer.start` + +```python +osTimer.start(initialTime, cyclialEn, callback) +``` + +**Parameter** + +* `initialTime` - Integer type. The timeout for the timer. Unit: ms. +* `cyclialEn` - Integer type. Loop or not. 0 - Once. 1 - Loop. +* `callback` - Function type. Callback function triggered when the timer expires. Prototype: *callback(arg)*. `arg` is not actually used and `None` can be configured directly. + +**Return Value** + +Integer type. + +0 - Successful execution + +Other values - Failed execution + +## Stop Timer + +### `osTimer.stop` + +```python +osTimer.stop() +``` +Stops the timer. + +**Return Value** + +Integer type. + +0 - Successful execution + +Other values - Failed execution \ No newline at end of file diff --git a/docs/API_reference/en/syslib/pm.WakeUp.md b/docs/API_reference/en/syslib/pm.WakeUp.md new file mode 100644 index 0000000000000000000000000000000000000000..960b1a93130926c3679cf6e263ed076ce7847d75 --- /dev/null +++ b/docs/API_reference/en/syslib/pm.WakeUp.md @@ -0,0 +1,106 @@ +# class WakeUp - Wake-Up Interrupt + +The ordinary GPIOs of the EC600/EC800E series do not support double-edge trigger interrupts, and do not support interrupts to wake up the module during sleep. WakeUp has no pull-up/pull-down restrictions, supports double-edge trigger interrupts and waking up the module during sleep by default. The usage is as follows: + +## **Constructor** + +```python +class pm.WakeUp(WakeupID, pull) +``` + +**Parameter:** + +- `WakeupID` - The wakeup number to control, described as follows:
EC800E:
`WAKEUP2` - Pin 79
`WAKEUP3` - Pin 109 (unavailable for EC800ECN_LE&LQ&LC)
`WAKEUP4` - Pin 108 (unavailable for EC800ECN_LE&LQ&LC)
`WAKEUP5` - Pin 19 + + EC600E:
`WAKEUP2` - Pin 9
`WAKEUP3` - Pin 51
`WAKEUP4` - Pin 50
`WAKEUP5` - Pin 39 + +- `pull` - Pull-up/pull-down mode, int type, described as follows:
`PULL_DISABLE` – Floating mode 0
`PULL_PU` – Pull-up mode 1
`PULL_PD` – Pull-down mode 2
+ +**Example:** + +```python +from pm import WakeUp +def fun(level): + print(str(level)) + +wake=WakeUp(WakeUp.WAKEUP5,WakeUp.PULL_PD) +wake.set_callback(fun)# Set callback, callback only returns level +wake.enable()# Enable interrupt + +wake.read() #Read pin level +``` + +## Methods + +### `wake.enable` + +```python +wake.enable() +``` + +This method is used to enable the WakeUp interrupt. When a rising or falling edge is detected on the WakeUp pin, the callback will be executed. + +**Return Value:** + +Returns integer value `0` for success, `-1` for failure. + +### `wake.disable` + +```python +wake.disable() +``` + +This method is used to disable the interrupt and disable the interrupt associated with the WakeUp object. + +**Return Value:** + +Returns integer value `0` for success, `-1` for failure. + +### `wake.read` + +```python +wake.read() +``` + +This method is used to read the current pin level. + +**Return Value:** + +Returns pin level, `0` means low pin level, `1` means high pin level. + +### `wake.deinit` + +```python +wake.deinit() +``` + +Disable WakeUp function. + +**Return Value:** + +Returns integer value `0` for success, `-1` for failure. + +### `wake.set_callback` + +```python +wake.set_callback(fun) +``` + +This method is used to set the callback. After the interrupt is triggered, this callback will be executed and return the level. + +**Parameter:** + +- `fun` - Callback function with prototype: + + ``` + fun(level) + ``` + + Callback function parameter description: + + - level:`0`: low level, `1`: high level. + +| Module | WakeUp Pin Description | +| ------ | ------------------------------------------------------------ | +| EC800E | `WAKEUP2` - Pin 79
`WAKEUP3` - Pin 109 (unavailable for EC800ECN_LE&LQ&LC)
`WAKEUP4` - Pin 108 (unavailable for EC800ECN_LE&LQ&LC)
`WAKEUP5` - Pin 19 | +| EC600E | `WAKEUP2` - Pin 9
`WAKEUP3` - Pin 51
`WAKEUP4` - Pin 50
`WAKEUP5` - Pin 39 | \ No newline at end of file diff --git a/docs/API_reference/en/syslib/pm.md b/docs/API_reference/en/syslib/pm.md new file mode 100644 index 0000000000000000000000000000000000000000..6c0737da36a7639dfd7c12f6b1ac64c3668ddf0c --- /dev/null +++ b/docs/API_reference/en/syslib/pm.md @@ -0,0 +1,254 @@ +# pm - Power Management + +When there is no service being processed, the system is in the sleep status and enters a low-power mode. + +**Example** + +Only for simulation tests. Please use the feature according to business scenarios in actual development. + +```python +import pm +import utime + +# Creates a wakelock +lpm_fd = pm.create_wakelock("test_lock", len("test_lock")) +# Sets the automatic sleep mode +pm.autosleep(1) + +# Only for simulation tests. Please use the feature according to business scenarios in actual development. +while 1: + utime.sleep(20) # Sleep + res = pm.wakelock_lock(lpm_fd) + print("ql_lpm_idlelock_lock, g_c1_axi_fd = %d" %lpm_fd) + print("unlock sleep") + utime.sleep(20) + res = pm.wakelock_unlock(lpm_fd) + print(res) + print("ql_lpm_idlelock_unlock, g_c1_axi_fd = %d" % lpm_fd) + num = pm.get_wakelock_num() # Gets the number of created wakelocks. + print(num) +``` + +## Create Wakelock + +### `pm.create_wakelock` + +```python +pm.create_wakelock(lock_name, name_size) +``` + +Creates a wakelock. + +**Parameter** + +* `lock_name` - String type. Custom lock name. +* `name_size` - Integer type. Length of `lock_name`. It is an optional parameter. + +**Return Value** + +The wakelock ID: Successful execution + +`-1` - Failed execution + +> Note: BC25 series module does not support this method. + +## Delete Wakelock + +### `pm.delete_wakelock` + +```python +pm.delete_wakelock(lpm_fd) +``` + +Deletes a wakelock. + +**Parameter** + +* `lpm_fd` - Integer type. ID of the wakelock to be deleted. + +**Return Value** + + `0` - Successful execution + +Other values - Failed execution + +> Note: BC25 series module does not support this method. + +## Lock Wakelock + +### `pm.wakelock_lock` + +```python +pm.wakelock_lock(lpm_fd) +``` + +Sets the specified wakelock to lock status. When there is a locked wakelock, the module will not enter the low power mode. + +**Parameter** + +* `lpm_fd` - Integer type. ID of the wakelock to be locked. + +**Return Value** + + `0` - Successful execution + + `-1` - Failed execution + +> Note: BC25 series module does not support this method. + +## Release Wakelock + +### `pm.wakelock_unlock` + +```python +pm.wakelock_unlock(lpm_fd) +``` + +Releases a wakelock. Only when all wakelocks are released will the module enter the low-power mode. + +**Parameter** + +* `lpm_fd` - Integer type. ID of the wakelock to be released. + +**Return Value** + + `0` - Successful execution + + `-1` - Failed execution + +> Note: BC25 series module does not support this method. + +## Set Automatic Sleep Mode + +### `pm.autosleep` + +```python +pm.autosleep(sleep_flag) +``` + +Sets automatic sleep mode. + +**Parameter** + +* `sleep_flag` - Integer type. `0` - Disable automatic sleep mode; `1` - Enable automatic sleep mode. + +**Return Value** + + `0` - Successful execution + + `-1` - Failed execution + +## Get the Number of Created Wakelocks + +### `pm.get_wakelock_num` + +```python +pm.get_wakelock_num() +``` + +Gets the number of created wakelocks. + +**Return Value** + +Integer type. The number of created wakelocks. + +> Note: BC25 series module does not support this method. + +## Set PSM Time + +### `pm.set_psm_time` + +```python +pm.set_psm_time(tau_uint,tau_time,act_uint,act_time) # Sets and enables PSM + +pm.set_psm_time(mode)# Enables or disables PSM +``` + +**Parameter** + +* `mode` - Integer type. Whether to enable PSM. + `0 ` - Disable PSM + `1 ` - Enable PSM + `2 ` - (Only for BC25 series module) Disable PSM and delete all parameters of PSM. If there is a default value, this method will reset the default value. (Please note that if you disable PSM in this way, you must call *pm.set_psm_time(tau_uint,tau_time,act_uint,act_time)* to enable PSM, because calling *pm.set_psm_time(mode)* is relatively nonsensical when all PSM parameters are deleted. +* `tau_uint` - Integer type. Unit of TAU (T3412). + +| Value of TAU Unit | Type | Description | +| ----------------- | ---- | ----------- | +| 0 | int | 10 minutes | +| 1 | int | 1 hour | +| 2 | int | 10 hours | +| 3 | int | 2 seconds | +| 4 | int | 30 seconds | +| 5 | int | 1 minute | +| 6 | int | 320 hours | +| 7 | int | Disabled | + +* `tau_time` - Integer type. Periodic value of TAU (T3412). +* `act_uint` - Integer type. Unit of ATC (T3324). + +| Value of ATC Unit | Type | Description | +| ----------------- | ---- | ----------- | +| 0 | int | 2 seconds | +| 1 | int | 1 minute | +| 2 | int | 6 minutes | +| 7 | int | Disabled | + +* `act_time` - Integer type. Periodic value of ATC (T3324). + +> The TAU and ATC actually set is the product of the unit value and the periodic value. + +**Return Value** + +`True ` - Successful execution +`False` - Failed execution + +**Example** + +```python +>>> import pm +>>> pm.set_psm_time(1,2,1,4) # Sets the periodic TAU request to 2 hours (1 hour * 2 = 2 hours) and ATC request to 4 minutes (1 minute * 4 = 4 minutes). +True +>>> +``` + +> Only BC25/ECX00U/ECX00E series module supports this method. + +## Get PSM Time + +### `pm.get_psm_time` + +```python +pm.get_psm_time() +``` + +**Return Value** + +List type - Successful execution + +The parameters are described below. + +| Parameter | Type | Description | +| --------- | ---- | ------------------------------------------------------------ | +| list[0] | int | mode
0- Disable PSM.
1- Enable PSM.
2- (Only for BC25 series module) Disable PSM and delete all parameters of PSM. If there is a default value, this method will reset the default value. | +| list[1] | int | TAU unit | +| list[2] | int | Periodic value of TAU | +| list[3] | int | ACT unit | +| list[4] | int | Periodic value of ACT | + + `None` - Failed execution + +**Example** + +```python +>>> pm.get_psm_time() + +[1, 1, 1, 1, 2] + + +``` + +> Only BC25/ECX00U/ECX00E series module supports this method. + +## Classes + +- [class WakeUp - Wake-Up Interrupt](./pm.WakeUp.md) diff --git a/docs/API_reference/en/syslib/ql_fs.md b/docs/API_reference/en/syslib/ql_fs.md new file mode 100644 index 0000000000000000000000000000000000000000..e1f0ff5a976af43a89e953296b83bdf70b9c3270 --- /dev/null +++ b/docs/API_reference/en/syslib/ql_fs.md @@ -0,0 +1,226 @@ +# ql_fs - Advanced Operations of Files + +This feature is used for advanced operations of files. + + + +## Query Whether File or Folder Exists + +### `ql_fs.path_exists` + +```python +ql_fs.path_exists(file_path) +``` + +**Parameter** + +* `file_path` - String type. The absolute path of the file or folder. + +**Return Value** + +True - The file or folder exists. + +False - The file or folder does not exist. + +**Example** + +```python +>>> import ql_fs +>>> ret = ql_fs.path_exists("/usr/xxx.py") +>>> print(ret) + +# If files or folders exist, True will be printed. Otherwise, False will be printed. +``` + + + +## Get Folder or File Path + +### `ql_fs.path_dirname` + +```python +ql_fs.path_dirname(file_path) +``` + +**Parameter** + +* `file_path` - String type. The absolute path of the file or folder. + +**Return Value** + +String type. File or folder path. + +**Example** + +```python +>>> import ql_fs +>> ret = ql_fs.path_dirname("/usr/bin") +>>> print(ret) + +# Print result: +# /usr +``` + + + +## Create Folder + +### `ql_fs.mkdirs` + +```python +ql_fs.mkdirs(dir_path) +``` + +Creates a folder recursively and configures a folder path. + +**Parameter** + +* `dir_path` - String type. The absolute path of the folder to be created. + +**Example** + +```python +>>> import ql_fs +>>> ql_fs.mkdirs("usr/a/b") +``` + + + + + +## Delete Folder + +### `ql_fs.rmdirs` + +```python +ql_fs.rmdirs(dir_path) +``` + +**Parameter** + +* `dir_path` - String type. The absolute path of the folder to be created. + +**Example** + +```python +>>> import ql_fs + +>>> ql_fs.rmdirs("usr/a/b") +``` + + + +## Get File Size + +### `ql_fs.path_getsize` + +```python +ql_fs.path_getsize(file_path) +``` + +**Parameter** + +* `file_path` - String type. The absolute path of the file or folder. + +**Return Value** + +An integer. Unit: byte. + +**Example** + +```python +import ql_fs + +ql_fs.path_getsize('usr/system_config.json') +``` + + + +## Create File + +### `ql_fs.touch` + +```python +ql_fs.touch(file, data) +``` + +Creates a file or updates file data. If the configured file path already exists, update the file content. If the configured file path does not exist, create a file and write the file content. + +**Parameter** + +* `file` - String type. The absolute path of the file. + +* `data` - Dict type. The data to be written. Currently only files in JSON format are supported. + +**Return Value** + +Integer type. + +0 - Successful execution + +-1 - Failed execution + +**Example** + +```python +>>> import ql_fs +>>> data = {"test":1} +>>> ql_fs.touch("/usr/bin/config.json", data) +``` + + + +## Read File in JSON Format + +### `ql_fs.read_json` + +```python +ql_fs.read_json(file) +``` + +Files in JSON format will be read directly and returned. The data of string type will be returned for files in other formats. + +**Parameter** + +* `file` - String type. The absolute path of files or folders. + +**Return Value** + +Dictionary type - Successful execution + +None - Failed execution + +**Example** + +```python +>>> import ql_fs +>>> data = ql_fs.read_json("/usr/system_config.json") +``` + + + +## Copy File + +### `ql_fs.file_copy` + +```python +ql_fs.file_copy(dst, src) +``` + +Copies files from the source path to the target path. + +**Parameter** + +* `dst` - String type. The target file path. +*`src` - String type. The source file path. + +**Return Value** + +True - Successful execution + +**Example** + +```python +>>> import ql_fs +>>> ql_fs.file_copy("usr/a.json", "usr/system_config.json") +``` \ No newline at end of file diff --git a/docs/API_reference/en/syslib/securedata.md b/docs/API_reference/en/syslib/securedata.md new file mode 100644 index 0000000000000000000000000000000000000000..2250239b27ae7d2bccc4e4f4c40878d8536cefde --- /dev/null +++ b/docs/API_reference/en/syslib/securedata.md @@ -0,0 +1,77 @@ +# securedata - Secure-Data Area + +The module provides a bare flash area and a dedicated read/write interface for you to store important information, which won't be lost after the firmware burning. (If you burn the firmware that does not provide the secure data area, it cannot be ensured that information won't be lost.) Besides, the module also provides a storage and read interface but deletion interface is not provided. + + +> All Quectel modules support SecureData area, excluding BC25, BG95 and EC200A series modules. + +**Example** + +```python +import SecureData +# A cache used to store data +databuf = '\x31\x32\x33\x34\x35\x36\x37\x38' +# In a storage area with index as 1, store data with a length of 8 bytes +SecureData.Store(1, databuf, 8) +# Define an array with a length of 20 bytes to read stored data +buf = bytearray(20) +# Read the data from the storage area with index as 1 to buf and the length of the read data is stored in the variable length +length = SecureData.Read(1, buf, 20) +# Output the read data +print(buf[:length]) +``` + + +## Data Storage + +### `SecureData.Store` + +```python +SecureData.Store(index,databuf,len) +``` + +**Parameter** + +* `index` - Integer type. +| Index Serial Number | Maximum Storage | +| ------------------- | --------------- | +| 1 - 8 | 52 bytes | +| 9 - 12 | 100 bytes | +| 13 - 14 | 500 bytes | +| 15 - 16 | 1000 bytes | +* Special for FCM362K model: +| Index Serial Number | Maximum Storage | +| ------------------- | --------------- | +| 1 - 6 | 248 bytes | +| 7 - 8 | 1016 bytes | +* `databuf` - Bytearray type. A data array to be stored. +* `len` - Integer type. The length of data to be written. + +> Store the one with the shorter data length between databuf and len. + +**Return Value** + +`-1`: Parameter error. +`0`: Normal execution. + +## Data Reading + +### `SecureData.Read` + +```python +SecureData.Read(index,databuf,len) +``` + +**Parameter** + +* `index` - Integer type. Index range: 1-16; Index number of the data to be read. +* `databuf` - Bytearray type. Store the read data. +* `len` - Integer type. Length of data to be read. + +> If the stored data is not larger than the input parameter len, the actual stored data length is returned. + +**Return Value** + +`-2`: Both storage and backup data do not exist. +`-1`: Parameter error. +`Other values`: Length of data actually read. \ No newline at end of file diff --git a/docs/API_reference/en/syslib/sys_bus.md b/docs/API_reference/en/syslib/sys_bus.md new file mode 100644 index 0000000000000000000000000000000000000000..bcfca1c806cb45b54d0f7e9e57a0a9fd899df9d5 --- /dev/null +++ b/docs/API_reference/en/syslib/sys_bus.md @@ -0,0 +1,102 @@ +# sys_bus - Session Bus + +This feature subscribes to messages and publishes one-to-many broadcasts with multithreading, similar to an internal MQTT protocol. + + + +## Subscribe to Topics + +### `sys_bus.subscribe` + +```python +sys_bus.subscribe(topic, handler) +``` + +**Parameter** + +* `topic` – String or integer type. The topic to be subscribed to. +* `handler` – Function type. Event handler function. This function will be called to handle the subscribed topics. This function has two parameters, *topic* and *msg* (See *sys_bus.publish()* for details). + + + +## Publish Topics + +### `sys_bus.publish` + +```python +sys_bus.publish(topic , msg) +``` + +Publishes messages. The server will receive the subscribed topics and process the message with multithreading. + +**Parameter** + +* `topic` – String or integer type. The topic to be subscribed to. +* `msg` – The published messages. + + + +## View Session Bus Registry + +### `sys_bus.sub_table` + +```python +sys_bus.sub_table(topic=None) +``` + +Views the subscription registry, including all topics and the subscribed functions. + +**Parameter** +* `topic` – String or integer type. Topics. If this parameter is specified, view the registry of the specified topic. If this parameter is omitted, view the registry of all topics. + +**Return Value** + +Dict or list type. The list or registry of the subscribed functions. + + + +## Unsubscribe from Topics + +### `sys_bus.unsubscribe` + +```python +sys_bus.unsubscribe(topic , cb=None) +``` + +Unsubscribes from the subscribed topics or a function under the topics. If only *topic* is specified, unsubscribe from the topics and all subscribed functions under the topics. If both *topic* and *cb* are specified, unsubscribe from the callback function under the subscribed topics. + +**Parameter** + +* `topic`– String or integer type. The subscribed topics. +* `cb` – Function type. Callback function. The function to be unsubscribed from. Unsubscribe from the subscribed topics if this parameter is omitted. + +**Return Value** + +True – Successful execution + +False – Failed execution + + + +**Example** + +```python +import sys_bus + + +def test(topic, msg): + print("test ... topic = {} msg = {}".format(topic, msg)) + +# Subscribe +sys_bus.subscribe("test", test) +# Publish +sys_bus.publish("test", "this is a test msg") + +# test ... topic = test msg = this is a test msg + +# Unsubscribe from the test function under the test topic +sys_bus.unsubscribe("test", test) + +# Unsubscribe from all subscribed functions under the test topic +sys_bus.unsubscribe("test") +``` \ No newline at end of file diff --git a/docs/API_reference/en/syslib/system.md b/docs/API_reference/en/syslib/system.md new file mode 100644 index 0000000000000000000000000000000000000000..b7c219efcf8516bd63cc8a28e59f2604978ca2c9 --- /dev/null +++ b/docs/API_reference/en/syslib/system.md @@ -0,0 +1,131 @@ +# system - System Configuration + +This feature is used to configure the system parameter and features. + +Applicable modules: EC100Y(V0009) and above; EC600S(V0002) and above. + + +### `system.replSetEnable` + +```python +system.replSetEnable(flag,**kw_args) +``` + +Enables or disables interaction protection. + +**Parameter** + +1. When kw_args is omitted + +0 - Disable (default) + +1 - Enable + +2 - Query the current encryption status + +After the interaction protection is enabled, all external commands and codes cannot be executed and the operation is irreversible. Please enable the interaction protection after confirmation. Default value: 0. + +2. When kw_args is configured + +Interaction protection can be enabled and disabled by a password. (Few module models do not support password protection, so when you enter a password on a module that does not support password protection, you will receive an error message. For example BC25 series and EC600M series modules.) + +* Parameter + +| Parameter | Type | Description | +| :--- | :--- | ---------------------------- | +| flag | Integer | 0 - Disable (default)
1 - Enable
2- Query encryption status | +| kw_args | String | Password (optional) | + +* Return Value + +0 - Successful execution + +-1 or errorlist or both - Failed execution + +If *flag* is set to 2, the return values are as follows. +-1 - Querying failed +1 - repl enable +2- repl enable but The password has already been set +3 - repl refuse +4 - repl-protection by password + + +### `system.replChangPswd` + +```python +system.replChangPswd(old_password,new_password) +``` + +Changes the password for interaction protection. + +* Parameter + +| Parameter | Type | Description | +| :----------- | :----- | --------------------------------- | +| old_password | String | Old password. Length: 6–12 bytes. | +| new_password | String | New password. Length: 6–12 bytes. | + +* Return Value + +0 - Successful execution + +-1 or errorlist or both - Failed execution + +**Example** + +```python +>>>import system + +>>> system.replSetEnable(1,password='miamia123')//Set a password for the first time upon startup and enable interaction protection. You can set a password with a length of 6 to 12 bytes. +0 +>>> //Set successfully. The interaction interface is locked and only can be used after you enter the password. +Please enter password: +>>> ****** //Incorrect password. +Incorrect password, please try again: +>>> ******** //Incorrect password. +Incorrect password, please try again: +>>> ********* //Correct password. The interaction interface is available. +REPL enable +>>> system.replSetEnable(2) +2 +>>> + +>>> system.replSetEnable(1,password='miamia') //A password has been set. You need to enter the correct password to relock the interaction interface. +Incorrect password! +-1 +>>> system.replSetEnable(1,password='miamia123') +0 +>>> +Please enter password: //Relock the interaction interface. +>>> miamia123 +********* +REPL enable +>>> system.replSetEnable(2) +2 + + +>>> system.replChangPswd(old_password='miamia123',new_password='123456') //Change password. +0 +>>> system.replSetEnable(1,password='miamia123') //The password has been changed, so the message "incorrect password" will be prompted if you try to lock the interface with the old password. +Incorrect password! +-1 +>>> system.replSetEnable(1,password='123456') //Relock the interaction interface with the new password successfully. +0 +>>> +Please enter password: +>>> ****** +REPL enable + +>>> system.replSetEnable(0,password='123456') //Disable interaction protection, after which you can use any password to relock the interaction interface. + +0 +>>> +>>> system.replSetEnable(2) //Query the current interaction protection status. +1 +>>> system.replSetEnable(0) //Default value: 0. +0 +>>>system.replSetEnable(1) //Enable interaction protection. +>>> +REPL refuse +>>> +``` diff --git a/docs/API_reference/en/wifilib/README.md b/docs/API_reference/en/wifilib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00c09d7f12b2567c7e0962af220a8d6263fe9edd --- /dev/null +++ b/docs/API_reference/en/wifilib/README.md @@ -0,0 +1,11 @@ +# QuecPython Wi-Fi communication + +> QuecPython Wi-Fi Communication Library includes functional components related to wireless local area networks + +This article describes the modules in the QuecPython Wi-Fi communication library. + +## QuecPython Wi-Fi communication library list + +- [WLAN - related functions](./WLAN.md) +- [ESP8266 - Control ESP8266](./WLAN.ESP8266.md) +- [ASR5803W - ASR5803W Driver](./WLAN.ASR5803W.md) \ No newline at end of file diff --git a/docs/API_reference/en/wifilib/WLAN.ASR5803W.md b/docs/API_reference/en/wifilib/WLAN.ASR5803W.md new file mode 100644 index 0000000000000000000000000000000000000000..654c195048f51470300ebee16cfa0b18b7a9b6a7 --- /dev/null +++ b/docs/API_reference/en/wifilib/WLAN.ASR5803W.md @@ -0,0 +1,149 @@ +# class ASR5803W - ASR5803W Driver + +This class controls the Wi-Fi NIC: `ASR5803W`. + +> Supported module models: EC200A series. + +## Constructor + +### `network.ASR5803W` + +```python +class network.ASR5803W(mode, wlan_ldo_en_pin, wlan_reset_pin, host_wake_wlan_pin, wlan_wake_host_pin) +``` + +Initialize the Wi-Fi NIC information and return the Wi-Fi NIC object. + +**Parameter** + +- `mode` - Integer type. Wi-Fi NIC working mode. 0: AP mode. 1: STA mode (not supported currently). +- `wlan_ldo_en_pin` - Integer type. EN pin of the Wi-Fi NIC. +- `wlan_reset_pin` - Integer type. Reset pin of the Wi-Fi NIC. +- `host_wake_wlan_pin` - Integer type. Pin of module waking up the Wi-Fi NIC. +- `wlan_wake_host_pin` - Integer type. Pin of Wi-Fi NIC waking up the module. + +**Example** + +```python +import network +from machine import Pin + +nic = network.ASR5803W(0, Pin.GPIO7, Pin.GPIO36, Pin.GPIO34, Pin.GPIO6) +``` + +## Method + +### `ASR5803W.active` + +```python +ASR5803W.active([is_active]) +``` + +Configure/query the activation status of ASR5803W. If **is_active** is specified, configure the NIC status. If **is_active** is not specified, query the NIC status. + +**Parameter** + +- `is_active` - Boolean type. + + True: Enable the NIC and activate the NIC configuration + + False: Disable the NIC + +**Return Value** + +0: Successful execution + +Other value: Failed execution + + +### `ASR5803W.isconnected` + +```python +ASR5803W.isconnected() +``` + +Query whether there is a client connected to the Wi-Fi NIC. + +**Return Value** + +True: A client is connected to the Wi-Fi NIC + +False: No client is connected to the Wi-Fi NIC + + +### `ASR5803W.status` + +```python +ASR5803W.status([param]) +``` + +Query the NIC status. **param** can be `stations/node` or `speed`. You can only query one parameter value at a time. If **param** is not specified, query the current connection status. If **param** is `stations/node` or `speed`, query the corresponding parameter value. + +**Parameter** + +- `stations/node` - List of devices currently connected to the client +- `speed` - Network speed of the NIC. + +**Return Value** + +If **param** is not specified + +- `True` - The NIC is connected. +- `False` - The NIC is not connected. + +If **param** is `stations/node` +- List type. List of devices currently connected to the client. + + - 0: No device is connected. + + - A list containing two elements: At least one device is connected. + + - Element 1: Integer type. The number of currently connected devices. + + - Element 2: Tuple type. Information of the currently connected devices. The information in the tuple includes the device MAC address (byte type), the device IP address (string type), and the device connection time (Integer type. Unit: second). + +If **param** is `speed` + +- Tuple type. The current network speed of the NIC. + - Element 1: Integer type. Downlink network speed. Unit: bps. + - Element 2: Integer type. Uplink network speed. Unit: bps. + + +### `ASR5803W.config` + +```python +ASR5803W.config('param') +ASR5803W.config(param=value) +``` + +Query/configure network information. + +If only the parameter name is specified, *ASR5803W.config* is used to query the current parameter value. Only one value can be queried at a time. + +If the parameter value is specified, *ASR5803W.config* is used to configure the parameter. When the return value is True, it indicates a successful setting; when the return value is False, it indicates a failed setting. Multiple values can be configured at the same time. + +**Parameter** + +| Parameter | Type | Description | +| ---- | ---- |---------- | +| `ssid` | `str` | Wi-Fi network name | +| `authmode`| `enum` | Authentication type | +| `security` | `enum` | Encryption method | +| `password` | `str` | Password | +| `protocol` | `enum` | Network protocol | +| `channel` | `enum` | Wi-Fi network channel number | +| `b40acs` | `bool` | Channel adaptation in LTE band 40 | +| `mac` | `str` | MAC address | + +**Example** +Query network information: + +```python +# Query SSID configuration +ASR5803W.config('ssid') +``` +Configure network information: +```python +# Configure Wi-Fi name and channel +ASR5803W.config(ssid='ssid', channel=1) +``` \ No newline at end of file diff --git a/docs/API_reference/en/wifilib/WLAN.ESP8266.md b/docs/API_reference/en/wifilib/WLAN.ESP8266.md new file mode 100644 index 0000000000000000000000000000000000000000..0fcf5c33c42eed1a93173116f97f59d58bbd5808 --- /dev/null +++ b/docs/API_reference/en/wifilib/WLAN.ESP8266.md @@ -0,0 +1,298 @@ + +# class ESP8266 - Control ESP8266 + +This class controls `ESP8266`. + +## Constructor + +### `ESP8266` + +```python +class ESP8266(uart=UART.UART1, mod=ESP8266.STA, callback=None) +``` + +Load ESP8266 driver, initialize the virtual Wi-Fi module and return the ESP8266 object. + +**Parameter** + +- `uart` - Module UART option, indicating the `UART ID` that the module connects to ESP8266. Default: `UART1`. +- `mode` - The working mode of the Wi-Fi module, which specifies the `working mode` of ESP8266. The working mode of station mode is ESP8266.STA, while the working mode of AP mode is ESP8266.AP. Default: `Station ` mode. +- `callback` - Enable or disable the callback function, used for the notifications of `network changes` and `OTA upgrades`. Default: disable. + +**callback Parameter** + +- `content` - The reported content. + +**The Reported Content** + +Once the callback function is enabled, the module will report the notifications when an OTA upgrade occurs and the network connectio mode changes in `station` mode. + +Report `ota` information: +- `ota,begin` - OTA upgrade starts. +- `ota,downloading,xx` - Percentage of OTA upgrade. +- `ota,restart` - Reboot after the OTA upgrade is completed. +- `ota,err_code,x` - OTA upgrade error code. + - `1` - Failed to analyze the URL + - `2` - Failed to connect to the HTTP server + - `3` - Failed to allocate memory for a GET request + - `4` - Failed to send a GET request to the server + - `5` - An error occurred when the OTA upgrade started + - `6` - Failed to receive data + - `7` - Failed to write OTA upgrade files + - `8` - An error occurred when the OTA upgrade ended + - `9` - Failed to set boot partition + +Report the network connection change in `station` mode: +- `station, connected` - The Wi-Fi has been connected. +- `station, disconnected` - The Wi-Fi has been disconnected. + +**Example** + +```python +# callback Example +from usr.WLAN import ESP8266 +from machine import UART + +def cb(args): + content = args + print('wifi content:{}'.format(content)) + +ESP8266 = ESP8266(UART.UART2, ESP8266.STA, cb) + +``` + + +## Method + +### `ESP8266.status` + +```python +ESP8266.status() +``` + +Gets the Wi-Fi module status to determine the current working mode of the Wi-Fi module. + +**Return Value** + +Integer type. The enumerations are as follows. +- `0` - ESP8266 does not exist. +- `1` - ESP8266 station mode has been connected. +- `2` - ESP8266 station mode has not been connected. +- `3` - ESP8266 web mode +- `4` - ESP8266 AP mode +- `5` - ESP8266 OTA upgrading + + + + +### `ESP8266.version` + +```python +ESP8266.version() +``` + +Gets the current firmware information of the Wi-Fi module. + +**Return Value** + +String type. Format: (sdk, model, version, time). +- `sdk` - SDK information +- `model` - Wi-Fi module model +- `version` - Version number +- `time` - Version time + + + +### `ESP8266.ipconfig` + +```python +ESP8266.ipconfig() +``` + +Gets the current network configuration of the Wi-Fi module, including the IP address and DNS server. + +**Return Value** + +A Tuple (ip, subnet, gateway, mtu, primary_dns, secondary_dns). + +- `ip` - IP address +- `subnet` - Subnet mask +- `gateway` - Gateway address +- `mtu` - Maximum transmission unit +- `primary_dns` - IP address of the primary DNS server +- `secondary_dns` - IP address of the secondary DNS server + + + +### `ESP8266.station` + +```python +ESP8266.station(username,password) +``` + +Enables the Wi-Fi module to work in `station` mode to connect to a specified Wi-Fi router. + +**Parameter** + +- `username` - Name of the Wi-Fi to be connected. Range: 1–32 characters. +- `password` - Password of the Wi-Fi to be connected. Range: 8–64 characters. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.ap` + +```python +ESP8266.ap(username,password) +``` + +Enables the Wi-Fi module to work in `ap` mode as an AP. + +**Parameter** + +- `username` - Name of the `Wi-Fi hotspot`. Range: 1–32 characters. +- `password` - Password of the `Wi-Fi hotspot`. Range: 8–64 characters. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.web_config` + +```python +ESP8266.web_config(username,password) +``` + +Enables the Wi-Fi module to work in `web` mode. You can configure the network on the web page. + +> Note: After enabling the network configuration, use a terminal device such as a mobile phone or computer to connect to a Wi-Fi module (with a custom name and password) over a wireless network. Then enter 192.168.4.1 in the browser to access the web page. + +**Parameter** + +- `username` - Name of the `web hotspot`. Range: 1–32 characters. +- `password` - Password of the `web hotspot`. Range: 8–64 characters. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.ota` + +```python +ESP8266.ota(url) +``` + +Updates the firmware after an `OTA upgrade` is enabled. + +> Note: Only when the module is in station mode can the module be upgraded over the air. In the OTA upgrade process, you can only query the current status rather than perform any other operation. + +**Parameter** + +- `url` - The URL of firmware download. Only HTTP is supported currently. Length: up to 256 bytes. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + +**Example** + +```python + +url='http://www.example.com/fota.bin' + +ESP8266.ota(url) + +``` + + + +### `ESP8266.stop` + +```python +ESP8266.stop() +``` + +Releases the virtual Wi-Fi module configured for the Wi-Fi module. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.set_default_NIC` + +```python +ESP8266.set_default_NIC(ip_str) +``` + +Specifies the Wi-Fi module to forward the network. + +**Parameter** + +- `ip_str` - String type. The IP address of the Wi-Fi module used by default to forward network data, such as '192.168.1.100'. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.set_dns` + +```python +ESP8266.set_dns(pri_dns, sec_dns) +``` + +Specifies the `DNS server` of the Wi-Fi module for IP address resolution. + +**Parameter** + +- `pri_dns` - IP address of the `primary DNS` server. Default value: `8.8.8.8`. +- `sec_dns` - IP address of the `secondary DNS` server. Default value: `114.114.114.114`. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution + + + +### `ESP8266.router_add` + +```python +ESP8266.router_add(ip, mask) +``` + +Sets forwarding rules of the Wi-Fi module. + +**Parameter** + +- `ip` - IP address of the Wi-Fi module in `AP` mode. Default value: 192.168.4.1. +- `mask` - Subnet mask. Default value: 255.255.255.0. + +**Return Value** + +`0` - Successful execution + +Other values - Failed execution \ No newline at end of file diff --git a/docs/API_reference/en/wifilib/WLAN.md b/docs/API_reference/en/wifilib/WLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..16cd08007779600d6b339040528add0743a37d2c --- /dev/null +++ b/docs/API_reference/en/wifilib/WLAN.md @@ -0,0 +1,732 @@ +# WLAN - Wireless Local Area Network + +This class `WLAN` is primarily used for controlling the Wi-Fi network card. + +> Supported module model: FCM360W + +**Example:** + +```python +# This example demonstrates the functionality of connecting the Wi-Fi network card to a hotspot and performing network communication. +import network +import utime +nic = network.WLAN(network.STA_MODE) +while nic.status("station_if") != 1011: + print("Waiting for connection...") + nic.connect(ssid="your_ssid", password="your_password") + utime.sleep(1) +print(nic.ifconfig()) + +# Now use socket as usual +import usocket +addr = usocket.getaddrinfo("python.quectel.com", 80)[0][-1] +s = usocket.socket() +s.connect(addr) +s.send(b"GET / HTTP/1.1\r\nHost: python.quectel.com\r\n\r\n") +data = s.recv(1000) +print(data) +s.close() +``` + +## Constructor + +### `network.WLAN` + +```python +class network.WLAN(mode) +``` + +Initialize WLAN network card and return a WLAN object. + +**Parameter:** + +- `mode` - Wireless network card operating mode, `int` type. + - `network.NONE_MODE` : `0` - Idle mode. + - `network.AP_MODE` : `1` - AP (Access Point) mode, supports only wireless client connections. + - `network.STA_MODE` : `2` - Station mode, connects to a wireless network, such as a router or mobile hotspot. + - `network.AP_STA_MODE` : `3` - AP+Station mode, supports both wireless client connections and connection to a wireless network. + +> Note: +> +> 1. Only one WLAN network card object can be created. Attempting to create more will raise an exception: `ERR_WLAN_NETIF_IS_BUSY`. +> 2. The WLAN network card has a total of four working modes as mentioned above. These four modes are actually operations on two network interfaces: the `softap interface` and the `station interface`. When the mode is `AP_STA_MODE`, both `softap` and `station` interfaces coexist. Therefore, when calling some interface-specific functions, the `interface` parameter needs to be specified to indicate the intended interface, or else it won't be clear which interface you are targeting. + +**Example:** + +```python +# Create Station mode and connect to a specified AP +import network +nic = network.WLAN(network.STA_MODE) +nic.connect(ssid='your-ssid', password='your-password') +nic.status("station_if") +``` + +## Methods + +### `WLAN.mode` + +```python +WLAN.mode([mode]) +``` + +Set or query the wireless network card operating mode. + +- Query the wireless network card operating mode + + When called without parameters, it queries the wireless network card operating mode. +- Set the wireless network card operating mode + + When a parameter is provided, it sets the wireless network card operating mode. After mode switching, the wireless network card is in a stopped state. + +**Parameter:** + +- `mode` - Wireless network card operating mode, `int` type. + - `network.NONE_MODE` : `0` - Idle mode. + - `network.AP_MODE` : `1` - AP (Access Point) mode, supports only wireless client connections. + - `network.STA_MODE` : `2` - Station mode, connects to a wireless network, such as a router or mobile hotspot. + - `network.AP_STA_MODE` : `3` - AP+Station mode, supports both wireless client connections and connection to a wireless network. + +**Return:** + +- Query the wireless network card operating mode + + Returns the current operating mode of the wireless network card, `int` type. +- Set the wireless network card operating mode + + Returns an error code, `int` type. + + - `ERR_OK` : `2000` - No error. + - `ERR_WIFI_BUSY` : `2003` - Already in this operating mode. + - `ERR_INTERNAL` : `2006` - Internal error, the underlying interface encountered an error. + - `ERR_NOT_SUPPORT` : `2004` - This mode is not supported. + +**Examples:** + +```python +# Query the current mode +>>> nic.mode() +2 +``` + +```python +# Set the current mode to AP mode +>>> nic.mode(network.AP_MODE) +2000 +``` + +### `WLAN.config` + +```python +WLAN.config('param') +WLAN.config(param=value) +``` + +Set or query configuration parameters. + +- Query configuration parameters + + Input relevant keywords to query parameters, each time only one parameter can be queried, `str` type. +- Set configuration parameters + + When parameters are keyword arguments, it sets the parameters; multiple parameters can be set simultaneously. + +**Parameter:** + +- `ap_ssid` - SoftAP's wireless access point name, `str` type, 1~32 characters, default value: `'quecpython'`. +- `ap_password` - SoftAP's wireless access point password, `str` type, 0~63 characters, default value: `'quecpython'`. + + - `AUTH_OPEN` : `0` characters - No password required. + - `AUTH_WEP` : `5` characters - Fixed length of 5. + - `AUTH_WPA_PSK` : `8~63` characters. + - `AUTH_WPA2_PSK` : `8~63` characters. + - `AUTH_WPA_WPA2_PSK` : `8~63` characters. +- `ap_auth` - SoftAP's authentication method, `int` type, default value: `AUTH_WPA_WPA2_PSK`. + + - `AUTH_OPEN` : `0` - Open system authentication. + - `AUTH_WEP` : `1` - Wired Equivalent Privacy (WEP) authentication. + - `AUTH_WPA_PSK` : `2` - WPA Pre-Shared Key (PSK) authentication. + - `AUTH_WPA2_PSK` : `3` - WPA2 PSK authentication. + - `AUTH_WPA_WPA2_PSK` : `4` - Mixed mode, combining WPA and WPA2 PSK authentication. +- `ap_channel` - SoftAP's channel, `int` type. The allowable range is: `[1,13]`, default value: `3`. +- `ap_hidden` - Whether the wireless access point name of SoftAP is hidden, `bool` type, `True` for hidden, default value: `False`. +- `ap_max_clients` - Maximum number of client connections for SoftAP, `int` type, default value: `4`. +- `ap_mac` - MAC address of SoftAP, `str` type. +- `sta_ssid` - Wireless access point name to be connected by the station, `str` type, 1~32 characters. +- `sta_password` - Password of the wireless access point to be connected by the station, `str` type, 0~63 characters. +- `sta_bssid` - MAC address of the target wireless access point for the station, `str` type. +- `sta_channel` - Channel of the station, `int` type. The allowable range is: `[1,13]`. +- `sta_mac` - MAC address of the station, `str` type. +- `block` - Whether it is in blocking mode, `bool` type, default is `True`, i.e., blocking mode. Non-blocking mode should be used with event callbacks. +- `timeout` - Connection timeout period, `int` type, unit: s, default value: `15`s. +- `country` - Country code, `str` type. +- `event_callback` - WLAN status callback function, called when WLAN status changes, callback function prototype: + + ```python + fun(event) + ``` + + Callback function parameter description: + + - `event`: Event information, `dict` type, carrying the parameters as follows: + - `type`: Event type, `int` type, see `Event Type` in [Event Codes](#Event-Codes) for details. + - `id`: Specific event, `int` type, see `Event ID` in [Event Codes](#Event-Codes) for details. + - `msg`: Message passed to the user, see `Message Passed to User in Event Callback` in [Event Codes](#Event-Codes) for details. + +**Return Value:** + +- Query configuration parameters: + + Returns the query result. + If this interface fails, an error code will be returned. + + - `ERR_NO_AP_IF` : `2020` - Cannot obtain the current query information as the device is not in `AP` or `AP_STA` mode. + - `ERR_NO_STA_IF` : `2017` - Cannot obtain the current query information as the device is not in `STA` or `AP_STA` mode. + - `ERR_INTERNAL` : `2006` - Internal error, the underlying interface encountered an error. + - `ERR_NOT_SUPPORT` : `2004` - Unsupported parameter. +- Set configuration parameters: + + Returns an error code. + + - `ERR_OK` : `2000` - No error. + - `ERR_PARAM_INVALID` : `2002` - Parameter error. + - `ERR_INTERNAL` : `2006` - Internal error, the underlying interface encountered an error. + +**Examples:** + +```python +# Query AP SSID configuration +>>> nic.config('ap_ssid') +'quecpython' +``` + +```python +# Set to AP mode and connect with blocking +>>> import network +>>> nic = network.WLAN(network.AP_MODE) +>>> nic.config(ap_ssid="FCM360W-TEST", ap_password="12345678", ap_channel=5, ap_auth=nic.AUTH_WPA_WPA2_PSK, block=True, timeout=15) +>>> nic.active(True) +2000 +``` + +```python +# Set to AP+STA mode and connect with non-blocking +>>> import network +>>> +>>> def fun(event): +>>> print(event) +>>> +>>> nic = network.WLAN(network.AP_STA_MODE) +>>> nic.config(ap_ssid="FCM360W-TEST", ap_password="12345678", ap_channel=5, ap_auth=nic.AUTH_WPA_WPA2_PSK, sta_ssid="Tenda_996", sta_password="12345678", country="CN", block=False, timeout=15, event_callback=fun) +>>> nic.active(True) +2015 +>>> {'msg': {'password': '12345678', 'ssid': 'Tenda_996', 'rssi': -35, 'channel': 3, 'bssid': '50:2b:73:08:55:d1', 'auth': 3, 'cipher': 4}, 'type': 3200, 'id': 3201} +{'msg': ('192.168.137.206', '255.255.255.0', '192.168.137.1', '0.0.0.0', '0.0.0.0'), 'type': 3200, 'id': 3204} +``` + +### `WLAN.active` + +```python +WLAN.active([enable]) +``` + +Configure/Query the activation status of the network card. + +- Query Network Card Status + + It indicates querying the network card status without passing the parameter. +- Activate the Network Card + + It represents activating/disabling the network card when the parameter is passed as `True`/`False`. + +**Parameter:** + +- `enable` - `bool `type, `True`/`False` respectively represent activate/deactivate the network card. + +**Return Value:** + +- Network card status query + + Returns `True`/`False`, indicating activated/deactivated, `bool` type. +- Network card activation + + Returns error code, `int` type. + + - `ERR_OK`: `2000` - No error. + - `ERR_WOULDBLOCK`: `2015` - In non-blocking mode, when the conditions for activating the network card are met, the interface returns `ERR_WOULDBLOCK` and performs asynchronous network card activation. + - `ERR_PARAM_INVALID`: `2002` - Invalid parameter. + - `ERR_TIMEOUT`: `2023` - Execution timeout. + +**Example:** + +```python +# Query network card status +>>> nic.active() +False +``` + +```python +# Activate network card +>>> nic.active(True) +2000 +``` + +### `WLAN.connect` + +```python +WLAN.connect([ssid, password, bssid, timeout]) +``` + +Connects to a wireless network. Only supports Station mode and can be used for both blocking and non-blocking connections, with the default being blocking. The timeout is set to 15 seconds by default. If ssid and password are not specified, it will automatically connect to the last successfully connected AP. + +**Parameter:** + +- `ssid` - Specify the name of the Wi-Fi to connect to, `str` type, 1 to 32 characters. +- `password` - Specify the password for the Wi-Fi to connect to, `str` type, 0 to 63 characters. + - `AUTH_OPEN`: `0` characters - No password required. + - `AUTH_WEP`: `5` characters - Fixed length of 5. + - `AUTH_WPA_PSK`: `8~63` characters. + - `AUTH_WPA2_PSK`: `8~63` characters. + - `AUTH_WPA_WPA2_PSK`: `8~63` characters. +- `bssid` - Specify the BSSID information of the Wi-Fi to connect to; this parameter is the MAC address of the target AP, `str` type. +- `timeout` - Connection timeout in seconds, `int` type, default is `15` seconds. + +**Return Value:** + +Returns error code, `int` type. + +- `ERR_OK`: `2000` - No error. +- `ERR_WOULDBLOCK`: `2015` - In non-blocking mode, when the conditions for establishing a network connection are met, the interface returns `ERR_WOULDBLOCK` and performs an asynchronous network connection. +- `ERR_NO_STA_IF`: `2017` - Cannot connect to the Wi-Fi network, as the device is not in `STA` or `AP_STA` mode. +- `ERR_PARAM_INVALID`: `2002` - Invalid parameter. +- `ERR_TIMEOUT`: `2023` - Execution timeout. + +**Example:** + +```python +# Connect to an AP and set the timeout to 10 seconds +>>> import network +>>> nic = network.WLAN(network.STA_MODE) +>>> nic.connect(ssid='your-ssid', password='your-password', timeout=10) +``` + +### `WLAN.disconnect` + +```python +WLAN.disconnect([interface, mac, ip]) +``` + +Disconnect from the network. + +- In AP mode + + Passing the corresponding MAC or IP of the station can disconnect from that specific station. + + If no parameters are passed, it disconnects from all stations. +- In STA mode + + Disconnect from the AP network. +- In AP_STA mode + + Specify the WLAN interface to be operated on through the `interface` parameter. + +**Parameter:** + +- `interface` - Mandatory for AP_STA Mode, used to specify the WLAN interface to operate on, `int` type. + + - `SOFTAP_IF` : `0` - SoftAP interface. + - `STATION_IF` : `1` - Station interface. +- `mac` - Disconnect from the specified station with the given MAC address in AP or AP_STA mode. If MAC is `'FF:XX:XX:XX:XX:XX'`, it disconnects from all stations, `str` type. +- `ip` - Disconnect from the specified station with the given IP address in AP or AP_STA mode, `str` type. + +> If both the `mac` and `ip` parameters are passed simultaneously, the one specified later takes effect. + +**Return Value:** + +Returns an error code. + +- `ERR_OK` : `2000` - No error. +- `ERR_NO_AP_IF` : `2020` - Unable to operate on the softap interface as the current mode is not `AP` or `AP_STA`. +- `ERR_NO_STA_IF` : `2017` - Unable to operate on the station interface as the current mode is not `STA` or `AP_STA`. +- `ERR_PARAM_INVALID` : `2002` - Parameter error. +- `ERR_INTERNAL` : `2006` - Internal error, underlying interface operation failed. + +**Examples:** + +```python +# Disconnect a station with MAC '7e:d0:3f:21:5d:34' in AP mode +>>> nic.disconnect(mac="7e:d0:3f:21:5d:34") +2000 +``` + +```python +# Disconnect from the AP and close the station interface in STA mode +>>> nic.disconnect() +2000 +``` + +```python +# Disconnect from the AP and close the station interface in AP_STA mode +>>> nic.disconnect(interface=nic.STATION_IF) +2000 +``` + +```python +# Disconnect a station with IP '10.10.10.2' in AP_STA mode +>>> nic.disconnect(interface=nic.SOFTAP_IF, ip="10.10.10.2") +2000 +``` + +### `WLAN.status` + +```python +WLAN.status('param') +``` + +Query the status of the WLAN interface. + +**Parameter:** + +- `stations_list` - Only for `AP` or `AP_STA` mode, retrieves a list of all stations currently connected to the AP. +- `ap_list` - Only for `STA` or `AP_STA` mode, retrieves information about the currently connected AP. + + - `rf` - Retrieves the RF status, see [Status Codes](#Status-Codes). +- `softap_if` - Retrieves the current state of the `softap` interface, see [Status Codes](#Status-Codes). +- `station_if` - Retrieves the current state of the `station` interface, see [Status Codes](#Status-Codes). +- `netcfg` - Retrieves the current network configuration status, see [Status Codes](#Status-Codes). + +**Return Value:** + +- `stations_list` - Returns a list of all stations currently connected to the AP, `list` type, format: `[(aid, ip, mac), ...]`. +- `ap_list` - Only for `STA` or `AP_STA` mode, retrieves information about the currently connected AP, `list` type, format: `[ssid, password, mac, rssi, channel, auth, cipher]`. + + - `auth` - Authentication method, `int` type. + + - `AUTH_OPEN` : `0` - Open system authentication. + - `AUTH_WEP` : `1` - Wired Equivalent Privacy (WEP) authentication. + - `AUTH_WPA_PSK` : `2` - WPA Pre-Shared Key (PSK) authentication. + - `AUTH_WPA2_PSK` : `3` - WPA2 Pre-Shared Key (PSK) authentication. + - `AUTH_WPA_WPA2_PSK` : `4` - Mixed mode, a combination of WPA and WPA2 PSK authentication. + - `cipher` - Encryption method, `int` type. + + - `CIPHER_NONE` : `0` - No encryption. + - `CIPHER_WEP40` : `1` - WEP with 40-bit encryption. + - `CIPHER_WEP104` : `2` - WEP with 104-bit encryption. + - `CIPHER_TKIP` : `3` - TKIP encryption. + - `CIPHER_CCMP` : `4` - CCMP encryption. +- `rf` - Retrieves the RF status, `int` type, see [Status Codes](#Status-Codes). +- `softap_if` - Retrieves the current state of the `softap` interface, `int` type, see [Status Codes](#Status-Codes). +- `station_if` - Retrieves the current state of the `station` interface, `int` type, see [Status Codes](#Status-Codes). +- `netcfg` - Retrieves the current network configuration status, `int` type, see [Status Codes](#Status-Codes). + +If the execution of this interface fails, it will return an error code: + +- `ERR_NO_AP_IF` : `2020` - Unable to perform operations related to the softap interface as the current mode is not `AP` or `AP_STA`. +- `ERR_AP_UNSTART` : `2019` - Softap is not started, unable to query the stations list. +- `ERR_NO_STA_IF` : `2017` - Unable to perform operations related to the station interface as the current mode is not `STA` or `AP_STA`. +- `ERR_UNCONNECTED_AP` : `2018` - Not connected to an AP, unable to query AP information. +- `ERR_PARAM_INVALID` : `2002` - Parameter error. +- `ERR_INTERNAL` : `2006` - Internal error, underlying interface operation failed. + +**Example:** + +```python +# Get information about the currently connected AP in STA mode +>>> nic.status("ap_list") +['Tenda_996', '12345678', '50:2b:73:08:55:d1', -38, 11, 3, 4] +``` + +### `WLAN.scan` + +```python +WLAN.scan([ssid, bssid, channel, passive, max_item, scan_time]) +``` + +Wireless network scanning. + +**Parameter:** + +- `ssid` - Specify the ssid to scan, `str` type, default is not configured, meaning scan all reachable APs in the current area. +- `bssid` - Specify the bssid to scan, `str` type, default is not configured, meaning scan all reachable APs in the current area. +- `channel` - Specify the channel to scan, `int` type, default is not configured, meaning scan all channels. +- `passive` - Whether it is a passive scan, `bool` type, `True` for passive scan, default is `False`. +- `max_item` - Specify the maximum number of APs to scan, `int` type, default is `128`. +- `scan_time` - Scan time for each channel, unit: ms, `int` type, default is not configured. + +**Return Value:** + +In blocking mode, returns the information of the scanned access points, `list` type, `[(ssid, bssid, channel, rssi, auth, hidden), ...]` + +| Parameter | Type | Description | +| ----------- | -------- | ---------------------------------- | +| `ssid` | `str` | Access point name | +| `bssid` | `str` | Access point MAC | +| `channel` | `int` | Access point channel | +| `rssi` | `int` | Access point signal strength | +| `auth` | `int` | Access point authentication method | +| `hidden` | `bool` | Access point hidden status | + +For non-blocking mode, please use it with event callbacks to receive the scan results in the callback. + +If scanning fails, it returns the corresponding error code, `int` type. + +- `ERR_OK` : `2000` - No error. +- `ERR_WOULDBLOCK` : `2015` - `2015` - In non-blocking mode, when the conditions for hotspot scanning are met, the interface returns `ERR_WOULDBLOCK` and performs asynchronous hotspot scanning. +- `ERR_NO_STA_IF` : `2017` - Unable to use this method as the current mode is not `STA` or `AP_STA`. +- `ERR_PARAM_INVALID` : `2002` - Parameter error. +- `ERR_INTERNAL` : `2006` - Internal error, underlying interface operation failed. + +**Example:** + +```python +# Scan for AP with ssid 'Tenda_996' in STA mode +>>> nic.scan(ssid="Tenda_996") +[('Tenda_996', '50:2b:73:08:55:d1', 11, -42, 3, False)] +``` + +### `WLAN.ifconfig` + +```python +WLAN.ifconfig([interface, config]) +``` + +Configure or query network information. + +**Parameter:** + +- `interface` - Must specify the interface to configure/query in AP_STA mode, `int` type. + + - `SOFTAP_IF` : `0` - SoftAP interface. + - `STATION_IF` : `1` - Station interface. +- `config` - IP configuration, `tuple` type, format: `(ip, netmask, gateway, primary_dns, secondary_dns)`. + + | Parameter | Type | Description | + | ----------------- | ------- | ---------------------------- | + | `ip` | `str` | IP address | + | `netmask` | `str` | Subnet mask | + | `gateway` | `str` | Gateway | + | `primary_dns` | `str` | DNS server primary address | + | `secondary_dns` | `str` | DNS server secondary address | + +**Return Value:** + +For parameter query, returns the corresponding query result. + +For parameter configuration, returns the corresponding error code, `int` type. + +- `ERR_OK` : `2000` - No error. +- `ERR_NO_AP_IF` : `2020` - Unable to query softAP interface parameters as the current mode is not `AP` or `AP_STA`. +- `ERR_NO_STA_IF` : `2017` - Unable to query station interface parameters as the current mode is not `STA` or `AP_STA`. +- `ERR_PARAM_INVALID` : `2002` - Parameter error. +- `ERR_INTERNAL` : `2006` - Internal error, underlying interface operation failed. + +**Example:** + +Query the IP information of the station interface: + +```python +nic.ifconfig(interface=nic.STATION_IF) +``` + +Set the IP information of the station interface: + +```python +nic.ifconfig(interface=nic.STATION_IF, config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8', '114.114.114.114')) +``` + +### `WLAN.netcfg` + +```python +WLAN.netcfg(enable=True, type=nic.NETCFG_SMARTCONFIG, timeout=120) +``` + +Enable or disable network configuration. + +**Parameter:** + +- `enable` - Enable/disable network configuration, `bool` type, `True` to enable, default is `True`. +- `type` - Network configuration method, `int` type. + + - `NETCFG_SMARTCONFIG` : `0` - SmartConfig, as this configuration mode requires enabling promiscuous mode, it will turn off the already enabled AP and STA. + - `NETCFG_WEBCONFIG` : `1` - Web configuration, this configuration mode depends on AP, so please enable softAP first to use this configuration mode for network configuration. After successful activation, please access this address in the browser: http://`IP`:8080/setting, enter the ssid and password to complete the network configuration. Here, `IP` is the IP of the softAP opened by the module, which can be queried through `nic.ifconfig(interface=nic.SOFTAP_IF)`. + - `NETCFG_BLECONFIG` : `2` - BLE configuration. +- `timeout` - Configuration timeout, `int` type, unit: s, default is 120s. + +**Return Value:** + +Returns an error code, `int` type. + +- `ERR_OK` : `2000` - No error. +- `ERR_WOULDBLOCK` : `2015` - In non-blocking mode, after meeting the conditions for network configuration, the interface returns `ERR_WOULDBLOCK` and performs an asynchronous network configuration process. +- `ERR_NETCFG_BUSY` : `2024` - Repeatedly enabling network configuration. +- `ERR_AP_UNSTART` : `2019` - AP must be enabled before using web configuration, and web configuration logic depends on this AP. +- `ERR_TIMEOUT` : `2023` - Execution timeout. +- `ERR_PARAM_INVALID` : `2002` - Parameter error. +- `ERR_INTERNAL` : `2006` - Internal error, underlying interface operation failed. +- `ERR_NOT_SUPPORT` : `2004` - Unsupported operation. + +**Example:** + +```python +# Enable AP mode and start web configuration +>>> import network +>>> nic=network.WLAN(network.AP_MODE) +>>> nic.active(True) +2000 +>>> def fun(event): +... print(event) +>>> nic.config(block=False, event_callback=fun) +2000 +>>> nic.netcfg(enable=True, type=nic.NETCFG_WEBCONFIG, timeout=120) +2015 +{'msg': None, 'type': 3400, 'id': 3401} +``` + +```python +# Disable web configuration +>>> nic.netcfg(enable=False) +2000 +{'msg': None, 'type': 3400, 'id': 3403} +``` + +## Constants + +### Modes + +| Mode | Value | Description | +| ----------- | ----- | -------------- | +| NONE_MODE | 0 | IDLE Mode | +| AP_MODE | 1 | Access Point Mode | +| STA_MODE | 2 | Station Mode | +| AP_STA_MODE | 3 | Access Point and Station Mode | + +### Interfaces + +| Interface | Value | Description | +| ---------- | ----- | ----------------- | +| SOFTAP_IF | 0 | SoftAP interface | +| STATION_IF | 1 | Station interface | + +### Authentication Modes + +| Authentication Mode | Value | Description | +| ------------------- | ----- | ----------------------------------------------- | +| AUTH_OPEN | 0 | Open system authentication | +| AUTH_WEP | 1 | Wired Equivalent Privacy (WEP) authentication | +| AUTH_WPA_PSK | 2 | WPA pre-shared key (PSK) authentication | +| AUTH_WPA2_PSK | 3 | WPA2 pre-shared key (PSK) authentication | +| AUTH_WPA_WPA2_PSK | 4 | Mixed mode with WPA and WPA2 PSK authentication | +| AUTH_WPA3_PSK | 5 | WPA3 pre-shared key (PSK) authentication | +| AUTH_WPA2_WPA3_PSK | 6 | Mixed mode with WPA2 and WPA3 PSK authentication | + +### Encryption Modes + +| Encryption Mode | Value | Description | +| --------------- | ----- | ----------------- | +| CIPHER_NONE | 0 | No encryption | +| CIPHER_WEP40 | 1 | WEP40 encryption | +| CIPHER_WEP104 | 2 | WEP104 encryption | +| CIPHER_TKIP | 3 | TKIP encryption | +| CIPHER_CCMP | 4 | CCMP encryption | + +### Configuration Modes + +| Configuration Mode | Value | Description | +| ------------------ | ----- | ----------------- | +| NETCFG_SMARTCONFIG | 0 | SmartConfig | +| NETCFG_WEBCONFIG | 1 | Web configuration | +| NETCFG_BLECONFIG | 2 | BLE configuration | + +### Error Codes + +| Error Code | Value | Description | +| ----------------------------- | ----- | ------------------------------------------------------- | +| ERR_OK | 2000 | No error | +| ERR_NO_MEM | 2001 | Memory allocation failed | +| ERR_PARAM_INVALID | 2002 | Invalid parameter | +| ERR_WIFI_BUSY | 2003 | Wi-Fi card busy | +| ERR_NOT_SUPPORT | 2004 | Unsupported function or operation | +| ERR_WIFI_ALREADY_CUR_IF | 2005 | The mode is already enabled | +| ERR_INTERNAL | 2006 | Internal exception | +| ERR_WOULDCONNECT | 2007 | Connect to AP needs to be called | +| ERR_NO_AP_FOUND | 2008 | Hotspot not found | +| ERR_PWD_WRONG | 2009 | Incorrect password | +| ERR_AUTHMODE_WRONG | 2010 | Authentication error | +| ERR_CHANNEL_INVALID | 2011 | Invalid channel | +| ERR_NONAUTH | 2012 | WPA received class-2 frame from unauthenticated station | +| ERR_NONASSOC | 2013 | WPA received class-3 frame from unauthenticated station | +| ERR_HANDSHAKE_TIMEOUT | 2014 | Handshake timeout | +| ERR_WOULDBLOCK | 2015 | Currently in non-blocking mode | +| ERR_NOT_ACTIVE | 2016 | Not in active state | +| ERR_NO_STA_IF | 2017 | Not in STA mode | +| ERR_UNCONNECTED_AP | 2018 | Not connected to AP | +| ERR_AP_UNSTART | 2019 | SoftAP interface not started | +| ERR_NO_AP_IF | 2020 | Not in AP mode | +| ERR_NO_SCAN_MODE | 2021 | Not in scan mode | +| ERR_NO_AP_STA_IF | 2022 | Not in STA or AP mode | +| ERR_TIMEOUT | 2023 | Timeout | +| ERR_NETCFG_BUSY | 2024 | Repeatedly enabling network configuration | +| ERR_NETCFG_SOFTAP_START | 2025 | AP start failed | +| ERR_NETCFG_SOCKET_CREATE | 2026 | Socket creation failed | +| ERR_NETCFG_HTTP_SERVER_CREATE | 2027 | HTTP server start failed | +| ERR_NETCFG_BLE_SERVER_CREATE | 2028 | BLE start failed | +| ERR_NETCFG_GATT_SERVER_CREATE | 2029 | GATT server start failed | +| ERR_NETCFG_NOT_IN_NETCFG | 2030 | Not in network configuration mode | +| ERR_NETCFG_HTTP_SERVER_CLOSE | 2031 | Web configuration HTTP close failed | +| ERR_NETCFG_SOCKET_CLOSE | 2032 | Web configuration SOCKET close failed | +| ERR_NETCFG_SOFTAP_CLOSE | 2033 | Web configuration AP close failed | +| ERR_NETCFG_BLE_SERVER_CLOSE | 2034 | BLE configuration server close failed | +| ERR_STA_KICKED_OFFLINE_BY_AP | 2035 | Kicked offline by AP | +| ERR_SER_DISCONNECT | 2036 | User-initiated disconnection | +| ERR_AUTHMODE_CHANGED | 2037 | Connection strategy changed | +| ERR_IFMODE_CHANGED | 2038 | Mode changed | +| ERR_DHCP_LEASE_EXPIRED | 2039 | DHCP lease expired | +| ERR_INACTIVE_TIMEOUT | 2040 | No interaction within the specified timeout | +| ERR_IP_DEL_ARTIFICIALLY | 2041 | IP address deleted artificially | + +### Event Codes + +| Event Type | Event Name | Event ID | Event Description | Message Passed to User in Event Callback | +| ---------- | -------------------------------- | -------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 3000 | EVENT_RF_WAKEUP | 3001 | RF Wakeup | None | +| 3000 | EVENT_RF_SLEEP | 3002 | RF Sleep | None | +| 3100 | EVENT_SCAN_DONE | 3101 | Scan Done | Returns scan results,`list` type, format: `[(ssid, bssid, channel, rssi, auth, hidden),...]` | +| 3200 | EVENT_AP_START_SUCCEED | 3201 | AP Creation Successful | None | +| 3200 | EVENT_AP_START_FAILED | 3202 | AP Creation Failed | None | +| 3200 | EVENT_STA_CONNECTED | 3203 | Connected to Station | Returns information about the Station,`dict` type. `
aid`: ID assigned by AP to Station. `
mac`: Station's MAC address. | +| 3200 | EVENT_STA_DISCONNECTED | 3204 | Disconnected from Station | Returns information about the Station,`dict` type. `
aid`: ID assigned by AP to Station. `
ip`: Station's IP address. `
mac`: Station's MAC address. | +| 3200 | EVENT_STA_IP_ASSIGNED | 3205 | IP Assigned to Station | Returns information about the Station,`dict` type. `
aid`: ID assigned by AP to Station. `
ip`: Station's IP address. `
mac`: Station's MAC address. | +| 3200 | EVENT_AP_STOP | 3206 | AP Mode Stop | None | +| 3300 | EVENT_STA_START_CONN | 3301 | Start Connecting to AP | None | +| 3300 | EVENT_CONN_SUCCEED | 3302 | Connection to AP Successful | Returns information about the connected AP,`dict` type. `
ssid`: Wireless access point name, `str` type.`
password`: Wireless access point password, `str` type. `
bssid`: Wireless access point MAC address, `str` type. `
channel`: Current channel, `int` type. `
rssi`: Signal strength of the wireless access point, `int` type. `
auth`: Authentication mode, `int` type. `
cipher`: Encryption mode, `int` type. | +| 3300 | EVENT_CONN_FAILED | 3303 | Connection to AP Failed | None | +| 3300 | EVENT_CONN_LOST | 3304 | Connection to AP Lost | Returns information about the disconnected AP,`dict` type. `
ssid`: Wireless access point name, `str` type.`
bssid`: Wireless access point MAC address, `str` type.`
reason`: Disconnection reason, `int` type(0 or 1:normal,other:error). | +| 3300 | EVENT_GOT_IP | 3305 | IP Obtained | Returns obtained IP information,`tuple` type, format: `(ip, netmask, gateway, primary_dns, secondary_dns)` | +| 3300 | EVENT_LOST_IP | 3306 | IP Lost | None | +| 3400 | EVENT_NETCFG_START_SUCCEED | 3401 | Network Configuration Start Successful | None | +| 3400 | EVENT_NETCFG_START_FAILED | 3402 | Network Configuration Start Failed | None | +| 3400 | EVENT_NETCFG_STOP_SUCCEED | 3403 | Network Configuration Stop Successful | None | +| 3400 | EVENT_NETCFG_STOP_FAILED | 3404 | Network Configuration Stop Failed | None | +| 3400 | EVENT_NETCFG_STAT_CLIENT_CONNECT | 3405 | Network Configuration Client Connected | None | +| 3400 | EVENT_NETCFG_GOT_KEY | 3406 | Network Configuration Got Account Password | Returns the obtained account and password,`tuple` type, format: `(ssid, password)` | +| 3400 | EVENT_NETCFG_TIMEOUT | 3407 | Network Configuration Timeout | None | + +### Status Codes + +| Status Code | Value | Description | +| ----------------------- | ----- | -------------------------------------- | +| STATUS_RF_NOT_ACTIVATED | 1000 | RF not activated | +| STATUS_RF_ACTIVATED | 1001 | RF activated | +| STATUS_RF_SLEEP | 1002 | RF in sleep mode | +| STATUS_RF_WAKEUP | 1003 | RF wake up | +| STATUS_AP_IDLE | 1004 | SoftAP interface idle, not started | +| STATUS_AP_START | 1005 | SoftAP interface started | +| STATUS_AP_STACONNECTED | 1006 | Devices connected to SoftAP | +| STATUS_STA_IDLE | 1007 | Station interface idle, not started | +| STATUS_STA_SCANNING | 1008 | Scanning for APs | +| STATUS_STA_CONNECTING | 1009 | Connecting to AP | +| STATUS_STA_CONNECTED | 1010 | Connected to AP | +| STATUS_STA_GOT_IP | 1011 | Obtained IP | +| STATUS_STA_LOST_IP | 1012 | Lost IP | +| STATUS_NETCFG_NOT_INTO | 1013 | Network configuration mode not started | +| STATUS_NETCFG_INTO | 1014 | Entered network configuration mode | +| STATUS_NETCFG_GOT_KEY | 1015 | Obtained SSID and Password | diff --git a/docs/API_reference/zh/Note.md b/docs/API_reference/zh/Note.md new file mode 100644 index 0000000000000000000000000000000000000000..168f336cd30357a6724ddcc7ac0258ae63590d8c --- /dev/null +++ b/docs/API_reference/zh/Note.md @@ -0,0 +1,69 @@ +# QuecPython API 参考手册编写注意事项 + +## 编写规范 + +参考[Quectel_QuecPython_WiKi编写规范.pdf](https://knowledge.quectel.com/download/attachments/151561997/%5BInternal%5DQuectel_QuecPython_WiKi%E7%BC%96%E5%86%99%E8%A7%84%E8%8C%83_V1.0.0_Preliminary_20230112.pdf?api=v2)。 + +## 目录结构 + +API 参考手册根目录下存在一个名为`README.md`的文件,该文件用来描述 QuecPython 的简介和 API 三个板块的的入口链接。 + +> 文档中心使用的[teedoc](https://gitee.com/teedoc)架构要求每个版块的首页文件都要是名为`README.md`的文件。 + +参照原官网的三个主要板块,将 API 参考手册的目录结构整体划分为 [QuecPython 标准库](https://python.quectel.com/wiki/#/zh-cn/api/pythonStdlib)、[QuecPython类库](https://python.quectel.com/wiki/#/zh-cn/api/QuecPythonClasslib) 和 [QuecPython组件库](https://python.quectel.com/wiki/#/zh-cn/api/QuecPythonThirdlib)。 + +每个目录结构下,均有对应的同名md文件,这些md文件分别对相应的板块做了综合叙述,并列出了板块中包含了哪些模块,点击这些模块名,就可以跳转到对应的模块的md文件中。 + +同时,每个目录下,也包含了一系列名为`.md`的文件,用来描述名为``的模块的API;若模块下包含类,则在该目录下创建名为`..md`。以`machine`模块为例,在`QuecPython类库`目录下应创建`machine.md`文件,其下存在`Pin`等类,需要创建`machime.Pin.md`文件。 + +所有md文件中引用的图片,均存放于media目录中: +- README.md中的图片存放于media根目录。 +- 其余文件中的图片请存放于media下的对应目录中。 +- 图片统一为png格式,命名请见名知意,如`machine.Pin.xxx.png`,其中`xxx`表示用简短英文编写的图片作用描述。 + +目录结构示例如下: + +``` +QuecPython官网文档中心/API手册 +├── README.md +├── QuecPython标准库 +│   ├── README.md +│   ├── gc.md +│   ├── ubinascii.md +│   ├── ucollections.md +│   ├── uos.md +│   └── urandom.md +├── QuecPython类库 +│   ├── README.md +│   ├── atcmd.md +│   ├── cellLocator.md +│   ├── dataCall.md +│   ├── example.md +│   ├── machine.Pin.md +│   ├── machine.md +│   └── wifilocator.md +├── QuecPython组件库 +│   ├── README.md +│   ├── TenCentYun.md +│   ├── aLiYun.md +│   ├── log.md +│   ├── request.md +│   └── umqtt.md +└── media +    ├── QuecPython架构.png +    ├── QuecPython标准库 +    │   └── uos.xxx.png +    ├── QuecPython类库 +    │ ├── machine.xxx.png +    │   └── machine.Pin.xxx.png +    └── QuecPython组件库 +    └── umqtt.xxx.png +``` + +## README.md + +README.md作为板块的首页入口,需要对该板块做综合性描述,并且在最后提供板块的所有二级目录链接。 + +## QuecPython API 参考手册 + +[点此查看](./README.md) diff --git a/docs/API_reference/zh/README.md b/docs/API_reference/zh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f2310ee733a9096de320fe30b3f08ce7775d00e6 --- /dev/null +++ b/docs/API_reference/zh/README.md @@ -0,0 +1,45 @@ +# QuecPython API 参考手册 + +**作者** + +   QuecPython 开发团队 + +**版本** + +   1.12 + +QuecPython 由移远通信 QuecPython 开发团队基于开源项目 microPython 移植而来。其继承了 microPython 基础功能的同时,又扩充了我司通信模组相关的功能,开发者可以很好地使用 QuecPython 进行嵌入式物联网项目的开发。 + +或许你对 QuecPython 还比较陌生,然而一旦你对它有所接触,你就会立即发现它的魅力和它相较于其他嵌入式物联网项目开发方式的种种优越之处。 + +## QuecPython 概述 + +QuecPython 取 "Quectel + microPython" 之意,其兼容 Python3 的语法规范;最小 ROM 占用空间为 150KB,最小 RAM 占用空间为 50KB。 + +得益于 Python 先天的优势,使得 QuecPython 具有`跨平台`、`无需编译`、`动态加载`、`提供丰富且成熟的应用框架`等诸多优势;同时 QuecPython 也提供了诸如`智能电表`、`智能定位器`、`公网对讲机`、`BMS通信云盒`及其它更多的解决方案([点此查看详情](https://python.quectel.com/solutions))。 + +QuecPython 团队也提供了丰富的开发工具,如 QPYcom、VSCode 插件、产测工具等,方便用户进行开发和生产测试。 + +## QuecPython 架构 + +近年来,物联网市场发展迅猛, 嵌入式设备的联网已是大势所趋。传统的嵌入式物联网项目开发仍然采取在基于 C 语言的 RTOS 内核上移植或开发功能组件的方式,此方式开发效率低,平台适配工作量大,对开发者能力要求较高。 + +QuecPython 则在系统中集成了丰富的嵌入式物联网项目常用的各种组件,用户只需要简单的调用 Python 接口即可快速实现功能。系统架构如下图所示: + +![](./media/README/QuecPython架构.png) + +## QuecPython API 参考手册 + +- [Python 标准库](./stdlib/README.md) +- [蜂窝通信](./iotlib/README.md) +- [外设接口](./peripherals/README.md) +- [系统功能](./syslib/README.md) +- [多媒体](./medialib/README.md) +- [Wi-Fi 通信](./wifilib/README.md) +- [蓝牙通信](./btlib/README.md) +- [网络应用](./networklib/README.md) +- [定位应用](./gnsslib/README.md) +- [IoT 平台](./cloudlib/README.md) +- [行业应用](./industry/README.md) +- [开源组件](./componentlib/README.md) +- [错误码](./errcode/README.md) diff --git a/docs/API_reference/zh/ailib/README.md b/docs/API_reference/zh/ailib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..af8bebb661a5531da96566911f12f17a6e529886 --- /dev/null +++ b/docs/API_reference/zh/ailib/README.md @@ -0,0 +1,7 @@ +# QuecPython AI 聊天机器人 + +该部分内容主要介绍 QuecPython 支持的各 AI 聊天机器人功能的接口用法。 + +## QuecPython AI 聊天机器人库列表 + +- [TiktokRTC - 豆包火山 RTC 平台](./TiktokRTC.md) diff --git a/docs/API_reference/zh/ailib/TiktokRTC.md b/docs/API_reference/zh/ailib/TiktokRTC.md new file mode 100644 index 0000000000000000000000000000000000000000..0d009308a3f39e32e8e3473947d0b9c7e81d7d88 --- /dev/null +++ b/docs/API_reference/zh/ailib/TiktokRTC.md @@ -0,0 +1,101 @@ +# TiktokRTC - 火山实时对话式 AI + +火山实时对话式 AI,在实时音视频场景中,若你希望启动智能体提供语音聊天服务,可以通过调用此类实现。 + +> 支持模组型号:EC600M系列、EC800M系列、EG810M系列。 + +## 构造函数 + +### `TiktokRTC` + +```python +class TiktokRTC(time, callback=None) +``` + +初始化 TiktokRTC,并返回 tiktok 火山大模型对话对象。 + +**参数描述:** +- `time` - 房间无对话时,自动退出房间的超时时间。 +- `callback` - 回调函数,用于大模型连接状态改变通知。 + +**callback参数描述:** + +tuple类型,格式(event,msg) + +- `event` - 整性数值。 + - `1` - 大模型启动。 + - `2` - 大模型关闭。 + - `3` - TTS内容,播放声音内容的文本。 + - `4` - ASR内容,返回当前识别文本。 + - `5` - 异常事件,返回异常信息。 +- `msg` - 消息内容。 + + +**示例:** + +```python +import TiktokRTC + +tiktok = TiktokRTC(3000000) +``` + +## 方法 + +### `TiktokRTC.active([is_active])` + +```python +tiktok.active() +``` + +大模型连接激活状态配置/查询。 + +若传参则表示火山大模型连接状态配置,传参True/False开启/关闭火山大模型。 +若不传参则表示查询火山大模型连接状态,返回值True/False表示火山大模型开启/关闭。 + +**可选参数描述:** + +- `is_active` - bool类型,填True时表示启动火山大模型,为False则代表关闭火山大模型。返回0表示成功,返回其他值表示失败。 + + +### `TiktokRTC.config` + +```python +TiktokRTC.config('param') +TiktokRTC.config(param=value) +``` + +火山大模型参数查询/配置。 + +当只传参关键字时,接口查询,每次只能查询一个值。 +当传参赋值时,接口设置,返回True/False表示成功/失败,可以同时设置多个值。 + +**可选参数描述:** + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `StartVoiceChat` | `str` | 启动智能体url | +| `UpdateVoiceChat`| `str` | 更新智能体url | +| `StopVoiceChat` | `str` | 关闭智能体url | +| `BotId` | `str` | 智能体 ID | +| `VoiceId` | `str` | 音色编号。当前仅支持系统音色。| +| `volume` | `int` | 音量大小,0-11 默认 5。 | + +**示例:** +配置信息查询: +```python +# 查询音量大小 +TiktokRTC.config('volume') +``` +配置信息设置: +```python +# 配置音量大小 +TiktokRTC.config(volume=6) +``` + +### `TiktokRTC.interrupt()` + +```python +tiktok.interrupt() +``` + +打断智能体,语音过程中打断智能体讲话。 diff --git a/docs/API_reference/zh/btlib/README.md b/docs/API_reference/zh/btlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..de837426d81a2b623cfe699197f408ca59f2482c --- /dev/null +++ b/docs/API_reference/zh/btlib/README.md @@ -0,0 +1,10 @@ +# QuecPython 蓝牙通信 + +> QuecPython 蓝牙通信库包括低功耗蓝牙相关功能模块和经典蓝牙相关功能模块 + +本文描述了 QuecPython 蓝牙通信相关库中的模块。 + +## QuecPython 蓝牙通信库列表 + +- [ble - 低功耗蓝牙相关功能](./ble.md) +- [bt - 经典蓝牙相关功能](./bt.md) diff --git a/docs/API_reference/zh/btlib/ble.md b/docs/API_reference/zh/btlib/ble.md new file mode 100644 index 0000000000000000000000000000000000000000..656a9f261c535d872dd8c96fdce1c845e9a8446d --- /dev/null +++ b/docs/API_reference/zh/btlib/ble.md @@ -0,0 +1,1252 @@ +# ble-低功耗蓝牙相关功能 + +`ble`模块用于提供BLE GATT Server (从机)与 Client (主机)功能,基于BLE 4.2协议。 + +**示例**: + +见github:https://github.com/QuecPython/example_BLE + +> 当前仅EC200U/EC600U/EG915U/EG912U/FCM360W型号支持`ble`功能。 + + + +## 初始化相关功能 + +### `ble.gattStart` + +```python +ble.gattStart() +``` + +开启 BLE GATT 功能。 + +**返回值描述:** + +- 执行成功返回整型0,失败返回整型-1。 + +### `ble.gattStop` + +```python +ble.gattStop() +``` + +关闭 BLE GATT 功能。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.getStatus` + +```python +ble.getStatus() +``` + +获取 BLE 的状态。 + +**返回值描述:** + +0 - BLE处于停止状态。1 - BLE处于开启状态。-1 - 获取状态失败。 + +### `ble.getPublicAddr` + +```python +ble.getPublicAddr() +``` + +获取 BLE 协议栈正在使用的公共地址。该接口需要在BLE已经初始化完成并启动成功后才能调用,比如在回调中收到 event_id 为0的事件之后,即 start 成功后,去调用。 + +**返回值描述:** + +执行成功返回bytearray类型的BLE地址,大小6个byte,失败返回整型-1。 + +**示例**: + +```python +>>> addr = ble.getPublicAddr() +>>> print(addr) +b'\xdb3\xf5\x1ek\xac' +>>> mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) +>>> print('mac = [{}]'.format(mac)) +mac = [ac:6b:1e:f5:33:db] +``` + + + +> 如果有出厂设置默认蓝牙MAC地址,那么该接口获取的MAC地址和默认的蓝牙MAC地址是一致的;如果没有设置,那么该接口获取的地址,将是蓝牙启动后随机生成的静态地址,因此在每次重新上电运行蓝牙功能时都不相同。 + + + +## BLE Server相关功能 + +### `ble.serverInit` + +```python +ble.serverInit(user_cb) +``` + +初始化 BLE Server 并注册回调函数。 + +**参数描述:** + +- `user_cb`-回调函数,类型为function。回调函数参数含义:args[0] 固定表示event_id,args[1]固定 表示状态,0表示成功,非0表示失败。回调函数的参数个数并不是固定2个,而是根据第一个参数args[0]来决定的,下表中列出了不同事件ID对应的参数个数及说明。 + +| event_id | 参数个数 | 参数说明 | +| :------: | :------: | ------------------------------------------------------------ | +| 0 | 2 | args[0] :event_id,表示 BT/BLE start
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 1 | 2 | args[0] :event_id,表示 BT/BLE stop
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 16 | 4 | args[0] :event_id,表示 BLE connect
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :addr,BT/BLE address,bytearray类型数据 | +| 17 | 4 | args[0] :event_id,表示 BLE disconnect
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id,
args[3] :addr,BT/BLE address,bytearray类型数据 | +| 18 | 7 | args[0] :event_id,表示 BLE update connection parameter
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :max_interval,最大的间隔,间隔:1.25ms,取值范围:6-3200,时间范围:7.5ms\ ~ 4s
args[4] :min_interval,最小的间隔,间隔:1.25ms,取值范围:6-3200,时间范围:7.5ms\ ~ 4s
args[5] :latency,从机忽略连接状态事件的时间。需满足:(1+latecy)\*max_interval\*2\*1.25args[6] :timeout,没有交互,超时断开时间,间隔:10ms,取值范围:10-3200ms,时间范围:100ms ~ 32s | +| 20 | 4 | args[0] :event_id,表示 BLE connection mtu
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :handle
args[3] :mtu值 | +| 21 | 7 | args[0] :event_id,表示 client写入特征值或描述符通知
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,获取数据的长度
args[3] :data,一个数组,存放获取的数据
args[4] :attr_handle,属性句柄,整型值
args[5] :short_uuid,整型值
args[6] :long_uuid,一个16字节数组,存放长UUID | +| 22 | 7 | args[0] :event_id,表示client读取特征值或描述符通知
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,获取数据的长度
args[3] :data,一个数组,存放获取的数据
args[4] :attr_handle,属性句柄,整型值
args[5] :short_uuid,整型值
args[6] :long_uuid,一个16字节数组,存放长UUID | +| 25 | 2 | args[0] :event_id,表示 server发送通知并接收到了发送结束通知
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 63 | 2 | args[0] :event_id,表示SMP配对流程完成通知
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 64 | 5 | args[0] :event_id,表示SMP配对用户确认通知
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :pair_mode,配对模式,整型值。
0 - 配对失败
1 - Legacy Pairing:使用Just Works,不需要输入PIN码
2 - Legacy Pairing:使用Passkey Entry,显示PIN码,不需要输入PIN码
3 - Legacy Pairing:使用Passkey Entry,需要输入PIN码
4 - Legacy Pairing:使用OOB,目前不支持这种方式
5 - Secure Connections Pairing:使用Just Works,不需要输入PIN码
6 - Secure Connections Pairing:使用Numeric Comparison,显示PIN码,不需要输入PIN码
7 - Secure Connections Pairing:使用Passkey Entry,显示PIN码,不需要输入PIN码
8 - Secure Connections Pairing:使用Passkey Entry,需要输入PIN码
9 - Secure Connections Pairing:使用OOB,目前不支持这种方式
args[4] :pin_code,PIN码,整型值 | + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_callback(args): + event_id = args[0] + status = args[1] + print('[ble_callback]: event_id={}, status={}'.format(event_id, status)) + + if event_id == 0: # ble start + if status == 0: + print('[callback] BLE start success.') + else: + print('[callback] BLE start failed.') + elif event_id == 1: # ble stop + if status == 0: + print('[callback] ble stop successful.') + else: + print('[callback] ble stop failed.') + elif event_id == 16: # ble connect + if status == 0: + print('[callback] ble connect successful.') + connect_id = args[2] + addr = args[3] # 这是一个bytearray类型 + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + else: + print('[callback] ble connect failed.') + elif event_id == 17: # ble disconnect + if status == 0: + print('[callback] ble disconnect successful.') + connect_id = args[2] + addr = args[3] # 这是一个bytearray类型 + addr_str = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) + print('[callback] connect_id = {}, addr = {}'.format(connect_id, addr_str)) + else: + print('[callback] ble disconnect failed.') + ble.gattStop() + return + elif event_id == 18: # ble update connection parameter + if status == 0: + print('[callback] ble update parameter successful.') + connect_id = args[2] + max_interval = args[3] + min_interval = args[4] + latency = args[5] + timeout = args[6] + print('[callback] connect_id={},max_interval={},min_interval={},latency={},timeout={}'.format(connect_id, max_interval, min_interval, latency, timeout)) + else: + print('[callback] ble update parameter failed.') + ble.gattStop() + return + elif event_id == 20: # ble connection mtu + if status == 0: + print('[callback] ble connect mtu successful.') + handle = args[2] + ble_mtu = args[3] + print('[callback] handle = {:#06x}, ble_mtu = {}'.format(handle, ble_mtu)) + else: + print('[callback] ble connect mtu failed.') + ble.gattStop() + return + elif event_id == 21: # server:when ble client write characteristic value or descriptor,server get the notice + if status == 0: + print('[callback] ble recv successful.') + data_len = args[2] + data = args[3] # 这是一个bytearray类型 + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # 这是一个bytearray类型 + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv failed.') + ble.gattStop() + return + elif event_id == 22: # server:when ble client read characteristic value or descriptor,server get the notice + if status == 0: + print('[callback] ble recv read successful.') + data_len = args[2] + data = args[3] # 这是一个bytearray类型 + attr_handle = args[4] + short_uuid = args[5] + long_uuid = args[6] # 这是一个bytearray类型 + print('len={}, data:{}'.format(data_len, data)) + print('attr_handle = {:#06x}'.format(attr_handle)) + print('short uuid = {:#06x}'.format(short_uuid)) + print('long uuid = {}'.format(long_uuid)) + else: + print('[callback] ble recv read failed.') + ble.gattStop() + return + elif event_id == 25: # server send notification,and recieve send end notice + if status == 0: + print('[callback] ble send data successful.') + else: + print('[callback] ble send data failed.') + else: + print('unknown event id.') + +ble.serverInit(ble_callback) +``` + +### `ble.serverRelease` + +```python +ble.serverRelease() +``` + +BLE Server 资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.setLocalName` + +```python +ble.setLocalName(code, name) +``` + +设置 BLE 名称。 + +**参数描述:** + +- `code`-编码模式,类型为整型。0 - UTF8,1 - GBK。 +- `name`-编码模式,类型为string。BLE 名称,名称最长不能超过29个字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +>>> ble.setLocalName(0, 'QuecPython-BLE') +0 +``` + + + +> 对于BLE,设备在广播时,如果希望手机扫描app扫描时,能看到广播设备的名称,是需要在广播数据中包含蓝牙名称的,或者在扫描回复数据中包含设备名称。 + + + +### `ble.setAdvParam` + +```python +ble.setAdvParam(min_adv,max_adv,adv_type,addr_type,channel,filter_policy,discov_mode,no_br_edr,enable_adv) +``` + +设置广播参数。 + +**参数描述:** + +- `min_adv`-最小广播间隔,范围0x0020-0x4000。计算方式:时间间隔 = min_adv \* 0.625,单位ms。类型为整型。 +- `max_adv`-最大广播间隔,范围0x0020-0x4000。计算方式:时间间隔 = max_adv \* 0.625,单位ms。类型为整型。 +- `adv_type`-广播类型,0 - 可连接的非定向广播,默认选择,1 - 可连接高占空比的定向广播,2 - 可扫描的非定向广播,3 - 不可连接的非定向广播,4 - 可连接低占空比的定向广播。类型为整型。 +- `addr_type`-本地地址类型,0 - 公共地址,1 - 随机地址。类型为整型。 +- `channel`-广播通道,1 - 37信道,2 - 38信道,4 - 39信道,7 - 上述3个通道都选择,默认该选项。类型为整型。 +- `filter_policy`-广播过滤策略,0 - 处理所有设备的扫描和连接请求,1 - 处理所有设备的连接请求和只处理白名单设备的扫描请求(暂不支持),2 - 处理所有设备的扫描请求和只处理白名单设备的连接请求(暂不支持),3 - 只处理白名单设备的连接和扫描请求(暂不支持)。类型为整型。 +- `discov_mode`-发现模式,GAP协议使用,1 - 有限可发现模式,2 - 一般可发现模式。类型为整型。 +- `no_br_edr`-不用BR/EDR,1-不用BR/EDR,默认为该值,0-使用BR/EDR。类型为整型。 +- `enable_adv`-使能广播,1-使能,默认为该值,0-不使能。类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_set_param(): + min_adv = 0x300 + max_adv = 0x320 + adv_type = 0 # 可连接的非定向广播,默认选择 + addr_type = 0 # 公共地址 + channel = 0x07 + filter_strategy = 0 # 处理所有设备的扫描和连接请求 + discov_mode = 2 + no_br_edr = 1 + enable_adv = 1 + ret = ble.setAdvParam(min_adv, max_adv, adv_type, addr_type, channel, filter_strategy, discov_mode, no_br_edr, enable_adv) + if ret != 0: + print('ble_gatt_set_param failed.') + return -1 + print('ble_gatt_set_param success.') + return 0 +``` + +### `ble.setAdvData` + +```python +ble.setAdvData(data) +``` + +设置广播数据内容。 + +**参数描述:** + +- `data`-广播数据,最长不超过31个字节,类型为bytearray。广播数据的内容,采用 length+type+data 的格式。一条广播数据中可以包含多个这种格式数据的组合,如下示例中包含了两个数据组合,第一个是 "0x02, 0x01, 0x05",0x02表示后面有两个数据,分别是0x01和0x05,0x01即type,0x05表示具体数据;第二个是ble名称数据组合, length为ble名称长度加1、type为0x09,具体数据为name对应的具体编码值。关于type具体值代表的含义,请参考蓝牙协议官方标准文档。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_set_data(): + adv_data = [0x02, 0x01, 0x05] + ble_name = "Quectel_ble" + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvData(data) + if ret != 0: + print('ble_gatt_set_data failed.') + return -1 + print('ble_gatt_set_data success.') + return 0 +``` + +### `ble.setAdvRspData` + +```python +ble.setAdvRspData(data) +``` + +设置扫描回复数据。 + +**参数描述:** + +- `data`-扫描回复数据,最长不超过31个字节,类型为bytearray。 格式和上面设置广播数据内容接口一致。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_set_rsp_data(): + adv_data = [] + ble_name = "Quectel_ble" + length = len(ble_name) + 1 + adv_data.append(length) + adv_data.append(0x09) + name_encode = ble_name.encode('UTF-8') + for i in range(0, len(name_encode)): + adv_data.append(name_encode[i]) + print('set adv_rsp_data:{}'.format(adv_data)) + data = bytearray(adv_data) + ret = ble.setAdvRspData(data) + if ret != 0: + print('ble_gatt_set_rsp_data failed.') + return -1 + print('ble_gatt_set_rsp_data success.') + return 0 +``` + + + +> 当client设备扫描方式为积极扫描时,设置扫描回复数据才有意义。 + + + +### `ble.addService` + +```python +ble.addService(primary, server_id, uuid_type, uuid_s, uuid_l) +``` + +增加一个服务。 + +**参数描述:** + +- `primary`-服务类型,1表示主要服务,其他值表示次要服务,类型为整型。 +- `server_id`-服务ID,用来确定某一个服务,类型为整型。 +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_add_service(): + primary = 1 + server_id = 0x01 + uuid_type = 1 # 短UUID + uuid_s = 0x180F + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addService(primary, server_id, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_service failed.') + return -1 + print('ble_gatt_add_service success.') + return 0 +``` + +### `ble.addChara` + +```python +ble.addChara(server_id, chara_id, chara_prop, uuid_type, uuid_s, uuid_l) +``` + +在服务里增加一个特征。 + +**参数描述:** + +- `server_id`-服务ID,用来确定某一个服务,类型为整型。 +- `chara_id`-特征ID,类型为整型。 +- `chara_prop`-特征的属性,十六进制数,可通过“或运算”同时指定多个属性,值具体含义如下表,类型为整型。 + +| 值 | 含义 | +| ---- | ----------------------------- | +| 0x01 | 广播 | +| 0x02 | 可读 | +| 0x04 | 0x04 - 可写且不需要链路层应答 | +| 0x08 | 可写 | +| 0x10 | 通知 | +| 0x20 | 指示 | +| 0x40 | 认证签名写 | +| 0x80 | 扩展属性 | + +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_add_characteristic(): + server_id = 0x01 + chara_id = 0x01 + chara_prop = 0x02 | 0x10 | 0x20 # 0x02-可读 0x10-通知 0x20-指示 + uuid_type = 1 # 短UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ret = ble.addChara(server_id, chara_id, chara_prop, uuid_type, uuid_s, uuid_l) + if ret != 0: + print('ble_gatt_add_characteristic failed.') + return -1 + print('ble_gatt_add_characteristic success.') + return 0 +``` + +### `ble.addCharaValue` + +```python +ble.addCharaValue(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) +``` + +在特征里增加一个特征值。 + +**参数描述:** + +- `server_id`-服务ID,用来确定某一个服务,类型为整型。 +- `chara_id`-特征ID,类型为整型。 +- `permission`-特征值的权限,2个字节,十六进制数,可通过“或运算”同时指定多个属性,值具体含义如下表,类型为整型。 + +| 值 | 含义 | +| ------ | -------------- | +| 0x0001 | 可读权限 | +| 0x0002 | 可写权限 | +| 0x0004 | 读需要认证 | +| 0x0008 | 读需要授权 | +| 0x0010 | 读需要加密 | +| 0x0020 | 读需要授权认证 | +| 0x0040 | 写需要认证 | +| 0x0080 | 写需要授权 | +| 0x0100 | 写需要加密 | +| 0x0200 | 写需要授权认证 | + +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 +- `value`-特征值数据。类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_add_characteristic_value(): + data = [] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # 短UUID + uuid_s = 0x2A19 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + for i in range(0, 244): + data.append(0x00) + value = bytearray(data) + ret = ble.addCharaValue(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_value failed.') + return -1 + print('ble_gatt_add_characteristic_value success.') + return 0 +``` + +### `ble.changeCharaValue` + +```python +ble.changeCharaValue(server_id, chara_id, value) +``` + +修改特征值。 + +**参数描述:** + +- `server_id`-服务ID,用来确定某一个服务,类型为整型。 +- `chara_id`-特征ID,类型为整型。 + +- `value`-特征值数据。类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.addCharaDesc` + +```python +ble.addCharaDesc(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) +``` + +在特征里增加一个特征描述,注意特征描述和特征值同属与一个特征。 + +**参数描述:** + +- `server_id`-服务ID,用来确定某一个服务,类型为整型。 +- `chara_id`-特征ID,类型为整型。 +- `permission`-特征值的权限,2个字节,十六进制数,可通过“或运算”同时指定多个属性,值具体含义如下表,类型为整型。 + +| 值 | 含义 | +| ------ | -------------- | +| 0x0001 | 可读权限 | +| 0x0002 | 可写权限 | +| 0x0004 | 读需要认证 | +| 0x0008 | 读需要授权 | +| 0x0010 | 读需要加密 | +| 0x0020 | 读需要授权认证 | +| 0x0040 | 写需要认证 | +| 0x0080 | 写需要授权 | +| 0x0100 | 写需要加密 | +| 0x0200 | 写需要授权认证 | + +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 +- `value`-特征描述数据。类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def ble_gatt_add_characteristic_desc(): + data = [0x00, 0x00] + server_id = 0x01 + chara_id = 0x01 + permission = 0x0001 | 0x0002 + uuid_type = 1 # 短UUID + uuid_s = 0x2902 + uuid_l = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + value = bytearray(data) + ret = ble.addCharaDesc(server_id, chara_id, permission, uuid_type, uuid_s, uuid_l, value) + if ret != 0: + print('ble_gatt_add_characteristic_desc failed.') + return -1 + print('ble_gatt_add_characteristic_desc success.') + return 0 +``` + +### `ble.addOrClearService` + +```python +ble.addOrClearService(option, mode) +``` + +增加已添加的所有服务信息到模块,或者删除模块中已增加的所有服务信息。 + +**参数描述:** + +- `option`-操作类型,类型为整型。0 - 删除服务,1 - 增加服务。 +- `mode`-是否保留系统默认服务,类型为整型。 0 - 删除系统默认的GAP和GATT服务,1 - 保留系统默认的GAP和GATT服务。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.sendNotification` + +```python +ble.sendNotification(connect_id, attr_handle, value) +``` + +发送通知。 + +**参数描述:** + +- `connect_id`-连接ID,类型为整型。 +- `attr_handle`-属性句柄,类型为整型。 +- `value`-要发送的数据,发送数据长度不要超过MTU,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.sendIndication` + +```python +ble.sendIndication(connect_id, attr_handle, value) +``` + +发送指示。 + +**参数描述:** + +- `connect_id`-连接ID,类型为整型。 +- `attr_handle`-属性句柄,类型为整型。 +- `value`-要发送的数据,发送数据长度不要超过MTU,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.advStart` + +```python +ble.advStart() +``` + +开启广播。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.advStop` + +```python +ble.advStop() +``` + +停止广播。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +## BLE Client相关功能 + +### `ble.clientInit` + +```python +ble.clientInit(user_cb) +``` + +初始化 BLE Client 并注册回调函数。 + +**参数描述:** + +- `user_cb`-回调函数,类型为function。回调函数参数含义:args[0] 固定表示event_id,args[1] 固定表示状态,0表示成功,非0表示失败。回调函数的参数个数并不是固定2个,而是根据第一个参数args[0]来决定的,下表中列出了不同事件ID对应的参数个数及说明。 + +| event_id | 参数个数 | 参数说明 | +| :------: | :------: | ------------------------------------------------------------ | +| 0 | 2 | args[0] :event_id,表示 BT/BLE start
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 1 | 2 | args[0] :event_id,表示 BT/BLE stop
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 16 | 4 | args[0] :event_id,表示 BLE connect
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :addr,BT/BLE address,bytearray类型数据 | +| 17 | 4 | args[0] :event_id,表示 BLE disconnect
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id,
args[3] :addr,BT/BLE address,bytearray类型数据 | +| 18 | 7 | args[0] :event_id,表示 BLE update connection parameter
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :max_interval,最大的间隔,间隔:1.25ms,取值范围:6-3200,时间范围:7.5ms ~ 4s
args[4] :min_interval,最小的间隔,间隔:1.25ms,取值范围:6-3200,时间范围:7.5ms ~ 4s
args[5] :latency,从机忽略连接状态事件的时间。需满足:(1+latecy)\*max_interval\*2\*1.25args[6] :timeout,没有交互,超时断开时间,间隔:10ms,取值范围:10-3200,时间范围:100ms ~ 32s | +| 19 | 9 | args[0] :event_id,表示 BLE scan report
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :event_type
args[3] :扫描到的设备名称
args[4] :设备地址类型
args[5] :设备地址,bytearray类型数据
args[6] :rssi,信号强度
args[7] :data_len,扫描的原始数据长度
args[8] :data,扫描的原始数据 | +| 20 | 4 | args[0] :event_id,表示 BLE connection mtu
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :handle
args[3] :mtu值 | +| 23 | 4 | args[0] :event_id,表示 client接收到通知
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,包含句柄等数据的原始数据,数据格式及解析见最后的综合示例程序 | +| 24 | 4 | args[0] :event_id,表示 client recieve indication,即接收指示
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,包含indication的原始数据,数据格式及解析见最后的综合示例程序 | +| 26 | 2 | args[0] :event_id,表示 开始查找服务
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 27 | 5 | args[0] :event_id,表示查找到服务
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :start_handle,表示service的开始句柄
args[3] :end_handle,表示service的结束句柄
args[4] :UUID,表示service的UUID(短UUID) | +| 28 | 4 | args[0] :event_id,表示查找到服务特征
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,包含句柄、属性、UUID等数据的原始数据,数据格式及解析见最后的综合示例程序 | +| 29 | 4 | args[0] :event_id,表示 查找到特征描述
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,包含句柄、UUID等数据的原始数据,数据格式及解析见最后的综合示例程序 | +| 30 | 2 | args[0] :event_id,表示写入特征值并需要server端确认
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 31 | 2 | args[0] :event_id,表示写入特征值,无需server端确认
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 32 | 4 | args[0] :event_id,表示通过句柄来读取特征值
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,原始数据 | +| 33 | 4 | args[0] :event_id,表示通过UUID来读取特征值
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,原始数据 | +| 34 | 4 | args[0] :event_id,表示读取多个特征值
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,原始数据 | +| 35 | 2 | args[0] :event_id,表示 写入特征描述,需server端确认
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 36 | 4 | args[0] :event_id,表示读特征描述
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :data_len,数据长度
args[3] :data,原始数据 | +| 37 | 3 | args[0] :event_id,表示属性错误
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :errcode,错误码 | +| 63 | 2 | args[0] :event_id,表示SMP配对流程完成通知
args[1] :status,表示操作的状态,0-成功,非0-失败 | +| 64 | 5 | args[0] :event_id,表示SMP配对用户确认通知
args[1] :status,表示操作的状态,0-成功,非0-失败
args[2] :connect_id
args[3] :pair_mode,配对模式,整型值。
0 - 配对失败
1 - Legacy Pairing:使用Just Works,不需要输入PIN码
2 - Legacy Pairing:使用Passkey Entry,显示PIN码,不需要输入PIN码
3 - Legacy Pairing:使用Passkey Entry,需要输入PIN码
4 - Legacy Pairing:使用OOB,目前不支持这种方式
5 - Secure Connections Pairing:使用Just Works,不需要输入PIN码
6 - Secure Connections Pairing:使用Numeric Comparison,显示PIN码,不需要输入PIN码
7 - Secure Connections Pairing:使用Passkey Entry,显示PIN码,不需要输入PIN码
8 - Secure Connections Pairing:使用Passkey Entry,需要输入PIN码
9 - Secure Connections Pairing:使用OOB,目前不支持这种方式
args[4] :pin_code,PIN码,整型值 | + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.clientRelease` + +```python +ble.clientRelease() +``` + +BLE Client 资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.setScanParam` + +```python +ble.setScanParam(scan_mode, interval, scan_window, filter_policy, addr_type) +``` + +设置扫描参数。 + +**参数描述:** + +- `scan_mode`-扫描模式,类型为整型。扫描模式,默认为积极扫描。0 - 消极扫描,1 - 积极扫描。 +- `interval`-扫描间隔,类型为整型。范围0x0004-0x4000,时间间隔 = interval \* 0.625,单位ms。 +- `scan_window`-一次扫描的时间,类型为整型。范围0x0004-0x4000,扫描时间 = scan_window\* 0.625,单位ms。 +- `filter_policy`-扫描过滤策略,类型为整型。默认为0。0 - 过滤目标地址不是本设备的定向广播包,1 - 过滤目标地址不是本设备的定向广播包及白名单之外的广播包,2 -过滤目标地址不是本设备且没使用Resolvable private address的定向广播包,3 - 过滤目标地址不是本设备且没使用Resolvable private address的定向广播包及白名单之外的广播包。 +- `addr_type`-本地地址类型,类型为整型。0 - 公共地址,1 - 随机地址。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + + + +> 扫描时间 `scan_window` 不能大于扫描间隔 `interval` 。如果两者相等,则表示连续不停的扫描。此时 BLE 的 Controller 会连续运行扫描,占满系统资源而导致无法执行其他任务。所以不允许设置连续扫描。并且不建议将时间设置的太短,扫描越频繁则功耗越高。 + + + +### `ble.scanStart` + +```python +ble.scanStart() +``` + +开始扫描。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.scanStop` + +```python +ble.scanStop() +``` + +停止扫描。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.setScanFilter` + +```python +ble.setScanFilter(act) +``` + +打开或者关闭扫描过滤。如果打开,那么扫描设备的广播数据时,同一个设备的广播数据只会上报一次;如果关闭,则同一个设备的所有的广播数据都会上报。 + +**参数描述:** + +- `act`-扫描过滤开关,类型为整型。0 - 关闭扫描过滤功能,1 - 打开扫描过滤功能。默认打开过滤功能。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.connect` + +```python +ble.connect(addr_type, addr) +``` + +根据指定的设备地址去连接设备。 + +**参数描述:** + +- `addr_type`-地址类型,类型为整型。0 - 公共地址,1 - 随机地址。 +- `addr`-BLE地址,类型为bytearray,大小为6字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.cancelConnect` + +```python +ble.cancelConnect(addr) +``` + +取消正在建立的连接。 + +**参数描述:** + +- `addr`-BLE地址,类型为bytearray,大小为6字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.disconnect` + +```python +ble.disconnect(connect_id) +``` + +断开已建立的连接。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.discoverAllService` + +```python +ble.discoverAllService(connect_id) +``` + +扫描所有的服务。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.discoverByUUID` + +```python +ble.discoverByUUID(connect_id, uuid_type, uuid_s, uuid_l) +``` + +扫描指定UUID的服务。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.discoverAllIncludes` + +```python +ble.discoverAllIncludes(connect_id, start_handle, end_handle) +``` + +扫描所有的引用,start_handle和end_handle要属于同一个服务。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `start_handle`-开始句柄,从这个句柄开始寻找引用,类型为整型。 +- `end_handle`-结束句柄,从这个句柄结束寻找引用,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.discoverAllChara` + +```python +ble.discoverAllChara(connect_id, start_handle, end_handle) +``` + +扫描所有的特征,start_handle和end_handle要属于同一个服务。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `start_handle`-开始句柄,从这个句柄开始寻找特征,类型为整型。 +- `end_handle`-结束句柄,从这个句柄结束寻找特征,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.discoverAllCharaDesc` + +```python +ble.discoverAllCharaDesc(connect_id, start_handle, end_handle) +``` + +扫描所有特征的描述,start_handle和end_handle要属于同一个服务。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `start_handle`-开始句柄,从这个句柄开始寻找特征描述,类型为整型。 +- `end_handle`-结束句柄,从这个句柄结束寻找特征描述,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.readCharaByUUID` + +```python +ble.readCharaByUUID(connect_id, start_handle, end_handle, uuid_type, uuid_s, uuid_l) +``` + +读取指定UUID的特征值,start_handle和end_handle必须要包含一个特征值句柄。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `start_handle`-开始句柄,一定要属于同一个服务的句柄,类型为整型。 +- `end_handle`-结束句柄,一定要属于同一个服务的句柄,类型为整型。 +- `uuid_type`-uuid类型,0 - 长UUID,128bit;1 - 短UUID,16bit。类型为整型。 +- `uuid_s`-短UUID,2个字节(16bit),类型为整型,当uuid_type为0时,该值给0。 +- `uuid_l`-长UUID,16个字节(128bit),类型为bytearray,当uuid_type为1时,该值填 bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.readCharaByHandle` + +```python +ble.readCharaByHandle(connect_id, handle, offset, is_long) +``` + +读取指定句柄的特征值。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `handle`-特征值句柄,类型为整型。 +- `offset`-偏移位置,类型为整型。 +- `is_long`-长特征值标志,0-短特征值,一次可以读取完;1-长特征值,分多次读取。类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.readCharaDesc` + +```python +ble.readCharaDesc(connect_id, handle, is_long) +``` + +读取特征描述。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `handle`-特征值句柄,类型为整型。 +- `is_long`-长特征值标志,0-短特征值,一次可以读取完;1-长特征值,分多次读取。类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.writeChara` + +```python +ble.writeChara(connect_id, handle, offset, is_long, data) +``` + +写入特征值,需要对端应答。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `handle`-特征值句柄,类型为整型。 +- `offset`-偏移位置,类型为整型。 +- `is_long`-长特征值标志,0-短特征值,一次可以读取完;1-长特征值,分多次读取。类型为整型。 +- `data`-特征值数据,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.writeCharaNoRsp` + +```python +ble.writeCharaNoRsp(connect_id, handle, data) +``` + +写入特征值,不需要对端应答。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `handle`-特征值句柄,类型为整型。 +- `data`-特征值数据,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.writeCharaDesc` + +```python +ble.writeCharaDesc(connect_id, handle, data) +``` + +写入特征描述。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `handle`-特征描述句柄,类型为整型。 +- `data`-特征描述数据,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.exchangeMtu` + +```python +ble.exchangeMtu(connect_id, mtu_size) +``` + +发送MTU交换请求。MTU交换请求应该由client端发起。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 +- `mtu_size`-MTU大小。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + + + +## BLE SMP相关功能 + +### `ble.smpSetConfig` + +```python +ble.smpSetConfig(io_cap, auth_req, passkey, timeout) +``` + +配对能力配置。 + +**参数描述:** + +* `io_cap`-设备输入输出能力,类型为整型,默认为3。 + +| 值 | 含义 | +| ---- | -------------------------------------------------- | +| 0 | 只有显示能力,可以显示PIN码 | +| 1 | 只有显示能力,只能显示Yes/No,不能显示PIN码 | +| 2 | 只有输入能力,可以输入PIN码 | +| 3 | 没有输入输出能力 | +| 4 | 有输入输出能力,既可以显示PIN码,又可以输入PIN码。 | + +- `auth_req`-认证请求参数,类型为整型,默认为9。 + +| | Bit0 | Bit1 | Bit2 | Bit3 | +| ---- | ------------ | ---------------- | ---------- | ------------------------------ | +| 0 | 配对后不绑定 | 预留,无实际含义 | 不启用MITM | 使用Legacy Pairing | +| 1 | 配对后绑定 | 预留,无实际含义 | 启用MITM | 使用Secure Connections Pairing | + +- `passkey`-配对显示的PIN码,类型为整型,默认为123456。 +- `timeout`-配对超时时间,单位为100ms,类型为整型,默认为160。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**配对方法选择过程:** + +BLE smp配对有`Legacy Pairing`和`Secure Connections Pairing`两种模式,具体有如下4种配对方法: + +* OOB + +* Just Works + +* Passkey Entry + +* Numeric Comparison (只有 Secure Connections Pairing 模式才有) + +具体选择哪一种方法配对,是由配对的双方在交换各自的IO能力后协商决定的,基本分为下面几个阶段: + +阶段1:配对双方会先确认使用`Legacy Pairing`还是`Secure Connections Pairing`模式来进行配对,原则是:只有双方都设置了`Secure Connections Pairing`标志,才会使用这种配对模式,否则使用`Legacy Pairing`。 + +阶段2:判断是否支持OOB。对于`Legacy Pairing`模式,只有双方均支持OOB,才会使用OOB方式。对于`Secure Connections Pairing`模式,如果`Initiator`支持OOB,则使用OOB方式。 + +阶段3:检查MITM(中间人)。如果配对双方都没有配置MITM标志,则直接使用`Just Works`方法来配对,否则按照双方的IO能力来选择配对方法。 + +阶段4:根据双方的IO能力来选择配对方法。 + +关于阶段2 ~ 阶段4的具体说明可以参考蓝牙官方手册文档《BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part H]》的 ***2.3.5.1 Selecting Key Generation Method*** 章节的内容。 + +### `ble.smpGetConfig` + +```python +ble.smpGetConfig(io_cap, auth_req, passkey, timeout) +``` + +配对能力查询。 + +**返回值描述:** + +执行成功返回值如下,失败返回整型-1。 + +* `io_cap`-设备输入输出能力,类型为整型,默认为3。 + +| 值 | 含义 | +| ---- | ------------------------------------------------ | +| 0 | 只有显示能力,可以显示PIN码 | +| 1 | 只有显示能力,只能显示Yes/No,不能显示PIN码 | +| 2 | 只有输入能力,可以输入PIN码 | +| 3 | 没有输入输出能力 | +| 4 | 有输入输出能力,既可以显示PIN码,又可以输入PIN码 | + +- `auth_req`-认证请求参数,类型为整型,默认为9。 + +| | Bit0 | Bit1 | Bit2 | Bit3 | +| ---- | ------------ | ---------------- | ---------- | ------------------------------ | +| 0 | 配对后不绑定 | 预留,无实际含义 | 不启用MITM | 使用Legacy Pairing | +| 1 | 配对后绑定 | 预留,无实际含义 | 启用MITM | 使用Secure Connections Pairing | + +- `passkey`-配对显示的PIN码,类型为整型,默认为123456。 +- `timeout`-配对超时时间,单位为100ms,类型为整型,默认为160。 + +### `ble.smpStartPair` + +```python +ble.smpStartPair(connect_id) +``` + +开始BLE SMP配对流程。SMP配对由client发起,server也可以通过该接口来通知client发起SMP配对请求。 + +**参数描述:** + +- `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.smpUserConfirm` + +```python +ble.smpUserConfirm(connect_id, pair_operation, pin) +``` + +确认配对。收到配对请求后确认是否接受配对。 + +**参数描述:** + +* `connect_id`-连接ID,建立连接时得到的连接ID,类型为整型。 + +* `pair_operation`-配对的操作类型,类型为整型。 + +| 值 | 含义 | +| ---- | ------------------------------------------------------------ | +| 0 | 取消配对,只有在配对过程中,才能执行该操作。取消配对会导致蓝牙连接断开。 | +| 1 | 确认配对,不携带PIN码(用于Just Work或者Numeric Comparison模式) | +| 2 | 确认配对,携带PIN码(用于Passkey模式) | + +- `pin`-PIN码,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.smpGetPairedDevInfo` + +```python +ble.smpGetPairedDevInfo() +``` + +获取已配对设备信息。 + +**返回值描述:** + +执行成功返回值如下,失败返回整型-1。 + +- `addr_list`-已配对设备的BLE地址列表,类型为list,list成员为bytearray类型的BLE地址。 + +### `ble.smpRemovePairedDev` + +```python +ble.smpRemovePairedDev(addr) +``` + +删除指定的已配对设备信息。 + +**参数描述:** + +- `addr`-待删除的设备BLE地址,类型为bytearray,大小为6字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `ble.smpCleanPairedDev` + +```python +ble.smpCleanPairedDev() +``` + +删除所有已配对设备信息。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +> 注意:以上BLE SMP相关接口均需要在BLE已经初始化的情况下执行,否则会返回失败。当前仅EC200UEUAA型号特定固件支持BLE SMP功能。 \ No newline at end of file diff --git a/docs/API_reference/zh/btlib/bt.md b/docs/API_reference/zh/btlib/bt.md new file mode 100644 index 0000000000000000000000000000000000000000..567a45616ee46f7ee02ee57bd986b989e05359bf --- /dev/null +++ b/docs/API_reference/zh/btlib/bt.md @@ -0,0 +1,760 @@ +# bt - 经典蓝牙相关功能 + +`bt`模块提供经典蓝牙的相关功能,支持HFP、A2DP、AVRCP、SPP。 + +**示例**: + +见github:https://github.com/QuecPython/example_BT + +> 当前仅EC200U/EC600U/EG912U/EG915ULA_AB/EG915UEU_AB型号支持`bt`功能。 + + + +## 初始化相关功能 + +### `bt.init` + +```python +bt.init(user_cb) +``` + +蓝牙初始化并注册回调函数。 + +**参数描述:** + +- `user_cb`-回调函数,类型为function。回调函数参数含义:args[0] 固定表示event_id,args[1] 固定表示状态,0表示成功,非0表示失败。回调函数的参数个数并不是固定2个,而是根据第一个参数args[0]来决定的,下表中列出了不同事件ID对应的参数个数及说明。 + +| event_id | 参数个数 | 参数说明 | +| :------: | :------: | ------------------------------------------------------------ | +| 0 | 2 | args[0] :event_id,表示 BT/BLE start 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败 | +| 1 | 2 | args[0] :event_id,表示 BT/BLE stop
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败 | +| 6 | 6 | args[0] :event_id,表示 BT inquiry 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :rssi,搜索到的设备的信号强度;
args[3] :device_class
args[4] :device_name,设备名称,字符串类型
args[5] :addr,搜到的蓝牙设备的mac地址 | +| 7 | 3 | args[0] :event_id,表示 BT inquiry end 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :end_status,0 - 正常结束搜索,8 - 强制结束搜索 | +| 14 | 4 | args[0] :event_id,表示 BT spp recv 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :data_len,收到的数据长度
args[3] :data,收到的数据,bytearray类型数据 | +| 40 | 4 | args[0] :event_id,表示 BT HFP connect 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_connect_status,表示hfp的连接状态;
0 - 已经断开连接
1 - 连接中
2 - 已经连接
3 - 断开连接中
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 41 | 4 | args[0] :event_id,表示 BT HFP disconnect 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_connect_status,表示hfp的连接状态;
0 - 已经断开连接
1 - 连接中
2 - 已经连接
3 - 断开连接中
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 42 | 4 | args[0] :event_id,表示 BT HFP call status 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_call_status,表示hfp的通话状态;
0 - 当前没有正在进行的通话
1 - 当前至少有一个正在进行的通话
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 43 | 4 | args[0] :event_id,表示 BT HFP call setup status 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_call_setup_status,表示hfp的call setup状态;
0 - 表示没有电话需要接通
1 - 表示有一个拨进来的电话还未接通
2 - 表示有一个拨出去的电话还没有接通
3 - 表示拨出电话的蓝牙连接的另一方正在响铃
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 44 | 4 | args[0] :event_id,表示 BT HFP network status 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_network_status,表示AG的网络状态;
0 - 表示网络不可用
1 - 表示网络正常
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 45 | 4 | args[0] :event_id,表示 BT HFP network signal 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_network_signal,表示AG的信号,范围 0~5
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 46 | 4 | args[0] :event_id,表示 BT HFP battery level 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_battery_level,表示AG端的电池电量,范围 0~5
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 47 | 4 | args[0] :event_id,表示 BT HFP call held status 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_call_held_status,表示hfp的call held状态;
0 - 表示没有保持呼叫
1 - 表示呼叫被暂停或活动/保持呼叫交换
2 - 表示呼叫暂停,没有活动呼叫
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 48 | 4 | args[0] :event_id,表示 BT HFP audio status 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_audio_status,表示audio连接状态;
0 - 表示audio已经断开连接
1 - 表示audio正在连接中
2 - 表示audio已经连接成功
3 - 表示audio正在断开连接
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 49 | 4 | args[0] :event_id,表示 BT HFP volume type 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_volume_type
0 - 表示volume type为speaker
1 - 表示volume type为microphone
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 50 | 4 | args[0] :event_id,表示 BT HFP service type 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_service_type,表示当前AG的网络服务模式;
0 - 表示AG当前为正常网络模式
1 - 表示AG当前处于漫游模式
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 51 | 4 | args[0] :event_id,表示 BT HFP ring 事件,即来电时响铃事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :当前无实际意义,保留
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 52 | 4 | args[0] :event_id,表示 BT HFP codec type 事件,即编解码模式
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :hfp_codec_type,表示当前使用哪个编解码模式;
1 - 表示 CVDS,采用8kHz采样率
2 - 表示mSBC,采用16kHz采样率
args[3] :addr,BT 主设备的地址,bytearray类型数据 | +| 61 | 4 | args[0] :event_id,表示 BT SPP connect 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :spp_connect_status,表示spp的连接状态;
0 - 已经断开连接
1 - 连接中
2 - 已经连接
3 - 断开连接中
args[3] :addr,对端设备的mac地址,bytearray类型数据 | +| 62 | 4 | args[0] :event_id,表示 BT SPP disconnect 事件
args[1] :status,表示操作的状态,0 - 成功,非0 - 失败
args[2] :spp_connect_status,表示spp的连接状态;
0 - 已经断开连接
1 - 连接中
2 - 已经连接
3 - 断开连接中
args[3] :addr,对端设备的mac地址,bytearray类型数据 | + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +def bt_callback(args): + event_id = args[0] # 第一个参数固定是 event_id + status = args[1] # 第二个参数固定是状态,表示某个操作的执行结果是成功还是失败 + ...... +``` + +### `bt.release` + +```python +bt.release() +``` + +蓝牙资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.start` + +```python +bt.start() +``` + +开启蓝牙功能。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.stop` + +```python +bt.stop() +``` + +关闭蓝牙功能。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.getStatus` + +```python +bt.getStatus() +``` + +获取蓝牙的状态。 + +**返回值描述:** + +蓝牙状态:类型为整型,0-蓝牙处于停止状态,1-蓝牙正常运行中,-1-获取状态失败。 + +### `bt.getLocalAddr` + +```python +bt.getLocalAddr() +``` + +获取蓝牙地址。 + +**返回值描述:** + +蓝牙地址:执行成功返回类型为bytearray的蓝牙地址,大小6字节,失败返回整型-1。 + +**示例**: + +```python +>>> addr = bt.getLocalAddr() +>>> print(addr) +b'\xc7\xa13\xf8\xbf\x1a' +>>> mac = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]) +>>> print('mac = [{}]'.format(mac)) +mac = [1a:bf:f8:33:a1:c7] +``` + + + +> 该接口需要在蓝牙已经初始化完成并启动成功后才能调用,比如在回调中收到 event_id 为0的事件之后,即 start 成功后,去调用。 + + + +### `bt.setLocalName` + +```python +bt.setLocalName(code, name) +``` + +设置蓝牙名称。 + +**参数描述:** + +- `code`-编码模式,类型为整型,0 - UTF8,1 - GBK。 +- `name`-蓝牙名称,类型为string,最大长度22字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +>>> bt.setLocalName(0, 'QuecPython-BT') +0 +``` + +### `bt.getLocalName` + +```python +bt.getLocalName() +``` + +获取蓝牙名称。 + +**返回值描述:** + +执行成功返回一个元组`(code, name)`,包含编码模式和蓝牙名称,失败返回整型-1。 + +**示例**: + +```python +>>> bt.getLocalName() +(0, 'QuecPython-BT') +``` + +### `bt.setVisibleMode` + +```python +bt.setVisibleMode(mode) +``` + +设置蓝牙可见模式,即做从机被扫描时,是否可被发现以及可被连接。 + +**参数描述:** + +- `mode`-可见模式,类型为整型,具体含义如下表。 + +| 值 | 含义 | +| ---- | ------------------------ | +| 0 | 不可被发现,不可被连接 | +| 1 | 可以被发现,但不可被连接 | +| 2 | 不可被发现,但可被连接 | +| 3 | 可以被发现,可被连接 | + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +>>> bt.setVisibleMode(3) +0 +``` + +### `bt.getVisibleMode` + +```python +bt.getVisibleMode() +``` + +获取蓝牙可见模式。 + +**返回值描述:** + +执行成功返回蓝牙当前的可见模式值,失败返回整型-1。 + +**示例**: + +```python +>>> bt.getVisibleMode() +3 +``` + +### `bt.startInquiry` + +```python +bt.startInquiry(mode) +``` + +开始搜索周边的蓝牙设备。 + +**参数描述:** + +- `mode`-搜索类型。目前固定为15,表示搜索所有类型的设备。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +bt.startInquiry(15) +``` + +### `bt.cancelInquiry` + +```python +bt.cancelInquiry() +``` + +取消搜索操作。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.setChannel` + +```python +bt.setChannel(channel) +``` + +设置音频输出通道,使用场景为蓝牙接听电话或者播放音频时。 + +**参数描述:** + +- `channel`-音频通道,类型为整型。0 - 听筒,1 - 耳机,2 - 喇叭。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.reconnect_set` + +```python +bt.reconnect_set(max_count, period) +``` + +配置尝试重连的最大次数和相邻2次尝试重连的时间间隔,使用场景为模块和蓝牙设备距离拉远后断开连接时。 + +**参数描述:** + +- `max_count`-尝试重连的最大次数,类型为整型,设置0则关闭自动重连功能。 +- `period`-相邻2次尝试重连的时间间隔,单位秒,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +```python +bt.reconnect_set(25, 2)#配置尝试重连的最大次数为25,每次尝试重连的间隔为2秒 +``` + +### `bt.reconnect` + +```python +bt.reconnect() +``` + +模组主动重连上次配对过的设备,如手机。使用场景为模组重启后重新初始化打开蓝牙、或者模组不重启仅关闭蓝牙再重新打开蓝牙。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +**示例**: + +参考A2DP示例程序。见github:https://github.com/QuecPython/example_BT/blob/master/bt_a2dp_avrcp_demo.py + +## HFP协议相关功能 + +提供蓝牙通话相关功能。 + +### `bt.hfpInit` + +```python +bt.hfpInit() +``` + +HFP 功能初始化 。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpRelease` + +```python +bt.hfpRelease() +``` + +HFP 资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpConnect` + +```python +bt.hfpConnect(addr) +``` + +连接AG,建立HFP连接。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpDisonnect` + +```python +bt.hfpDisonnect(addr) +``` + +断开HFP连接。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpSetVolume` + +```python +bt.hfpSetVolume(addr, vol) +``` + +设置蓝牙通话时的音量。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 +- `vol`-通话音量,类型为整型,范围 1-15。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpRejectAfterAnswer` + +```python +bt.hfpRejectAfterAnswer(addr) +``` + +挂断接通的电话。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpRejectCall` + +```python +bt.hfpRejectCall(addr) +``` + +拒接电话。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpAnswerCall` + +```python +bt.hfpAnswerCall(addr) +``` + +接听电话。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpEnableVR` + +```python +bt.hfpEnableVR(addr) +``` + +开启语音助手。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpDisableVR` + +```python +bt.hfpDisableVR(addr) +``` + +关闭语音助手。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.hfpDisableVR` + +```python +bt.hfpDisableVR(addr, cmd) +``` + +三方通话控制。 + +**参数描述:** + +- `addr`-AG端蓝牙地址,6个字节,类型为bytearray。 +- `cmd`-控制命令,类型为整型。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +## A2DP/AVRCP协议相关功能 + +提供蓝牙音乐相关功能。 + +### `bt.a2dpavrcpInit` + +```python +bt.a2dpavrcpInit() +``` + +A2DP和AVRCP功能初始化。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.a2dpavrcpRelease` + +```python +bt.a2dpavrcpRelease() +``` + +A2DP和AVRCP 资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.a2dpDisconnect` + +```python +bt.a2dpDisconnect(addr) +``` + +断开A2DP连接。 + +**参数描述:** + +- `addr`-A2DP主机蓝牙地址,6个字节,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.a2dpGetAddr` + +```python +bt.a2dpGetAddr() +``` + +获取A2DP主机蓝牙地址。 + +**返回值描述:** + +执行成功返回bytearray类型的A2DP主机蓝牙地址,6字节,失败返回整型-1。 + +### `bt.a2dpGetConnStatus` + +```python +bt.a2dpGetConnStatus() +``` + +获取A2DP连接状态。 + +**返回值描述:** + +A2DP连接状态,具体含义如下表。 + +| 值 | 类型 | 含义 | +| ---- | ---- | ------------ | +| -1 | int | 获取失败 | +| 0 | int | 连接已断开 | +| 1 | int | 正在连接中 | +| 2 | int | 已连接 | +| 3 | int | 正在断开连接 | + +### `bt.avrcpStart` + +```python +bt.avrcpStart() +``` + +控制主机开始播放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.avrcpPause` + +```python +bt.avrcpPause() +``` + +控制主机停止播放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.avrcpPrev` + +```python +bt.avrcpPrev() +``` + +控制主机播放上一首。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.avrcpNext` + +```python +bt.avrcpNext() +``` + +控制主机播放下一首。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.avrcpSetVolume` + +```python +bt.avrcpSetVolume(vol) +``` + +设置主机播放音量。 + +**参数描述:** + +- `vol`-播放音量,类型为整型,范围 0 - 11。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.avrcpGetVolume` + +```python +bt.avrcpGetVolume() +``` + +获取主机播放音量。 + +**返回值描述:** + +执行成功返回整形音量值,失败返回整型-1。 + +### `bt.avrcpGetPlayStatus` + +```python +bt.avrcpGetPlayStatus() +``` + +获取主机播放状态。 + +**返回值描述:** + +播放状态,具体含义如下表。 + +| 值 | 类型 | 说明 | +| ---- | ---- | -------------- | +| -1 | int | 获取失败 | +| 0 | int | 没有播放 | +| 1 | int | 正在播放 | +| 2 | int | 暂停播放 | +| 3 | int | 正在切换上一首 | +| 4 | int | 正在切换下一首 | + +### `bt.avrcpGetConnStatus` + +```python +bt.avrcpGetConnStatus() +``` + +通过AVRCP协议获取主机连接状态。 + +**返回值描述:** + +连接状态,具体含义如下表。 + +| 值 | 类型 | 说明 | +| ---- | ---- | ------------ | +| -1 | int | 获取失败 | +| 0 | int | 连接已断开 | +| 1 | int | 正在连接中 | +| 2 | int | 已连接 | +| 3 | int | 正在断开连接 | + +## SPP协议相关功能 + +提供蓝牙传输相关功能。 + +### `bt.sppInit` + +```python +bt.sppInit() +``` + +SPP 功能初始化。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.sppRelease` + +```python +bt.sppRelease() +``` + +SPP 资源释放。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.sppConnect` + +```python +bt.sppConnect(addr) +``` + +建立SPP连接。 + +**参数描述:** + +- `addr`-蓝牙地址,类型为bytearray,6个字节。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.sppDisconnect` + +```python +bt.sppDisconnect() +``` + +断开SPP连接。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +### `bt.sppSend` + +```python +bt.sppSend(data) +``` + +通过SPP发送数据。 + +**参数描述:** + +- `data`-待发送的数据,类型为bytearray。 + +**返回值描述:** + +执行成功返回整型0,失败返回整型-1。 + +> 注意:单次发送最大4008字节,建议按照667字节分片发送;返回-1一般是buffer满导致,需要加大延时发送。 diff --git a/docs/API_reference/zh/cloudlib/README.md b/docs/API_reference/zh/cloudlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d8c631d0fe1f03e7a2e2e31ec8a46bff99233ba --- /dev/null +++ b/docs/API_reference/zh/cloudlib/README.md @@ -0,0 +1,13 @@ +# QuecPython IoT 平台 + +> QuecPython IoT 平台库包括多个 IoT 平台的库,包括阿里 IoT 平台、腾讯 IoT 平台等。 + + +## QuecPython IoT 平台库列表 + +- [aLiYun - 阿里 IoT 平台](./aLiYun.md) +- [TXyun- 腾讯 IoT 平台](./TenCentYun.md) +- [Aws - 亚马逊 IoT 平台](./aws.md) +- [Azure - Azure IoT 平台](./azure.md) +- [Aws S3 – AWS S3 客户端](./aws_s3.md) + diff --git a/docs/API_reference/zh/cloudlib/TenCentYun.md b/docs/API_reference/zh/cloudlib/TenCentYun.md new file mode 100644 index 0000000000000000000000000000000000000000..e4762992fb217c71d0b7ae2c732c5bdafceb64e9 --- /dev/null +++ b/docs/API_reference/zh/cloudlib/TenCentYun.md @@ -0,0 +1,281 @@ +# TXyun- 腾讯 IoT 平台 + +该模块提供腾讯 IoT 平台物联网套件客户端功能,目前的产品节点类型仅支持“设备”,设备认证方式支持“一机一密”和“动态注册认证”。 + +>BC25PA系列不支持该功能。 + +## 初始化腾讯 IoT 平台 + +### `TXyun` + +```python +TXyun(productID, devicename, devicePsk, ProductSecret) +``` + +配置腾讯 IoT 平台物联网套件的产品信息和设备信息。 + +**参数描述:** + + +* `productID` - 产品标识(唯一ID) ,字符串类型 +* `devicename` - 设备名称 ,字符串类型 +* `devicePsk` - 设备密钥(一型一密认证方案时此参数传入None),字符串类型,可选参数,默认为None +* `ProductSecret` - 产品密钥,字符串类型,一机一密认证方案时,此参数传入None
一型一密认证方案时,此参数传入真实的产品密钥 + + + +**返回值描述:** + +返回TXyun连接对象。 + +## 设置相关功能和回调 + +### `TXyun.setMqtt` + +```python +TXyun.setMqtt(clean_session, keepAlive=300,reconn=True) +``` + +设置MQTT数据通道的参数 + +**参数描述:** + +* `clean_session` - 产品标识(唯一ID),布尔值类型,如果为True,
那么代理将在其断开连接时删除有关此客户端的所有信息。 如果为False,则客户端是持久客户端,当客户端断开连接时,订阅信息和排队消息将被保留。默认为False +* `keepAlive` - 通信之间允许的最长时间段(以秒为单位),整型类型,默认为300,范围(60-1000),建议300以上 +* `reconn` - (可选)控制是否使用内部重连的标志,布尔值类型,默认开启为True + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `TXyun.setCallback` + +```python +TXyun.setCallback(callback) +``` + +注册回调函数。 + +**参数描述:** + +* `callback` - 设置消息回调函数,function类型,当服务端响应时触发该方法 + +**回调函数参数** + +* `topic` - mqtt topic主题,字符串类型 +* `msg` - 需要发送的数据,字符串类型 + +**返回值描述:** + +无 + +### `TXyun.error_register_cb` + +```python +TXyun.error_register_cb(callback) +``` + +设置异常回调函数,腾讯 IoT 平台以及umqtt内部线程异常时通过回调返回error信息,该方法在设置不使用内部重连的情况下才可触发回调 + +**参数描述:** + +* `callback` - 设置异常回调函数,function类型 + +**回调函数参数** + +* `msg` - 异常信息,字符串类型 + +**返回值描述:** + +无 + +**示例:** + + +```python +from TenCentYun import TXyun + +def err_cb(err): + print("thread err:") + print(err) + +tenxun = TXyun(productID, devicename, devicePsk, ProductSecret) +tenxun.error_register_cb(err_cb) +``` + +## 订阅发布功能 + +### `TXyun.subscribe` + +```python +TXyun.subscribe(topic,qos) +``` + +订阅mqtt主题。 + +**参数描述:** + +* `topic` - mqtt topic主题,字符串类型 +* `qos` - MQTT消息服务质量(默认0,可选择0或1),整型类型
0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + + +### `TXyun.publish` + +```python +TXyun.publish(topic,msg, qos=0) +``` + +发布消息。 + +**参数描述:** + +* `topic` - mqtt topic主题,字符串类型 +* `msg` - 需要发送的数据,字符串类型 +* `qos` - MQTT消息服务质量(默认0,可选择0或1),整型类型
0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + + +## 启停服务相关功能 + +### `TXyun.start` + +```python +TXyun.start() +``` + +运行连接。 + +**参数描述:** + +无 + +**返回值描述:** + +无 + +### `TXyun.disconnect` + +```python +TXyun.disconnect() +``` + +关闭连接。 + +**参数描述:** + +无 + +**返回值描述:** + +无 + +### `TXyun.ping` + +```python +TXyun.ping() +``` + +发送心跳包 + +**参数描述:** + +无 + +**返回值描述:** + +无 + +### `TXyun.getTXyunsta` + +```python +TXyun.getTXyunsta() +``` + +获取腾讯 IoT 平台连接状态 + +注意:BG95平台不支持该功能。 + +**参数描述:** + +无 + +**返回值描述:** + +* 0 :连接成功 + +* 1:连接中 + +* 2:服务端连接关闭 + +* -1:连接异常 + + + +**示例:** + + +```python +from TenCentYun import TXyun +import log +import utime +import checkNet + + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_TencentYun_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +txyun_log = log.getLogger("TenCentYun") + +''' +腾讯 IoT 平台物联网套件客户端功能 +''' +productID = "" # 产品标识(参照接入腾讯 IoT 平台应用开发指导) +devicename = "" # 设备名称(参照接入腾讯 IoT 平台应用开发指导) +devicePsk = "" # 设备密钥(一型一密认证此参数传入None, 参照接入腾讯 IoT 平台应用开发指导) +ProductSecret = None # 产品密钥(一机一密认证此参数传入None,参照接入腾讯 IoT 平台应用开发指导) + +tenxun = TXyun(productID, devicename, devicePsk, ProductSecret) # 创建连接对象 +state = 5 + +def sub_cb(topic, msg): # IoT 平台消息响应回调函数 + global state + txyun_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + state -= 1 + + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + txyun_log.info('Network connection successful!') + + tenxun.setMqtt() # 设置mqtt + tenxun.setCallback(sub_cb) # 设置消息回调函数 + topic = "" # 输入自定义的Topic + tenxun.subscribe(topic) # 订阅Topic + tenxun.start() + tenxun.publish(topic, "hello world") # 发布消息 + + while 1: + if state: + pass + else: + tenxun.disconnect() + break + else: + txyun_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +``` diff --git a/docs/API_reference/zh/cloudlib/aLiYun.md b/docs/API_reference/zh/cloudlib/aLiYun.md new file mode 100644 index 0000000000000000000000000000000000000000..a74a7a930159ef9911e0bc03f793a7f8454ad1ad --- /dev/null +++ b/docs/API_reference/zh/cloudlib/aLiYun.md @@ -0,0 +1,306 @@ +# aLiYun - 阿里 IoT 平台 + +模块功能:阿里 IoT 平台物联网套件客户端功能,目前的产品节点类型仅支持“设备”,设备认证方式支持“一机一密和“一型一密”。 + +> BC25PA系列不支持模块功能。 + +## 初始化阿里 IoT 平台 + +### `aLiYun` + +```python +aliyun = aLiYun(productKey, productSecret, DeviceName, DeviceSecret, MqttServer) +``` + +配置阿里 IoT 平台物联网套件的产品信息和设备信息 + +**参数描述:** + +* `productKey` - 产品标识,字符串类型 +* `ProductSecret` - 产品密钥,字符串类型,一机一密认证方案时,此参数传入None
一型一密认证方案时,此参数传入真实的产品密钥 +* `devicename` - 设备名称 ,字符串类型 +* `DeviceSecret` - 可选参数,默认为None,设备密钥(一型一密认证方案时此参数传入None),字符串类型 +* `MqttServer` - 可选参数,需要连接的服务器名称,默认为"{productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com",字符串类型 + + +**返回值描述:** + +返回aLiYun连接对象。 + + +## 设置相关功能和回调 + +### `aLiYun.setMqtt` + +```python +aLiYun.setMqtt(clientID, clean_session, keepAlive=300,reconn=True) +``` + +设置MQTT数据通道的参数 + +**需要注意的是,当进行阿里 IoT 平台的一型一密连接的时候,会在本地生成secret.json的文件用以保存设备的设备密钥,如果重刷固件或者删除,再进行连接的时候会因为没有secret.json而报错,所以重刷固件或者删除了secert.json文件,需要手动新建secret.json文件,下面secret.json文件的模板** + +```json +{ + "Test01": "9facf9aba414ec9eea7c10d8a4cb69a0" +} +# Test01 : 设备名 +# "9facf9aba414ec9eea7c10d8a4cb69a0" 设备密钥 +``` + +**参数描述:** + +* `clientID` - 自定义阿里 IoT 平台连接id,字符串类型 +* `clean_session` - 产品标识(唯一ID),布尔值类型,如果为True,
那么代理将在其断开连接时删除有关此客户端的所有信息。 如果为False,则客户端是持久客户端,当客户端断开连接时,订阅信息和排队消息将被保留。默认为False +* `keepAlive` - 通信之间允许的最长时间段(以秒为单位),整型类型,默认为300,范围(60-1000),建议300以上 +* `reconn` - (可选)控制是否使用内部重连的标志,布尔值类型,默认开启为True + + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `aLiYun.setCallback` + +```python +aLiYun.setCallback(callback) +``` + +注册回调函数。 + +**参数描述:** + +* `callback` - 设置消息回调函数,function类型,当服务端响应时触发该方法 + +**回调函数参数** + +* `topic` - mqtt topic主题,字符串类型 +* `msg` - 需要发送的数据,字符串类型 + + +**返回值描述:** + +无 + + + +### `aLiYun.error_register_cb` + +```python +aLiYun.error_register_cb(callback) +``` + +设置异常回调函数,aliyun以及umqtt内部线程异常时通过回调返回error信息,该方法在设置不使用内部重连的情况下才可触发回调 + + +**参数描述:** + +* `callback` - 设置消息回调函数,function类型,当服务端响应时触发该方法 + +**回调函数参数** + +* `msg` - 异常信息,字符串类型 + +**返回值描述:** + +无 + +**示例:** + +```python +from aLiYun import aLiYun + +def err_cb(err): + print("thread err:") + print(err) + +ali = aLiYun(productKey, productSecret, DeviceName, DeviceSecret) +ali.error_register_cb(err_cb) +``` + + +## 订阅发布功能 + +### `aLiYun.subscribe` + +```python +aLiYun.subscribe(topic,qos) +``` + +订阅mqtt主题。 + +**参数描述:** + +* `topic` - mqtt topic主题,字符串类型 +* `qos` - MQTT消息服务质量(默认0,可选择0或1),整型类型
0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + + + +### `aLiYun.publish` + +```python +aLiYun.publish(topic,msg, qos=0) +``` + +发布消息。 + +**参数描述:** + +* `topic` - mqtt topic主题,字符串类型 +* `msg` - 需要发送的数据,字符串类型 +* `qos` - MQTT消息服务质量(默认0,可选择0或1),整型类型
0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +## 启停服务相关功能 + +### `aLiYun.start` + +```python +aLiYun.start() +``` + +运行连接。 + +**参数描述:** + +无 + +**返回值描述:** + +无 + + + +### `aLiYun.disconnect` + +```python +aLiYun.disconnect() +``` + +关闭连接。 + +**参数描述:** + +无 + +**返回值描述:** + +无 + +### `aLiYun.ping` + +```python +aLiYun.ping() +``` + +发送心跳包 + +**参数描述:** + +无 + +**返回值描述:** + +无 + + + +### `aLiYun.getAliyunSta` + +```python +aLiYun.getAliyunSta() +``` + +获取阿里 IoT 平台连接状态 + +注意:BG95平台不支持该API。 + +**参数描述:** + +无 + +**返回值描述:** + +* 0 :连接成功 + +* 1:连接中 + +* 2:服务端连接关闭 + +* -1:连接异常 + + + +**示例:** + +```python + +import log +import utime +import checkNet +from aLiYun import aLiYun + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_AliYin_example" +PROJECT_VERSION = "1.0.0" +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +aliYun_log = log.getLogger("ALiYun") + +productKey = "" # 产品标识(参照阿里 IoT 平台应用开发指导) +productSecret = None # 产品密钥(使用一机一密认证时此参数传入None,参照阿里 IoT 平台应用开发指导) +DeviceName = "" # 设备名称(参照阿里 IoT 平台应用开发指导) +DeviceSecret = "" # 设备密钥(使用一型一密认证此参数传入None,免预注册暂不支持,需先在 IoT 平台创建设备,参照阿里 IoT 平台应用开发指导) + +state = 5 + +# 回调函数 +def sub_cb(topic, msg): + global state + aliYun_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + state -= 1 + + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + aliYun_log.info('Network connection successful!') + # 创建aliyun连接对象 + ali = aLiYun(productKey, productSecret, DeviceName, DeviceSecret) + + # 设置mqtt连接属性 + clientID = "" # 自定义字符(不超过64) + ali.setMqtt(clientID, clean_session=False, keepAlive=300) + + # 设置回调函数 + ali.setCallback(sub_cb) + topic = "" # IoT 平台自定义或自拥有的Topic + # 订阅主题 + ali.subscribe(topic) + # 发布消息 + ali.publish(topic, "hello world") + # 运行 + ali.start() + + while 1: + if state: + pass + else: + ali.disconnect() + break + else: + aliYun_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +``` \ No newline at end of file diff --git a/docs/API_reference/zh/cloudlib/aws.md b/docs/API_reference/zh/cloudlib/aws.md new file mode 100644 index 0000000000000000000000000000000000000000..b8d03d76b9b18321ab7c80581e8241b0027eadb4 --- /dev/null +++ b/docs/API_reference/zh/cloudlib/aws.md @@ -0,0 +1,244 @@ +# Aws - 亚马逊 IoT 平台 + +提供一个可接入亚马逊 Iot 平台的客户端,用于管理亚马逊 MQTT 连接和影子设备。 + +## 初始化客户端 + +### `Aws` +```python +class Aws(client_id,server,port,keep_alive,ssl,ssl_params) +``` +**参数:** + +- `client_id` (str) - 客户端唯一标识。 +- `server` (str) - 亚马逊 Iot 平台服务器地址。 +- `port` (int) - MQTT 服务端口(默认端口为 1883,TLS 默认端口 为 8883)。 +- `keep_alive` (int) - 客户端 keep-alive 超时值,单位:秒(默认 60 秒)。 +- `ssl` (bool) - 是否使能 SSL/TLS(默认:False。如果设置为True,则必须设置 `ssl_params` 参数)。 +- `ssl_params` (dict) - SSL/TLS 连接参数。 + +**示例:** + +```python +>>> # Create Aws object +>>> import aws +>>> aws = aws.Aws(client_id, server, port, keep_alive=60,ssl=True,ssl_params={"cert": certificate_content,"key": private_content}) +``` + +## **MQTT 接入** + +使用 `umqtt` 模块接口来建立 AWS 云平台连接。 + +### `aws.connect` + +```python +connect() +``` +该方法用于建立 AWS 平台连接。 + +**返回值:** + +`None` + +### `aws.disconnect` + +```python +disconnect() +``` +改方法用于断开 AWS 平台连接。 + +**返回值:** + +`None` + +### `aws.subscribe` + +```python +subscribe(topic) +``` +该方法用于订阅 mqtt 主题。 + +**参数:** + +- `topic` (str) - 订阅主题。 + +**返回值:** + +`None` + +### `aws.publish` + +```python +publish(topic, payload) +``` +该方法用于发布消息到对应topic。 + +**参数:** + +- `topic` (str) - 发布主题。 +- `payload` (dict) - 需要发送的数据。 + +**返回值:** + +`None` + +## **影子设备管理** + +### `aws.create_shadow` + +```python +create_shadow(shadow_name="", state="") +``` +该方法用于创建影子设备。 + +**参数:** + +- `shadow_name` (str) - 影子设备名称(可选)。 +- `state` (dict) - 影子设备的初始状态参数(可选)。 + +**返回值:** + +`None` + +### `aws.update_shadow` + +```python +update_shadow(shadow_name="", state="") +``` +该方法用于更新影子设备名称和状态。 + +**参数:** + +- `shadow_name` (str) - 影子设备名称。 +- `state` (dict) - 影子设备的状态参数(可选)。 + +**返回值:** + + `None` + +### `aws.get_shadow` + +```python +get_shadow(shadow_name="") +``` +该方法用于获取影子设备状态。 + +**参数:** + +- `shadow_name` (str) - 影子设备名称。 + +**返回值:** + +当前影子设备的状态数据。 + +### `aws.delete_shadow` + +```python +delete_shadow(shadow_name="") +``` +该方法用于删除一个影子设备。 + +**参数:** + +- `shadow_name` (str) - 影子设备的名称。 + +**返回值:** + +`None` + +### `aws.connect_shadow` + +```python +connect_shadow(shadow_name="", topics=None) +``` +该方法用于连接影子设备。 + +**参数:** + +- `shadow_name` (str) - 影子设备名称(可选)。 +- `topics` (list) - 关联 影子设备的 MQTT 主题列表(可选)。 + +**返回值:** + +`None` + +### `aws.set_callback` + +```python +set_callback(topic_name, callback) +``` +**参数:** + +- `topic_name` (str) - MQTT 主题。 +- `callback` (function) - `topic_name` 主题对应的回调函数。 函数原型: + + callback_function(msg) + - 回调函数参数: + + - `msg`: 字典类型,接收到的消息。 + +**返回值:** + +`None` + +## **Python Example** +```python +import usr.aws as aws +import modem +import ujson +import sim # Check if PIN verification is needed for your SIM card +import net + +# AWS IoT credentials +certificate_content = """ +-----BEGIN CERTIFICATE----- + +-----END CERTIFICATE----- +""" + +private_content = """ +-----BEGIN RSA PRIVATE KEY----- + +-----END RSA PRIVATE KEY----- +""" + +client_id = 'qpthing' +server = 'abgka7vzgjoa0-ats.iot.eu-west-3.amazonaws.com' +port = 8883 + +def aws_callback(data): + print("HELLO from 1234 topic callback") + +def shadow_callback_get(data): + print("HELLO from get accepted callback") + +def shadow_callback_update(data): + print("HELLO from update accepted callback") + +def shadow_callback_delta(data): + print("HELLO from update delta callback") + +# Create AWS object +aws_obj = aws.Aws(client_id, server, port, keep_alive=60, ssl=True, + ssl_params={"cert": certificate_content, "key": private_content}) +print("Created AWS object") + +# Connect to AWS IoT +aws_obj.connect() +print("Connected to AWS IoT") + +# Subscribe and publish +aws_obj.set_callback("1234", aws_callback) +aws_obj.subscribe("1234") +aws_obj.publish("7777", "Hello from QuecPython") +aws_obj.start() + +# Shadow operations +aws_obj.create_shadow() +aws_obj.connect_shadow() +aws_obj.set_callback("$aws/things/qpthing/shadow/get/accepted", shadow_callback_get) +aws_obj.set_callback("$aws/things/qpthing/shadow/update/accepted", shadow_callback_update) +aws_obj.set_callback("$aws/things/qpthing/shadow/update/delta", shadow_callback_delta) +aws_obj.get_shadow() +aws_obj.update_shadow(state={"state": {"reported": {"welcome": "change reported"}}}) +``` diff --git a/docs/API_reference/zh/cloudlib/aws_s3.md b/docs/API_reference/zh/cloudlib/aws_s3.md new file mode 100644 index 0000000000000000000000000000000000000000..b3042e4ea977e6489d4bba681e8a49bd2c42d032 --- /dev/null +++ b/docs/API_reference/zh/cloudlib/aws_s3.md @@ -0,0 +1,126 @@ +# Aws S3 – AWS S3 客户端 + +`S3Client` 类为与 AWS S3 存储交互提供了一个方便的接口。它支持文件上传、下载和删除等操作,同时通过 HTTP SigV4 身份验证确保安全通信。 + +## 初始化客户端 + +### `S3Client` +```python +class S3Client(region=None, access_key=None, secret_key=None, bucket=None, config_path="config.json", download_path="") +``` + +**参数:** + +- **region** *(str, 可选)*: 指定S3存储桶所在的AWS区域。 +- **access_key** *(str, 可选)*: 用于身份验证的 Access Key。 +- **secret_key** *(str, 可选)*: 用于身份验证的 Secret Key。 +- **bucket** *(str, 可选)*: S3 存储桶的名称。 +- **config_path** *(str, 可选)*: JSON 配置文件的路径。默认为 `config.json`。 +- **download_path** *(str, 可选)*: 用于存储下载文件的本地目录。默认为空字符串。 + +**示例:** + +- 使用显示参数初始化 + +```python +from s3client import S3Client + +client = S3Client( + region="eu-west-3", + access_key="AKIA...", + secret_key="A2HAXbc...", + bucket="my-bucket", + download_path="s3_downloads/" +) +``` + +- 使用配置文件初始化 + +```python +from s3client import S3Client + +client = S3Client(config_path="usr/config.json") +``` + +## S3 通信 + +`S3Client` 使用 HTTP SigV4 签名的请求来执行上传、下载和从 AWS S3 存储中删除文件等操作。 + +### `upload_file` + +```python +upload_file(filepath, object_key, content_type='application/octet-stream') +``` + +将本地文件上载到指定的AWS S3存储桶。 + +**参数:** + +- **filepath** *(str)*: 要上载的文件的本地路径。 +- **object_key** *(str)*: 在S3存储桶中存储文件的密钥(路径)。 +- **content_type** *(str, 可选)*: 文件的 MIME 类型(默认: `application/octet-stream`)。 + +**返回值:** + +- **响应对象**包含服务器返回的所有信息,如响应状态代码、响应头和响应体。 + +- 返回 **None** 如果发生任何异常。 + +### `download_to_file` + +```python +download_to_file(object_key) +``` + +从 S3 存储桶下载一个文件,并将其保存在配置或构造函数中定义的`download_path`中。 + +**参数:** + +- **object_key** *(str)*: 要从S3存储桶下载的文件的密钥(路径)。 + +**返回值:** + +- **响应对象**包含服务器返回的所有信息,如响应状态代码、响应头和响应体。 + +- 返回 **None** 如果发生任何异常。 + +### `delete_object` + +```python +delete_object(object_key) +``` + +从 S3 存储桶中删除一个文件。 + +**参数:** + +- **object_key** *(str)*: 要从S3存储桶中删除的文件的密钥(路径)。 + +**返回值:** + +- **响应对象**包含服务器返回的所有信息,如响应状态代码、响应头和响应体。 + +- 返回 **None** 如果发生任何异常。 + +## 示例代码 + +```python +from s3client import S3Client + +s3_client = S3Client( + region="eu-west-3", + access_key="YOUR_ACCESS_KEY", + secret_key="YOUR_SECRET_KEY", + bucket="your-bucket-name", + download_path="s3_downloads/" +) + +# Upload a file +s3_client.upload_file(filepath='usr/hello.txt', object_key='test-folder/hello.txt',content_type='text/str') + +# Download a file +s3_client.download_to_file(object_key='test-folder/hello.txt') + +# Delete a file +s3_client.delete_file(object_key='test-folder/hello.txt') +``` \ No newline at end of file diff --git a/docs/API_reference/zh/cloudlib/azure.md b/docs/API_reference/zh/cloudlib/azure.md new file mode 100644 index 0000000000000000000000000000000000000000..94a2ccccdb17a6627d4928d186f5ad66626ba865 --- /dev/null +++ b/docs/API_reference/zh/cloudlib/azure.md @@ -0,0 +1,298 @@ +# Azure - Azure IoT 平台 + +用于连接到 Azure IoT Hub、管理MQTT连接、设备孪生、直接方法以及使用 SAS 令牌和 x.509 证书进行身份验证的客户端。 + +## 初始化客户端 + +### `Azure` +```python +class Azure(client_id, server, port, keep_alive=60, user=None, password=None, ssl=False, ssl_params=None) +``` +**参数:** + +- `client_id` (str) – 设备的唯一标识符。 +- `server` (str) – Azure IoT Hub 服务器域名 (e.g. `your-hub.azure-devices.net`)。 +- `port` (int) – MQTT 端口 (通常 8883 作为 TLS 端口)。 +- `keep_alive` (int) – 保活包心跳周期单位秒。 (默认: 60秒)。 +- `user` (str) – MQTT 用户名 (格式: `hostname/deviceId/?api-version=2020-09-30`)。 +- `password` (str) – SAS 认证的 token 值。 +- `ssl` (bool) – 是否采用 SSL/TLS 连接。(默认: False)。 +- `ssl_params` (dict) – SSL 连接参数。 + +**示例** + +```python +>>> import azure +>>> az = azure.Azure(client_id, server, port, keep_alive=60, user=username, password=sas_token, ssl=True, ssl_params={"cert": cert, "key": key}) +``` + +--- + +## 认证 + +### `azure.generate_sas_token` +```python +generate_sas_token(uri, key, policy_name, expiry=3600) +``` +生成共享访问签名(SAS)令牌。 + +**参数:** + +- `uri` - 统一资源标识符(URI),指定Azure IoT Hub中的目标设备。它应该遵循以下格式: `"{}/devices/{}".format(server, client_id)`, where `server` is the IoT Hub hostname and `client_id` is the unique device identifier. For example: `"your-hub.azure-devices.net/devices/myDeviceId"`。 +- `key` - 共享访问密钥。 +- `policy_name` - 您正在使用的策略的名称。如果不使用任何值,则 policy_name 值为None。 + +**返回值:** + +一个有效的 SAS 令牌字符串。 + + +## MQTT 通信 + +### `azure.connect` +```python +connect() +``` +建立 Azure IoT Hub 的 MQTT 连接。 + +**返回值:** + +None + +### `azure.disconnect` +```python +disconnect() +``` +断开与服务器的 MQTT 连接。 + +**返回值:** + +None + +### `azure.subscribe` +```python +subscribe(topic, qos=0) +``` +订阅主题。 + +**参数:** + +- `topic` (str) - 订阅主题。Azure IoT Hub已为订阅和发布保留了主题。 +- `qos` (str) - QoS 0或1。IoT Hub最多支持QoS 1,并将QoS 2订阅降级为QoS 1。 + +**返回值:** + +None + +### `azure.publish` +```python +publish(topic, payload, qos=0) +``` +指定主题发布消息。 + +**参数:** + +- `topic` (str) - 发布的主题。 +- `qos` (str) - QoS ,0 或 1。 + +**返回值:** + +None + +### `azure.set_callback` +```python +set_callback(topic_name, callback) +``` +为某个主题的传入消息设置回调。 + +**参数:** + +- `topic_name` (str) - 要为其设置回调的主题的名称。 +- `callback` (function) - 收到指定主题的回调函数,原型如下: + + callback_function(msg) + - 回调函数参数: + + - `msg`: 字典类型的消息。已从JSON字符串转换为字典格式。 + +**返回值:** + +None + +### `azure.loop` +```python +loop() +``` +处理传入的MQTT消息(非阻塞循环)。 + +**返回值:** + +None + +### `azure.start` +```python +start() +``` +启动MQTT客户端的主业务循环。 + +**返回值:** + +None + +--- + +## 管理设备孪生 + +### `azure.retrieve_twin` +```python +retrieve_twin(request_id=None, qos=0) +``` +从Azure IoT Hub检索当前孪生设备。它将打印 json 文件。 + +**参数:** + +- `request_id` (str) - 用于跟踪请求的唯一标识符。 +- `qos` (str) - level 0 或 1. + +**返回值:** + +None. + +### `azure.update_twin` +```python +update_twin(payload, request_id=None, qos=0) +``` +发送有关此主题的已报告属性更新:$iothub/twin/PATCH/properties/reported/?$rid={request_id} + +**参数:** + +- `payload`- json格式属性值。 +- `request_id` (str) - 用于跟踪请求的唯一标识符。 +- `qos` (str) - level 0 或 1. + +**返回值:** + +None + +### `azure.subscribe_to_desired_updates` + +```python +subscribe_to_desired_updates(qos=0) +``` +从云端订阅所需的属性更新。当所需属性从云端更改为此主题时,设备应订阅以接收实时更新:$iothub/twin/PATCH/properties/desired/# + +**参数:** + +- `qos` (str) - level 0 or 1. + +**返回值:** + +None + +--- +## Direct Methods + +### `azure.init_direct_method_handler` +```python +init_direct_method_handler(method_handler) +``` +初始化传入方法调用的直接方法处理程序。 + +**参数:** + +- `method_handler` - 回调函数,将在收到直接方法消息后调用。 + +**返回值:** + +None + +### `azure.send_method_response` +```python +send_method_response(status, message, request_id) +``` +向直接方法调用发送响应。当您收到直接方法消息时,您必须在预定义的时间段内做出响应。 + +**参数:** + +- `status` - 如果方法被识别,则为200;如果方法未被识别,则为400。 +- `message` - 响应字符串。 +- `request_id` - 唯一标识。 + +**返回值:** + +None + +--- + +## 示例代码 + +*Using SAS token authentication.* + +```python +import usr.azure as azure +import modem +import ujson +from usr.config import CERT,PRIVATE_KEY,SHARED_ACCESS_KEY, PASSWORD + + +# device name +client_id = 'device_name' +# server address +server = 'hub_name.azure-devices.net' +# port MQTT +port = 8883 + +username = '{}/{}/?api-version=2021-04-12'.format(server, client_id) + +uri = "{}/devices/{}".format(server, client_id) +SharedAccessKey = SHARED_ACCESS_KEY + + +# create azure obj +azure_obj = azure.Azure(client_id, server, port, keep_alive=60, user=username, password=PASSWORD, ssl=True, ssl_params={"cert": +CERT, "key": PRIVATE_KEY}) +print("create azure obj") + +#generate token +token = azure_obj.generate_sas_token(uri, SharedAccessKey, None) +azure_obj.mqtt_client.password = token + +# connect mqtt server +print("azure connect start") +azure_obj.connect() +print("azure connect end") + +''' +direct methods example +''' +#direct method handler +def handle_method(method_name, msg, request_id): + if method_name == "turn_on_the_light": + print("Light on!") + azure_obj.send_method_response(200, "Light on", request_id) + else: + azure_obj.send_method_response(404, "Method not found", request_id) + +#initializing direct method handler +azure_obj.init_direct_method_handler(handle_method) + +''' +device twins example +''' +#getting the twin json payload +azure_obj.retrieve_twin() + +#new payload to be added +payload = { + "status": "active", + "temperature": 24.5 +} + +#updating twin json payload +azure_obj.update_twin(payload) + +#subscribing to recieve updates on desired field in device twin +azure_obj.subscribe_to_desired_updates() + +azure_obj.start() +``` \ No newline at end of file diff --git a/docs/API_reference/zh/componentlib/README.md b/docs/API_reference/zh/componentlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d36ef3b03847d03db22f6b6c22370c852d4ec1c --- /dev/null +++ b/docs/API_reference/zh/componentlib/README.md @@ -0,0 +1,9 @@ +# QuecPython 开源组件 + +> QuecPython 组件库包括所有使用QuecPython脚本开发的功能组件 + +本文描述了 QuecPython 组件库中的模块。 + +## QuecPython 开源组件库列表 + +- [uasyncio-协程](./uasyncio.md) diff --git a/docs/API_reference/zh/componentlib/uasyncio.md b/docs/API_reference/zh/componentlib/uasyncio.md new file mode 100644 index 0000000000000000000000000000000000000000..097698aab565b8e868d7811694c2d556bae86f83 --- /dev/null +++ b/docs/API_reference/zh/componentlib/uasyncio.md @@ -0,0 +1,249 @@ +# uasyncio - 协程 + +`uasyncio`是MicroPython中的异步IO库,它是`asyncio`模块的一个轻量级子集。它提供了类似于标准库中的协程和事件循环的抽象,用于并发运行多个协程并管理协程的执行和挂起。`uasyncio`适用于嵌入式系统和资源受限设备,具有小巧的代码体积和低的内存占用。它提供了一组API和工具来创建和管理协程、支持异步IO的网络和协议相关类。 + + + +## coro创建 + + + +### uasyncio.create_task + +创建一个异步任务,用于执行指定的协程 + +```python +uasyncio.create_task(coro) +``` + +**参数描述:** + +* `coro`-要执行的协程对象 + +**示例:** + +```python +import usr.uasyncio as asyncio +async def my_coroutine(): + print("Running my_coroutine") + +task = asyncio.create_task(my_coroutine()) +``` + + + +## coro运行 + +### uasyncio.run + +运行一个协程,阻塞直到该协程完成。这是启动事件循环的主要方式。 + +```python +uasyncio.run(coro) +``` + +**参数描述:** + +* `coro`-要运行的协程对象 + +**示例:** + +```python +import usr.uasyncio as asyncio + +async def my_coroutine(): + print("Running my_coroutine") + +asyncio.run(my_coroutine()) +``` + +## coro取消任务 + +### task.cancel + +取消任务 + +```python +task.cancel() +``` + +**示例:** + +```python +from usr import uasyncio as asyncio +async def bar(n): + print('Start cancellable bar()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def do_cancel(task): + await asyncio.sleep(5) + print('About to cancel bar') + # 取消任务 + task.cancel() + +def main(): + task = asyncio.wait_for(bar(10), 7) + asyncio.create_task(do_cancel(task)) + asyncio.sleep(1) + +asyncio.run(main()) +``` + + + +## coro睡眠 + +### uasyncio.sleep + +暂停当前任务指定的秒数。这允许其他任务运行。 + +```python +uasyncio.sleep(delay) +``` + +**参数描述:** + +* `delay`-延迟的秒数, int |(可以是浮点数) + + + +### uasyncio.sleep_ms + +暂停当前任务指定的毫秒数。这允许其他任务运行。 + +```python +uasyncio.sleep_ms(delay) +``` + +**参数描述:** + +* `t`-延迟的毫秒数, int |(可以是浮点数) + + + +## coro任务超时取消 + +### uasyncio.wait_for + +等待一个协程,如果在给定的超时时间内未完成,则引发一个异常。。 + +```python +uasyncio.wait_for(coro, timeout) +``` + +**参数描述:** + +* `coro`-协程对象 +* `timeout`-超时时间, 单位是秒, int/float类型 + +**示例:** + +```python +from usr import uasyncio as asyncio + + +async def bar(x): + count = 0 + while True: + count += 1 + print('Instance: {} count: {}'.format(x, count)) + await asyncio.sleep(2) # Pause 1s + print("sleep count instance = {} count = {}".format(x, count)) + + +async def main(): + """设置协程wait task""" + task = asyncio.wait_for(bar(10), 7) + """启动协程, 上面协程表示在7秒内如果执行的task没退出,则关闭协程, 跑出error""" + asyncio.run(task) + await asyncio.sleep(10) + +asyncio.run(main()) +``` + + + +### uasyncio.wait_for_ms + +这个函数的功能和 `wait_for` 类似,但是超时时间的单位是毫秒。 + +```python +uasyncio.wait_for_ms(coro, timeout) +``` + +**参数描述:** + +* `coro`-协程对象 + +* `timeout`-超时时间, 单位是毫秒, int/float类型 + + + +## coro并发执行 + +### uasyncio.gather + +运行给定的协程并收集它们的结果。当所有协程都完成时,此函数返回一个结果列表。 `return_exceptions` (默认为`False`),即在任何协程引发异常时立即中止并引发异常。如果设置为`True`,则将异常包装在结果中返回。 + +```python +uasyncio.gather(*coros, return_exceptions=False) +``` + +**参数描述:** + +* `coros`-单个或多个协程对象 +* `return_exceptions`-是否返回异常作为结果, bool类型, 默认为False。 + +**示例:** + +```python +from usr import uasyncio as asyncio + + +async def barking(n): + print('Start barking') + for _ in range(6): + await asyncio.sleep(1) + print('Done barking.') + return 2 * n + +async def foo(n): + print('Start timeout coro foo()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def bar(n): + print('Start cancellable bar()') + while True: + await asyncio.sleep(1) + n += 1 + return n + +async def do_cancel(task): + await asyncio.sleep(5) + print('About to cancel bar') + task.cancel() + +async def main(): + tasks = [asyncio.create_task(bar(70))] + tasks.append(barking(21)) + tasks.append(asyncio.wait_for(foo(10), 7)) + asyncio.create_task(do_cancel(tasks[0])) + res = None + try: + # return_exceptions=True, 默认为False,即在任何协程引发异常时立即中止并引发异常。 如果设置为True,则将异常包装在结果中返回。 + res = await asyncio.gather(*tasks, return_exceptions=True) + except asyncio.TimeoutError: # These only happen if return_exceptions is False + print('Timeout') # With the default times, cancellation occurs first + except asyncio.CancelledError: + print('Cancelled') + print('Result: ', res) + +asyncio.run(main()) +``` + diff --git a/docs/API_reference/zh/config.json b/docs/API_reference/zh/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ee90bec6d6c97e7ed26fa905b9e62b7922b0adf1 --- /dev/null +++ b/docs/API_reference/zh/config.json @@ -0,0 +1,19 @@ +{ + "import": "config_zh", + "name": "API参考手册", + "navbar": { + "items": [ + { + "label": "Version", + "position": "right", + "type": "list", + "items": [ + { + "url": "/API_reference/zh/", + "label": "V1.0(latest)" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/docs/API_reference/zh/errcode/README.md b/docs/API_reference/zh/errcode/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2f47cd38a41f329c3b0ff9e2103037414ab05395 --- /dev/null +++ b/docs/API_reference/zh/errcode/README.md @@ -0,0 +1,115 @@ +# QuecPython错误码汇总 + +**QuecPython中定义的各种错误代码常量** + +| 错误码常量 | 错误码 | 释义 | +| ----------------------- | ------ | ----------------------------------------------- | +| QUEC_PY_FAIL | -1 | Generic failure codes | +| QUEC_PY_OK | 0 | Quec_py value indicating success (no error) | +| QUEC_PY_EPERM | 1 | Operation not permitted | +| QUEC_PY_ENOENT | 2 | No such file or directory | +| QUEC_PY_ESRCH | 3 | No such process | +| QUEC_PY_EINTR | 4 | Interrupted system call | +| QUEC_PY_EIO | 5 | I/O error | +| QUEC_PY_ENXIO | 6 | No such device or address | +| QUEC_PY_E2BIG | 7 | Argument list too long | +| QUEC_PY_ENOEXEC | 8 | Exec format error | +| QUEC_PY_EBADF | 9 | Bad file number | +| QUEC_PY_ECHILD | 10 | No child processes | +| QUEC_PY_EAGAIN | 11 | Try again | +| QUEC_PY_ENOMEM | 12 | Out of memory | +| QUEC_PY_EACCES | 13 | Permission denied | +| QUEC_PY_EFAULT | 14 | Bad address | +| QUEC_PY_ENOTBLK | 15 | Block device required | +| QUEC_PY_EBUSY | 16 | Device or resource busy | +| QUEC_PY_EEXIST | 17 | File exists | +| QUEC_PY_EXDEV | 18 | Cross-device link | +| QUEC_PY_ENODEV | 19 | No such device | +| QUEC_PY_ENOTDIR | 20 | Not a directory | +| QUEC_PY_EISDIR | 21 | Is a directory | +| QUEC_PY_EINVAL | 22 | Invalid argument | +| QUEC_PY_ENFILE | 23 | File table overflow | +| QUEC_PY_EMFILE | 24 | Too many open files | +| QUEC_PY_ENOTTY | 25 | Not a typewriter | +| QUEC_PY_ETXTBSY | 26 | Text file busy | +| QUEC_PY_EFBIG | 27 | File too large | +| QUEC_PY_ENOSPC | 28 | No space left on device | +| QUEC_PY_ESPIPE | 29 | Illegal seek | +| QUEC_PY_EROFS | 30 | Read-only file system | +| QUEC_PY_EMLINK | 31 | Too many links | +| QUEC_PY_EPIPE | 32 | Broken pipe | +| QUEC_PY_EDOM | 33 | Math argument out of domain of func | +| QUEC_PY_ERANGE | 34 | Math result not representable | +| QUEC_PY_EDEADLK | 35 | Resource deadlock would occur | +| QUEC_PY_ENAMETOOLONG | 36 | File name too long | +| QUEC_PY_ENOLCK | 37 | No record locks available | +| QUEC_PY_ENOSYS | 38 | Function not implemented | +| QUEC_PY_ENOTEMPTY | 39 | Directory not empty | +| QUEC_PY_ELOOP | 40 | Too many symbolic links encountered | +| QUEC_PY_EWOULDBLOCK | 41 | Operation would block | +| QUEC_PY_ENOMSG | 42 | No message of desired type | +| QUEC_PY_EIDRM | 43 | Identifier removed | +| QUEC_PY_ECHRNG | 44 | Channel number out of range | +| QUEC_PY_EL2NSYNC | 45 | Level 2 not synchronized | +| QUEC_PY_EL3HLT | 46 | Level 3 halted | +| QUEC_PY_EL3RST | 47 | Level 3 reset | +| QUEC_PY_ELNRNG | 48 | Link number out of range | +| QUEC_PY_EUNATCH | 49 | Protocol driver not attached | +| QUEC_PY_ENOCSI | 50 | No CSI structure available | +| QUEC_PY_EL2HLT | 51 | Level 2 halted | +| QUEC_PY_EBADE | 52 | Invalid exchange | +| QUEC_PY_EBADR | 53 | Invalid request descriptor | +| QUEC_PY_EXFULL | 54 | Exchange full | +| QUEC_PY_ENOANO | 55 | No anode | +| QUEC_PY_EBADRQC | 56 | Invalid request code | +| QUEC_PY_EBADSLT | 57 | Invalid slot | +| QUEC_PY_EDEADLOCK | 58 | Deadlock | +| QUEC_PY_EBFONT | 59 | Bad font file format | +| QUEC_PY_ENOSTR | 60 | Device not a stream | +| QUEC_PY_ENODATA | 61 | No data available | +| QUEC_PY_ETIME | 62 | Timer expired | +| QUEC_PY_ENOSR | 63 | Out of streams resources | +| QUEC_PY_ENONET | 64 | Machine is not on the network | +| QUEC_PY_ENOPKG | 65 | Package not installed | +| QUEC_PY_EREMOTE | 66 | Object is remote | +| QUEC_PY_ENOLINK | 67 | Link has been severed | +| QUEC_PY_EADV | 68 | Advertise error | +| QUEC_PY_ESRMNT | 69 | Srmount error | +| QUEC_PY_ECOMM | 70 | Communication error on send | +| QUEC_PY_EPROTO | 71 | Protocol error | +| QUEC_PY_EMULTIHOP | 72 | Multihop attempted | +| QUEC_PY_EDOTDOT | 73 | RFS specific error | +| QUEC_PY_EBADMSG | 74 | Not a data message | +| QUEC_PY_EOVERFLOW | 75 | Value too large for defined data type | +| QUEC_PY_ENOTUNIQ | 76 | Name not unique on network | +| QUEC_PY_EBADFD | 77 | File descriptor in bad state | +| QUEC_PY_EREMCHG | 78 | Remote address changed | +| QUEC_PY_ELIBACC | 79 | Can not access a needed shared library | +| QUEC_PY_ELIBBAD | 80 | Accessing a corrupted shared library | +| QUEC_PY_ELIBSCN | 81 | .lib section in a.out corrupted | +| QUEC_PY_ELIBMAX | 82 | Attempting to link in too many shared libraries | +| QUEC_PY_ELIBEXEC | 83 | Cannot exec a shared library directly | +| QUEC_PY_EILSEQ | 84 | Illegal byte sequence | +| QUEC_PY_ERESTART | 85 | Interrupted system call should be restarted | +| QUEC_PY_ESTRPIPE | 86 | Streams pipe error | +| QUEC_PY_EUSERS | 87 | Too many users | +| QUEC_PY_ENOTSOCK | 88 | Socket operation on non-socket | +| QUEC_PY_EDESTADDRREQ | 89 | Destination address required | +| QUEC_PY_EMSGSIZE | 90 | Message too long | +| QUEC_PY_EPROTOTYPE | 91 | Protocol wrong type for socket | +| QUEC_PY_ENOPROTOOPT | 92 | Protocol not available | +| QUEC_PY_EPROTONOSUPPORT | 93 | Protocol not supported | +| QUEC_PY_ESOCKTNOSUPPORT | 94 | Socket type not supported | +| QUEC_PY_EOPNOTSUPP | 95 | Operation not supported on transport endpoint | +| QUEC_PY_EAFNOSUPPORT | 97 | Address family not supported by protocol | +| QUEC_PY_EADDRINUSE | 98 | Address already in use | +| QUEC_PY_ECONNABORTED | 103 | Software caused connection abort | +| QUEC_PY_ECONNRESET | 104 | Connection reset by peer | +| QUEC_PY_ENOBUFS | 105 | No buffer space available | +| QUEC_PY_EISCONN | 106 | Transport endpoint is already connected | +| QUEC_PY_ENOTCONN | 107 | Transport endpoint is not connected | +| QUEC_PY_ETIMEDOUT | 110 | Connection timed out | +| QUEC_PY_ECONNREFUSED | 111 | Connection refused | +| QUEC_PY_EHOSTUNREACH | 113 | No route to host | +| QUEC_PY_EALREADY | 114 | Operation already in progress | +| QUEC_PY_EINPROGRESS | 115 | Operation now in progress | \ No newline at end of file diff --git a/docs/API_reference/zh/gnsslib/README.md b/docs/API_reference/zh/gnsslib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..103542c73a413eae39007a879d44c7ab3345f5e0 --- /dev/null +++ b/docs/API_reference/zh/gnsslib/README.md @@ -0,0 +1,13 @@ +# QuecPython 定位应用 + +> QuecPython 定位应用包括所有定位相关的功能模块 + +本文描述了 QuecPython 定位应用库中的模块。 + +## QuecPython 定位应用库列表 + +- [gnss - 外置GNSS](./gnss.md) +- [quecgnss - 内置GNSS](./quecgnss.md) +- [cellLocator - 基站定位](./cellLocator.md) +- [wifilocator - WIFI定位](./wifilocator.md) +- [wifiScan - WiFi扫描](./wifiScan.md) diff --git a/docs/API_reference/zh/gnsslib/cellLocator.md b/docs/API_reference/zh/gnsslib/cellLocator.md new file mode 100644 index 0000000000000000000000000000000000000000..fb466e1f9e1d5d88f85437570d897951b664595b --- /dev/null +++ b/docs/API_reference/zh/gnsslib/cellLocator.md @@ -0,0 +1,61 @@ +# cellLocator - 基站定位 + +该模块提供基站定位功能,获取模组经纬度坐标信息。 + + + +>当前仅EC600S/EC600N/EC800N/EC200U/EC600U/EG912U/EG915U/EC600E/EC800E系列支持该功能。 + + + +## 获取坐标信息 + +### `cellLocator.getLocation` + +```python +cellLocator.getLocation(serverAddr, port, token, timeout [, profileIdx]) +``` + +该方法用于获取模组经纬度坐标信息。 + +**参数描述:** + +* `serverAddr` - 服务器域名,字符串类型,长度必须小于255 bytes,域名请联系移远技术支持。 +* `port` - 服务器端口,整型值,目前仅支持 80 端口。 +* `token` - 密钥,字符串类型,16位字符组成,需要申请。 +* `timeout` -设置超时时间,整型值,范围1-300s,默认300s。 +* `profileIdx` - PDP上下文ID,整型值,可选参数,范围1 ~ 3,默认为当前拨号成功的那一路,设置其他值可能需要专用apn与密码才能设置成功;
+ +**返回值描述:** + + 成功返回经纬度坐标信息,元组格式:`(longitude, latitude, accuracy)`,`(0.0, 0.0, 0)`表示未获取到有效坐标信息; + +`longitude` : 经度 + +`latitude` :纬度 + +`accuracy` :精确度,单位米 + +失败返回错误码说明如下: + +`1` – 初始化失败 + +`2` – 服务器地址过长(超过255字节) + +`3` – 密钥长度错误,必须为16字节 + +`4` – 超时时长超出范围,支持的范围(1 ~ 300)s + +`5` – 指定的PDP网络未连接,请确认PDP是否正确 + +`6` – 获取坐标出错。 + +**示例:** + +```python +>>> import cellLocator +>>> cellLocator.getLocation("www.example.com", 80, "xxxxxxxxxxxxxxxx", 8, 1) +(117.1138, 31.82279, 550) +# 上面"www.example.com" 是指域名,请联系移远技术支持 +# 上面使用的密钥"xxxxxxxxxxxxxxxx"指代token,具体需要向移远申请 +``` diff --git a/docs/API_reference/zh/gnsslib/gnss.md b/docs/API_reference/zh/gnsslib/gnss.md new file mode 100644 index 0000000000000000000000000000000000000000..6b06d710f85228d17b52c4dabebd6dcef1b192aa --- /dev/null +++ b/docs/API_reference/zh/gnsslib/gnss.md @@ -0,0 +1,366 @@ +# gnss - 外置GNSS + +对L76K GPS型号(或数据类型与之类似的GPS模组)进行数据获取,可以得到模块定位是否成功,定位的经纬度数据,UTC授时时间,获取GPS模块的定位模式,获取GPS模块定位使用卫星数量,获取GPS模块定位可见卫星数量,获取定位方位角,GPS模块对地速度,模块定位大地高等数据信息。目前,该模块提供的功能接口,所获取的数据都来源于从串口读出的原始GNSS数据包中的GNGGA、GNRMC和GPGSV语句。 + +> 当前仅EC600S/EC600N/EC800N/200U/600U/600M/800M模块支持该功能 +> + +## 创建gnss对象 + +### `gnss.GnssGetData` + +```python +gnss.GnssGetData(uartn,baudrate,databits,parity,stopbits,flowctl) +``` + +创建获取GNSS的对象,参数为挂载GNSS模块的串口以及通信参数 + +**参数描述** + +* `uartn`,int类型 + uartn + `0`-uart0 - DEBUG PORT + `1`-uart1 – BT PORT + `2`-uart2 – MAIN PORT + `3`-uart3 – USB CDC PORT +* `baudrate`,int类型,常用波特率都支持,如4800、9600、19200、38400、57600、115200、230400等 +* `databits`,int类型,数据位(5 ~ 8),ECX00U系列平台当前仅支持8位 +* `parity`,int类型,奇偶校验(0 – NONE,1 – EVEN,2 - ODD) +* `stopbits`,int类型,停止位(1 ~ 2) +* `flowctl`,int类型,硬件控制流(0 – FC_NONE, 1 – FC_HW) + +**返回值描述**
gnss类的对象 + +**示例** + +```python +from gnss import GnssGetData +gnss = GnssGetData(1, 9600, 8, 0, 1, 0) +``` + +## 读取GNSS数据并解析 + +### `gnss.read_gnss_data` + +```python +gnss.read_gnss_data(max_retry=1, debug=0) +``` + +从串口读取GNSS数据,返回数据长度 + +**参数描述** + +* `max_retry`,int类型,可选参数,可不填该参数,默认为1;表示当读取的GNSS无效时,自动重新读取的最大尝试次数,如果读取数据长度为0(即没有读取到数据)则直接退出。 +* `debug`,int类型, 可选参数,可不填该参数,默认为0;表示在读取解析GNSS数据过程中,是否输出一些调试信息,为0表示不输出详细信息,为1表示输出详细信息。 + +**返回值描述** + +返回从串口读取的GNSS数据长度,int类型,单位字节。 + +**示例** + +```python +#========================================================================= +gnss.read_gnss_data() # 使用默认设置,仅读取一次,不输出详细调试信息 +4224 # 读取数据成功,并解析GNGGA、GNRMC和GPGSV语句都成功,直接返回读取的原始数据长度 +#========================================================================= +gnss.read_gnss_data() # 使用默认设置,仅读取一次,不输出详细调试信息 +GNGGA data is invalid. # 读取数据成功,获取的GNGGA定位数据无效 +GNRMC data is invalid. # 读取数据成功,获取的GNRMC定位数据无效 +648 # 返回读取的原始数据长度 +#========================================================================= +gnss.read_gnss_data(max_retry=3) # 设置最大自动读取次数为3次 +Not find GPGSV data or GPGSV data is invalid. # 第1次读取,GPGSV数据未找到或无效 +continue read. # 继续读取下一包数据 +Not find GNGGA data. # 第2次读取,没有找到GNGGA数据 +Not find GNRMC data. # 第2次读取,没有找到GNRMC数据 +continue read. # 继续尝试读取下一包 +Not find GNGGA data. # 第3次读取,没有找到GNGGA数据 +Not find GNRMC data. # 第3次读取,没有找到GNRMC数据 +continue read. # 第3次依然失败,准备继续读取,判断出已经达到最大尝试次数,退出 +128 +#========================================================================= +gnss.read_gnss_data(debug=1) # 设置读取解析过程输出详细信息 +GGA data : ['GNGGA', '021224.000', '3149.27680', 'N', '11706.93369', 'E', '1', '19', '0.9', '168.2', 'M', '-5.0', 'M', '', '*52'] # 输出从原始GNSS数据中匹配到并简单处理后的GNGGA数据 +RMC data : ['GNRMC', '021224.000', 'A', '3149.27680', 'N', '11706.93369', 'E', '0.00', '153.28', '110122', '', '', 'A', 'V*02'] # 输出从原始GNSS数据中匹配到并简单处理后的GNRMC数据 +total_sen_num = 3, total_sat_num = 12 # 输出一组完整GPGSV语句总条数和可视卫星数量 +# 下面是具体的匹配到的GPGSV语句信息 +[0] : ['$GPGSV', '3', '1', '12', '10', '79', '210', '35', '12', '40', '070', '43', '21', '08', '305', '31', '23', '46', '158', '43', '0*6E'] +[1] : ['$GPGSV', '3', '2', '12', '24', '', '', '26', '25', '54', '125', '42', '31', '', '', '21', '32', '50', '324', '34', '0*64'] +[2] : ['$GPGSV', '3', '3', '12', '193', '61', '104', '44', '194', '58', '117', '42', '195', '05', '162', '35', '199', '', '', '32', '0*54'] +4224 +``` + +## 获取读取的原始GNSS数据 + +### `gnss.getOriginalData` + +```python +gnss.getOriginalData() +``` + +该接口用于返回从串口读取的原始GNSS数据,如果用户希望拿到原始GNSS数据,自己进行处理或者进行一些数据确认,可以通过该接口来获取。该接口在每次调用 [`gnss.read_gnss_data(max_retry=1, debug=0)`](https://developer.quectel.com/doc/quecpython/API_reference/zh/gnsslib/gnss.html#%3Ccode%3Egnss.read_gnss_data%3C/code%3E)接口后,返回的即本次读取的原始数据。 + +**返回值描述** + +返回从串口读取的原始GNSS数据,string类型。 + +**示例** + +```python +data = gnss.getOriginalData() +print(data) +# 数据量较大,仅列出部分结果 +00,A,3149.28094,N,11706.93869,E,0.00,153.28,110122,,,A,V*04 +$GNVTG,153.28,T,,M,0.00,N,0.00,K,A*2E +$GNZDA,021555.000,11,01,2022,00,00*4D +$GPTXT,01,01,01,ANTENNA OK*35 +$GNGGA,021556.000,3149.28095,N,11706.93869,E,1,24,0.6,166.5,M,-5.0,M,,*5E +$GNGLL,3149.28095,N,11706.93869,E,021556.000,A,A*47 +$GNGSA,A,3,10,12,21,23,24,25,32,193,194,195,199,,1.0,0.6,0.8,1*35 +$GNGSA,A,3,01,04,07,09,14,21,22,24,38,39,42,45,1.0,0.6,0.8,4*36 +... +$GNGGA,021600.000,3149.28096,N,11706.93877,E,1,25,0.6,166.4,M,-5.0,M,,*52 +$GNGLL,3149.28096,N,11706.93877,E,021600.000,A,A*4B +$GNGSA,A,3,10,12,21,23,24,25,31,32,193,194,195,199,1.0,0.6,0.8,1*37 +$GNGSA,A,3,01,04,07,09,$GNGGA,021601.000,3149.28096,N,11706.93878,E,1,25,0.6,166.4,M,-5.0,M,,*5C +$GNGLL,3149.2809 +``` + +## 检查本次读取解析结果有效性 + +### `gnss.checkDataValidity` + +```python +gnss.checkDataValidity() +``` + +GNSS模块提供的功能接口,所获取的数据都来源于从串口读出的原始GNSS数据包中的GNGGA、GNRMC和GPGSV语句,该接口用于检查读取的一包GNSS数据中,GNGGA、GNRMC和GPGSV语句的有效性。 + +**返回值描述** + +返回一个元组,形式为 ` (gga_valid, rmc_valid, gsv_valid)` + +`gga_valid` - 表示本次读取解析,是否匹配到GNGGA数据并解析成功,0表示没有匹配到GNGGA数据或数据无效,1表示有效; + +`rmc_valid` - 表示本次读取解析,是否匹配到GNRMC数据并解析成功,0表述没有匹配到GNRMC数据或数据无效,1表示有效; + +`gsv_valid` - 表示本地读取解析,是否匹配到GPGSV数据并解析成功,0表示没有匹配到GPGSV数据或数据无效,1表示有效。 + +如果用户只关心定位结果,即GNGGA数据是否有效,只要gga_valid参数为1即可(或者通过gnss.isFix()接口来判断定位是否成功),不一定要三个参数都为1;解析GNRMC数据是为了获取对地速度,解析GPGSV数据是为了获取可视卫星数量以及这些卫星对应的方位角,所以用户如果不关心这些参数,可忽略rmc_valid和gsv_valid。 + +**示例** + +```python +gnss.checkDataValidity() +(1, 1, 1) # 说明本次读取解析,GNGGA、GNRMC和GPGSV这三种数据都匹配成功并解析成功 +``` + +## 检查是否定位成功 + +### `gnss.isFix` + +```python +gnss.isFix() +``` + +检查指定串口是否读取到有效GNSS信息 + +**返回值描述** + +`1`:定位成功 + +`0`:定位失败 + +**示例** + +``` +gnss.isFix() +1 +``` + +## 获取定位的UTC时间 + +### `gnss.getUtcTime` + +```python +gnss.getUtcTime() +``` + +获取GNSS信息中携带的时间 + +**返回值描述** + +成功返回UTC时间,字符串类型,失败返回整型`-1`。 + +**示例** + +```python +gnss.getUtcTime() +'06:22:05.000' # hh:mm:ss.sss +``` + +## 获取GPS模块定位模式 + +### `gnss.getLocationMode` + +```python +gnss.getLocationMode() +``` + +获取GNSS信息中携带的定位模式 + +**返回值描述** + +| 返回值 | 描述 | +| ------ | ---------------------------------------- | +| -1 | 获取失败,串口未读到数据或未读到有效数据 | +| 0 | 定位不可用或者无效 | +| 1 | 定位有效,定位模式:GPS、SPS 模式 | +| 2 | 定位有效,定位模式: DGPS、DSPS 模式 | +| 6 | 估算(航位推算)模式 | + +**示例** + +```python +gnss.getLocationMode() +1 +``` + +## 获取GPS模块定位使用卫星数量 + +### `gnss.getUsedSateCnt` + +```python +gnss.getUsedSateCnt() +``` + +获取GNSS信息中携带的使用卫星数量 + +**返回值描述** + +成功返回GPS模块定位使用卫星数量,返回值类型为整型,失败返回整型`-1`。 + +**示例** + +``` +gnss.getUsedSateCnt() +24 +``` + +## 获取GPS模块定位的经纬度信息 + +### `gnss.getLocation` + +```python +gnss.getLocation() +``` + +获取GNSS信息中携带的经纬度信息 + +**返回值描述** + +成功返回GPS模块定位的经纬度信息,失败返回整型`-1`;成功时返回值格式如下: + +`(longitude, lon_direction, latitude, lat_direction)` + +`longitude` - 经度,float型 + +`lon_direction` - 经度方向,字符串类型,E表示东经,W表示西经 + +`latitude` - 纬度,float型 + +`lat_direction` - 纬度方向,字符串类型,N表示北纬,S表示南纬 + +**示例** + +```python +gnss.getLocation() +(117.1156448333333, 'E', 31.82134916666667, 'N') +``` + +## 获取GPS模块定位可见卫星数量 + +### **`gnss.getViewedSateCnt`** + +```python +gnss.getViewedSateCnt() +``` + +获取GNSS信息中携带的可见卫星数量 + +**返回值描述** + +成功返回GPS模块定位可见卫星数量,整型值,失败返回整型-1。 + +**示例** + +```python +gnss.getViewedSateCnt() +12 +``` + +## 获取可视的GNSS卫星方位角 + +### **`gnss.getCourse`** + +```python +gnss.getCourse() +``` + +获取GNSS信息中携带的卫星方位角 + +**返回值描述** + +返回所有可视的GNSS卫星方位角,范围:`0 ~ 359`,以正北为参考平面。返回形式为字典,其中key表示卫星编号,value表示方位角。要注意,value的值可能是一个整型值,也可能是空,这取决于原始的GNSS数据中GPGSV语句中方位角是否有值,如获取失败返回-1。返回值形式如下: + +`{key:value, ..., key:value}` + +**示例** + +```python + gnss.getCourse() +{'10': 204, '195': 162, '12': 68, '193': 105, '32': 326, '199': 162, '25': 122, '31': 247, '24': 52, '194': 116, '21': 304, '23': 159} +``` + +## 获取GPS模块定位海拔高度 + +### **`gnss.getGeodeticHeight`** + +```python +gnss.getGeodeticHeight() +``` + +获取GNSS信息中携带的海拔高度 + +**返回值描述** + +成功返回浮点类型海拔高度(单位:米),失败返回整型`-1`。 + +**示例** + +```python +gnss.getGeodeticHeight() +166.5 +``` + +## 获取GPS模块对地速度 + +### `gnss.getSpeed` + +```python +gnss.getSpeed() +``` + +获取GNSS信息中携带的对地速度 + +**返回值描述** + +成功返回GPS模块对地速度(单位:KM/h),浮点类型,失败返回整型`-1` + +**示例** + +```python +gnss.getSpeed() +0.0 +``` diff --git a/docs/API_reference/zh/gnsslib/quecgnss.md b/docs/API_reference/zh/gnsslib/quecgnss.md new file mode 100644 index 0000000000000000000000000000000000000000..c2b35271d2890189575cef686856a60224535333 --- /dev/null +++ b/docs/API_reference/zh/gnsslib/quecgnss.md @@ -0,0 +1,541 @@ +# quecgnss - 内置GNSS + +此模块提供内置GNSS的使用接口 + +> QuecPython模组当前内置GNSS支持列表:
+> ECX00U AA/LA系列
+> EG91XU AA系列
+> EC800M GA/GB/GC/GD系列
+> EG810M GA系列
+> EC800G GA系列
+> BG95M1/M3型号 + +**使用示例** + +```python +import quecgnss + + +def main(): + quecgnss.configSet(0,1)#设置定位星系为GPS+Beidou + quecgnss.configSet(2,1)#打开AGPS + quecgnss.configSet(4,1)#打开备电 + ret = quecgnss.init() + if ret == 0: + print('GNSS init ok.') + else: + print('GNSS init failed.') + return -1 + data = quecgnss.read(4096) + print(data[1].decode()) + + quecgnss.gnssEnable(0) + + +if __name__ == '__main__': + main() + + +#=================================================================================================== +#运行结果 +167,169,170,,,,,,,,1.773,1.013,1.455*15 +$GPGSV,2,1,8,3,23,303,34,16,32,219,28,22,74,98,26,25,16,43,25*77 +$GPGSV,2,2,8,26,70,236,28,31,59,12,38,32,55,127,34,4,5,,21*49 +$BDGSV,2,1,8,163,51,192,32,166,70,11,31,167,52,197,32,169,59,334,31*61 +$BDGSV,2,2,8,170,40,205,31,161,5,,31,164,5,,27,165,5,,29*59 +$GNRMC,022326.000,A,3149.324624,N,11706.921702,E,0.000,261.541,180222,,E,A*38 +$GNGGA,022326.000,3149.324624,N,11706.921702,E,1,12,1.013,-8.580,M,0,M,,*47 +$GNGLL,3149.324624,N,11706.921702,E,022326.000,A,A*44 +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.773,1.013,1.455*1C +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.773,1.013,1.455*15 +$GPGSV,2,1,8,3,23,303,34,16,32,219,27,22,74,98,26,25,16,43,25*78 +$GPGSV,2,2,8,26,70,236,28,31,59,12,37,32,55,127,34,4,5,,20*47 +$BDGSV,2,1,8,163,51,192,32,166,70,11,31,167,52,197,32,169,59,334,31*61 +$BDGSV,2,2,8,170,40,205,31,161,5,,31,164,5,,27,165,5,,29*59 +$GNRMC,022327.000,A,3149.324611,N,11706.921713,E,0.000,261.541,180222,,E,A*3F +$GNGGA,022327.000,3149.324611,N,11706.921713,E,1,12,1.013,-8.577,M,0,M,,*48 +$GNGLL,3149.324611,N,11706.921713,E,022327.000,A,A*43 +...... # 数据较多,省略 +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.837,1.120,1.456*11 +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.837,1.120,1.456*18 +$GPGSV,2,1,8,3,23,302,27,16,32,220,26,22,73,101,27,25,16,43,27*45 +$GPGSV,2,2,8,26,70,237,28,31,59,13,33,32,54,128,28,4,5,,24*44 +$BDGSV,2,1,8,163,51,192,33,166,71,11,35,167,52,198,33,169,59,334,34*6E +$BDGSV,2,2,8,170,40,205,32,161,5,,33,164,5,,28,165,5,,30*5F +$GNRMC,022507.000,A,3149.324768,N,11706.922344,E,0.000,261.541,180222,,E,A*31 +$GNGGA,022507.000,3149.324768,N,11706.922344,E,1,12,1.120,-8.794,M,0,M,,*48 +$GNGLL,3149.324768,N,11706.922344,E,022507.000,A,A*4D +$GNGSA,A,3,31,32,3,16,22,25,26,,,,,,1.837,1.120,1.455*12 +$GNGSA,A,3,163,166,167,169,170,,,,,,,,1.837,1.120,1.455*1B +$GPGSV,2,1,8,3,23,302,26,16,32,220,26,22,73,101,27,25,16,43,26*45 +$GPGSV,2,2,8,26,70,237,28,31,59,13,32,32,54,128,28,4,5,,24*45 +$BDGSV,2,1,8,163,51,192,24,166,71,11,35,167,52,198,33,169,59,334,34*68 +$BDGSV,2,2,8,170,40,205,31,161,5,,33,164,5,,28,165,5,,30*5C +$GNRMC,022508.000,A,3149.324754,N,11706.922338,E,0.002,261.541,180222,,E,A*38 +$GNGGA,022508.000,3149.324754,N,11706.922338,E,1,12,1.120,-8.750,M,0,M,,*4B +$GNGLL,3149.324754,N,11706.922338,E,022508.000,A,A*46 +$GNGSA,A,3,31,3 +``` + +## GNSS 定位数据介绍 + +```python +NMEA端口数据分类: + $GPGGA 卫星定位信息 + $GPGSA  卫星PRN数据 + $GPGSV  可视卫星信息 + $GPRMC 推荐定位信息 + $GPVTG  地面速度信息 + $GPDTM 大地坐标系信息 + $GPGNS  GNSS定位数据 +NMEA语句解析: +GSV 语句的基本格式如下: + + $GPGSV,(1),(2),(3),(4),(5),(6),(7),...,(4),(5),(6),(7)*hh(CR)(LF) + + 字段1:GSV 语句总数 + + 字段2:本句 GSV 的编号 + + 字段3:可见卫星的总数(00~12,前面的 0 也将被传输) + + 字段4:卫星编号(01~32,前面的 0 也将被传输) + + 字段5:卫星仰角(00~90 度,前面的 0 也将被传输) + + 字段6:卫星方位角(000~359 度,前面的 0 也将被传输) + + 字段7:信噪比(00~99dB,没有跟踪到卫星时为空)(就是常说的CN值) + +GGA 语句的基本格式如下: + + $GPGGA,(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)*hh(CR)(LF) + + 字段1:UTC 时间,hhmmss.sss,时分秒格式 + + 字段2:纬度ddmm.mmmm,度分格式(前导位数不足则补0) + + 字段3:纬度N(北纬)或S(南纬) + + 字段4:经度dddmm.mmmm,度分格式(前导位数不足则补0) + + 字段5:经度E(东经)或W(西经) + + 字段6:GPS状态,0=未定位,1=非差分定位,2=差分定位,3=无效PPS,6=正在估算 + + 字段7:正在使用的卫星数量(00 - 12)(前导位数不足则补0) + + 字段8:HDOP水平精度因子(0.5 - 99.9) + + 字段9:海拔高度(-9999.9 - 99999.9) + + 字段10:海拔高度单位,米 + + 字段11:地球椭球面相对大地水准面的高度 + + 字段12:地球椭球面相对大地水准面的高度单位,米 + +GSA 语句的基本格式如下: + + $GPGSA,(1),(2),(3),(3),,,,,,,,,,(3),(4),(5),(6),(7)*hh(CR)(LF) + + 字段1:定位模式,A=自动手动2D/3D,M=手动2D/3D + + 字段2:定位类型,1=未定位,2=2D定位,3=3D定位 + + 字段3:PRN码(伪随机噪声码),第1信道正在使用的卫星PRN码编号(00)(前导位数不足则补0)(最多12个) + + 字段4:PDOP综合位置精度因子(0.0 - 500.0) + + 字段5:HDOP综合位置精度因子(0.0 - 500.0) + + 字段6:VDOP水平精度因子(0.0 - 500.0) + + 字段7:卫星系统ID + +VTG语句的基本格式如下: + + $GPVTG,(1),(2),(3),(4),(5),(6),(7),(8),(9)*hh(CR)(LF) + + 字段1:运动角度,000 - 359,(前导位数不足则补0) + + 字段2:T=真北参照系 + + 字段3:运动角度,000 - 359,(前导位数不足则补0) + + 字段4:M=磁北参照系 + + 字段5:水平运动速度(0.00)(前导位数不足则补0) + + 字段6:N=节,Knots + + 字段7:水平运动速度(0.00)(前导位数不足则补0) + + 字段8:K=公里/时,km/h + + 字段9:状态指示 E(航迹推算) A(非DGPS) + +RMC语句的基本格式如下: + + $GPRMC,(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13)*hh(CR)(LF) + + 字段1:UTC时间,hhmmss.sss格式 + + 字段2:状态,A=定位,V=未定位 + + 字段3:纬度ddmm.mmmm,度分格式(前导位数不足则补0) + + 字段4:纬度N(北纬)或S(南纬) + + 字段5:经度dddmm.mmmm,度分格式(前导位数不足则补0) + + 字段6:经度E(东经)或W(西经) + + 字段7:速度,节,Knots + + 字段8:方位角,度 + + 字段9:UTC日期,DDMMYY格式 + + 字段10:磁偏角,(000 - 180)度(前导位数不足则补0) + + 字段11:磁偏角方向,E=东W=西 + + 字段12:状态指示 E(航迹推算) A(非DGPS) + + 字段13:导航状态,V 表示不提供导航状态 + +DTM语句的基本格式如下: + + $GNDTM,<1>,<2>,<3>,<4>,<5>,<6>,<7>,<8>*<9>(CR)(LF) + + <1>本地坐标系代码 W84,P90 + + <2>坐标系子代码 空 + + <3>纬度偏移量 + + <4>纬度半球N(北半球)或S(南半球) + + <5>经度偏移量 + + <6>经度半球E(东经)或W(西经) + + <7>高度偏移量 + + <8>坐标系代码 W84 + + <9>校验码 + +GNS语句的基本格式如下: + + $GNGNS,<1>,<2>,<3>,<4>,<5>,<6>,<7>,<8>.<9>,<10>,<11>,<12>,<13>,*<14>(CR)(LF) + + <1> UTC时间: 定位时间 hhmmss.ss——000000.00~235959.99 + + <2> 纬度: ddmm.mmmmm——0000.00000~8959.9999 + + <3> 南纬北纬: 北纬N,S南纬 + + <4>经度:dddmm.mmmmm——0000.00000~17959.99999 + + <5>东经西经: 东经E,西经W + + <6>定位模式: N-未定位;A-已定位;D-普通差分定位;P-高精度定位;R-RTK定位固定解;F-RTK定位浮点解;E-估算值;M-注入位置;S-模拟输入 + + <7>定位卫星:参与定位卫星,00-99 + + <8>HDOP:水平精度因子,0.5-99.9 + + <9>海拔:单位:米 + + <10>大地水准面: 地球椭球面相对大地水准面的高度 + + <11>差异数据时间:GN开头时为空 + + <12>基准站ID:GN开头时为空 + + <13>导航状态—— C=告警, S=安全, U=不安全, V=无效 + + <14>校验和 +``` + +## GNSS 功能初始化 + +### **`quecgnss.init`** + +```python +quecgnss.init() +``` + +模组内置GNSS模块功能的初始化。 + +**返回值描述** +成功返回整型 `0`,失败返回整型 `-1`。 + +## GNSS 工作状态获取 + +### **`quecgnss.get_state`** + +```python +quecgnss.get_state() +``` + +获取GNSS模块当前工作状态 + +**返回值描述** + +| 返回值 | 类型 | 说明 | +| ------ | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 | int | GNSS模块处于关闭状态 | +| 1 | int | GNSS模块固件升级中 | +| 2 | int | GNSS模块定位中,这种模式下即可开始读取GNSS定位数据,定位数据是否有效需要用户获取到定位数据后,解析对应语句来判断,比如判断GNRMC语句的status是 A 还是 V,A 表示定位有效,V 表示定位无效。 | + +## GNSS开关 + +### `quecgnss.gnssEnable` + +```python +quecgnss.gnssEnable(opt) +``` + +开启或者关闭GNSS模块。如果是上电后第一次使用内置GNSS功能,一般不需要调用该接口来开启GNSS功能,直接调用init()接口即可,init() 接口在初始化时会自动开启GNSS功能。 + +**参数描述** + +`opt`,int类型 + + `0` - 关闭GNSS功能 + + `1` - 开启GNSS功能 + +**返回值描述** + +成功返回整型 `0`,失败返回整型 `-1`。 + +## GNSS定位数据获取 + +### `quecgnss.read` + +```python +quecgnss.read(size) +``` + +读取GNSS定位数据。 + +**参数描述** + +`size`,int类型,指定读取数据的大小,单位字节。 + +**返回值描述** + +成功返回一个元组,失败返回整型-1。元组形式如下: +`(size, data)` +`size` - 实际读取数据的大小 +`data` - GNSS定位数据 + +## GNSS/LTE优先级设置 + +> 当前仅BG95M1/M3型号支持该功能。 + +### `quecgnss.setPriority` + +```python +quecgnss.setPriority(Priority) +``` + +在部分模组上,GNSS和LTE会复用射频资源,该接口用来控制GNSS和LTE之间使用射频资源的优先级 + +**参数描述** + +`Priority`,int类型,设定GNSS/LTE优先级的值。 + +不同平台GNSS/LTE优先级的对应关系: + +| 优先级 | BG95M1/M3 | +| ------ | -------- | +| 0 | GNSS>LTE | +| 1 | LTE>GNSS | + +**返回值描述** + +成功返回整型 `0`,失败返回整型 `-1`。 + +## GNSS/LTE优先级获取 + +> 当前仅BG95M1/M3型号支持该功能。 + +### `quecgnss.getPriority` + +```python +quecgnss.getPriority() +``` + +在部分模组上,GNSS和LTE会复用射频资源,该接口用来读取GNSS和LTE之间使用射频资源的优先级 + +**返回值描述** + +返回一个整型,代表GNSS/LTE优先级。 + +不同平台GNSS/LTE优先级的对应关系: + +| 优先级 | BG95M1/M3 | +| ------ | -------- | +| 0 | GNSS>LTE | +| 1 | LTE>GNSS | + +## 内置GNSS配置参数设置 + +> 当前仅EC800M GA/GB/GC/GD系列、EG810M GA系列 ECX00U AA/LA系列支持该功能 + +### `quecgnss.configSet` + +```python +quecgnss.configSet(config_type, config_value) +``` + +设置GNSS参数,包括卫星系统、NMEA语句类型、是否使用AGNSS和APFLASH等 + +**参数描述** + +* `config_type`,int,要设置的GNSS配置选项类型,含义如下: + +| 参数 | 类型 | +| ---- | ---------------------- | +| 0 | 配置使用的卫星系统 | +| 1 | 配置输出的NMEA语句类型 | +| 2 | 配置是否使能AGPS | +| 3 | 配置是否使能APFLASH | +| 4 | 配置是否使能GNSS备电 | + +* `config_value`,int,GNSS配置选项的值,含义如下: + +卫星系统(config_type = 0): + +| 参数 | 含义 | +| ---- | ----------------------- | +| 0 | GPS | +| 1 | GPS + BeiDou | +| 3 | GPS + GLONASS + Galileo | +| 4 | GPS + GLONASS | +| 5 | GPS + BeiDou + Galileo | +| 6 | GPS + Galileo | +| 7 | BeiDou | + +NMEA语句类型(config_type = 1):该项以bitmap表示,需要打开的选项置为1 +如需要输出GGA+RMC+GSV+GSA+VTG时,应使用bitmap(011111),换算为十进制为31 + +| 参数 | 含义 | +| ---- | ------------------------ | +| 0 | 禁止输出NMEA语句(000000) | +| 1 | GGA(000001) | +| 2 | RMC(000010) | +| 4 | GSV(000100) | +| 8 | GSA(001000) | +| 16 | VTG(010000) | +| 32 | GLL(100000) | +| 63 | 全部输出(111111) | + +是否使能AGPS(config_type = 2):打开该项时,GNSS会从网络下载星历,并在启动时尝试使用星历加速 + +| 参数 | 含义 | +| ---- | -------- | +| 0 | 关闭AGPS | +| 1 | 打开AGPS | + +是否使能APFLASH(config_type = 3):打开该项时,GNSS会在Quecpython模组保存星历,并在启动时尝试使用星历加速 + +| 参数 | 含义 | +| ---- | ----------- | +| 0 | 关闭APFLASH | +| 1 | 打开APFLASH | + +是否使能备电 (config_type = 4):打开该项并正确连接备电时,GNSS芯片可自行保存星历信息 + +>EC800M GB/GD系列支持备电 + +| 参数 | 含义 | +| ---- | ----------- | +| 0 | 关闭备电 | +| 1 | 打开备电 | + +**返回值描述** + +int,0为成功,否则为失败 + +## 内置GNSS配置参数读取 + +> 当前仅EC800M GA/GB/GC/GD系列、EG810M GA系列、ECX00U AA/LA系列支持该功能 + +### `quecgnss.configGet` + +```python +quecgnss.configGet(config_type) +``` + +读取GNSS参数,包括卫星系统、NMEA语句类型、是否使用AGNSS和APFLASH等 + +**参数描述** + +* `config_type`,int,要读取的GNSS配置选项类型,含义如下: + +| 参数 | 类型 | +| ---- | ---------------------- | +| 0 | 配置使用的卫星系统 | +| 1 | 配置输出的NMEA语句类型 | +| 2 | 配置是否使能AGPS | +| 3 | 配置是否使能APFLASH | +| 4 | 配置是否使能GNSS备电 | + +**返回值描述** + +int,含义如下(-1为失败) + +卫星系统(config_type = 0): + +| 参数 | 含义 | +| ---- | ----------------------- | +| 0 | GPS | +| 1 | GPS + BeiDou | +| 3 | GPS + GLONASS + Galileo | +| 4 | GPS + GLONASS | +| 5 | GPS + BeiDou + Galileo | +| 6 | GPS + Galileo | +| 7 | BeiDou | + +NMEA语句类型(config_type = 1):该项以bitmap表示,被打开的选项置为1 +如输出GGA+RMC+GSV+GSA+VTG时,返回的值为31,换算为二进制即为bitmap(011111) + +| 参数 | 含义 | +| ---- | ------------------------ | +| 0 | 禁止输出NMEA语句(000000) | +| 1 | GGA(000001) | +| 2 | RMC(000010) | +| 4 | GSV(000100) | +| 8 | GSA(001000) | +| 16 | VTG(010000) | +| 32 | GLL(100000) | +| 63 | 全部输出(111111) | + +是否使能AGPS(config_type = 2):打开该项时,GNSS会从网络下载星历,并在启动时尝试使用星历加速 + +| 参数 | 含义 | +| ---- | -------- | +| 0 | 关闭AGPS | +| 1 | 打开AGPS | + +是否使能APFLASH(config_type = 3):打开该项时,GNSS会在Quecpython模组保存星历,并在启动时尝试使用星历加速 + +| 参数 | 含义 | +| ---- | ----------- | +| 0 | 关闭APFLASH | +| 1 | 打开APFLASH | + +是否使能备电 (config_type = 4):打开该项并正确连接备电时,GNSS芯片可自行保存星历信息 + +>EC800M GB/GD系列支持备电 + +| 参数 | 含义 | +| ---- | ----------- | +| 0 | 关闭备电 | +| 1 | 打开备电 | \ No newline at end of file diff --git a/docs/API_reference/zh/gnsslib/wifiScan.md b/docs/API_reference/zh/gnsslib/wifiScan.md new file mode 100644 index 0000000000000000000000000000000000000000..20845700aec981680207f55f3336a8a4c8d638ba --- /dev/null +++ b/docs/API_reference/zh/gnsslib/wifiScan.md @@ -0,0 +1,203 @@ +# wifiScan - WiFi扫描 + +`wifiScan`模块提供了同步和异步两种方式来扫描模组周边的WiFi热点信息。 + + + +> 支持`wifiScan`功能的模组: +> +> EC100Y/EC200N/EC600N/EC600S/EC600M部分系列/EC800M部分系列/EC800N/EG912N/EG915N/EG810M/EC600G/EC800G/EC200U/EC600U部分系列/EG912U部分系列/EG915U部分系列模组。 +> +> EC600M系列模组中,支持的型号有:EC600MCN_LA/EC600MCN_LE/EC600MEU_LA; +> +> EC800M系列模组中,支持的型号有:EC800MCN_GA/EC800MCN_LA/EC800MCN_LE/EC800MCN_LF/EG810MCN_GA; +> +> EC600U系列模组中,支持的型号有:EC600UCN_LB/EC600UEU_AB; +> +> EC200U系列模组中,支持的型号有:EC200UAU_AA/EC200UAU_AB/EC200UCN_AA/EC200UCN_LA/EC200UCN_LB/EC200UEU_AA/EC200UEU_AB; +> +> EG912U系列模组中,支持的型号有:EG912UGL_AA; +> +> EG915U系列模组中,支持的型号有:EG915UEU_AB/EG915ULA_AB。 + + + +## 开启或关闭扫描功能 + +### `wifiScan.control` + +```python +wifiScan.control(option) +``` + +开启或者关闭WiFi扫描功能。 + +**参数描述:** + +* `option` - 控制选项,整型值,`0`表示关闭WiFi扫描功能,`1`表示开启WiFi扫描功能。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + +**示例:** + +```python +>>> import wifiScan +>>> wifiScan.control(1) # 开启 wifiScan 功能 +0 +>>> wifiScan.control(0) # 关闭 wifiScan 功能 +0 +``` + + + +### `wifiScan.getState` + +```python +wifiScan.getState() +``` + +获取WiFi扫描功能的当前状态是开启还是关闭。 + +**返回值描述:** + +WiFi扫描功能已开启则返回`True`,未开启返回`False`。 + + + +## 扫描参数配置与获取功能 + +### `wifiScan.setCfgParam` + +```python +wifiScan.setCfgParam(timeout, round, maxNums[, priority]) +``` + +设置WiFi扫描参数。 + +**参数描述:** + +* `timeout` - 超时时间,整型值;当触发超时会主动上报已扫描到的热点信息,若在超时前扫描到设置的热点个数会结束扫描并返回扫描结果。参数范围:4~60s。 +* `round` - 扫描轮数,整型值,达到扫描轮数后,会结束扫描并返回扫描结果。参数范围:1~3次。 +* `maxNums` - 最大扫描数量,整型值,当扫描热点数量达到设置的最大个数,会结束扫描并返回扫描结果。参数范围:4~30个。 +* `priority` - 扫描业务的优先级,整型值,可选参数,范围0~1。`0`表示网络业务优先,`1`表示WiFi扫描业务优先。网络业务优先时,当有数据业务发起时会中断WiFi扫描。WiFi扫描业务优先时,当有数据业务发起时,不会建立RRC连接,保障WiFi扫描正常执行,扫描结束后才会建立RRC连接。 + +**返回值描述:** + +返回一个整型值,`0`表示设置成功,`-1`表示设置失败。 + + + +> EC200U/EC600U/EG912U/EG915U/EC600G/EC800G系列模组不支持priority参数,使用时可不填该参数。 + + + +### `wifiScan.getCfgParam` + +```python +wifiScan.getCfgParam() +``` + +获取WiFi扫描参数。 + +**返回值描述:** + +成功返回一个元组,失败返回整型` -1`。返回值参数描述见`wifiScan.setCfgParam`方法的参数描述,返回元组格式如下: + +`(timeout, round, maxNums, priority)` + + + +## 回调注册功能 + +### `wifiScan.setCallback` + +```python +wifiScan.setCallback(fun) +``` + +注册回调函数。使用异步扫描时,需要注册回调函数,扫描结果通过回调函数返回给用户。 + +**参数描述:** + +* `fun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def wifiscanCallback(args): + pass +``` + +回调函数参数描述: + +| 参数 | 类型 | 含义 | +| ---- | ---- | ------------------------------------------------------------ | +| args | 元组 | 包含扫描到的WiFi热点数量和热点信息,形式如下:
`(nums, [(mac, rssi),...,(mac, rssi)])`
`nums` - 整型值,表示扫描到的热点数量
`mac` - 字符串类型,表示WiFi无线接入点的MAC地址
`rssi` - 整型值,表示WiFi热点信号强度 | + +**返回值描述:** + +返回一个整型值,`0`表示注册成功,`-1`表示注册失败。 + + + +## 启动扫描功能 + +### `wifiScan.asyncStart` + +```python +wifiScan.asyncStart() +``` + +开始异步扫描,扫描结果通过用户注册的回调函数返回。 + +**返回值描述:** + +返回一个整型值,`0`表示执行成功,`-1`表示执行失败。 + +**示例:** + +```python +import wifiScan + +def wifiscanCallback(args): + print('wifi list:{}'.format(args)) +wifiScan.setCallback(wifiscanCallback) + +wifiScan.control(1) +wifiScan.asyncStart() + +''' +执行结果: +wifi list:(2, [('F0:B4:29:86:95:C7', -79),('44:00:4D:D5:26:E0', -92)]) +''' +``` + + + +### `wifiScan.start` + +```python +wifiScan.start() +``` + +开始同步扫描,扫描结束后直接返回扫描结果。由于是同步接口,所以扫描未结束时,程序会阻塞在该接口中。 + +**返回值描述:** + +扫描成功时返回一个元组,失败返回整型`-1`。成功时返回值格式如下: + +`(wifiNums, [(mac, rssi), ... , (mac, rssi)])` + +| 参数 | 类型 | 说明 | +| -------- | ------ | ---------------------- | +| wifiNums | 整型 | 扫描到的 WiFi 热点数量 | +| mac | 字符串 | WiFi 热点的MAC地址 | +| rssi | 整型 | 信号强度 | + +**示例:** + +```python +>>> wifiScan.start() +(7, [('34:CE:00:09:E5:A8', -30), ('30:FC:68:E2:2D:F7', -44), ('12:CA:41:D4:B2:50', -54), ('D0:DB:B7:90:2D:07', -58), ('00:03:7F:12:CB:CB', -61), ('60:38:E0:C2:84:D9', -62), ('08:4F:0A:05:22:8F', -63)]) +``` + diff --git a/docs/API_reference/zh/gnsslib/wifilocator.md b/docs/API_reference/zh/gnsslib/wifilocator.md new file mode 100644 index 0000000000000000000000000000000000000000..f4aa3d3760fe094a216fcd95b7acb9c542358a4b --- /dev/null +++ b/docs/API_reference/zh/gnsslib/wifilocator.md @@ -0,0 +1,70 @@ +# class wifilocator - WIFI定位 + +该模块提供WIFI定位功能的类,获取模组经纬度坐标信息。 + + + +> 当前仅EC600S/EC600N/EC800N/EC200U/EC600U/EG912U/EG915U系列支持该功能。 + + + +**示例:** + +```python +>>> import wifilocator +# 创建wifilocato对象 +>>> wifiloc = wifilocator.wifilocator("xxxxxxxxxxxxxxxx") +# 获取模块坐标信息 +>>> wifiloc.getwifilocator() +(117.1152877807617, 31.82142066955567, 100) +# 上面使用的密钥"xxxxxxxxxxxxxxxx"指代token,具体需要向移远申请 +``` + + + +## 构造函数 + +### `wifilocator.wifilocator` + +```python +class wifilocator.wifilocator(token) +``` + +创建wifilocator对象,配置wifi定位套件token信息。 + +**参数描述:** + +- `token` - 密钥,字符串类型,16位字符组成,需要申请。 + + + +## 获取坐标信息 + +### `wifilocator.getwifilocator` + +```python +wifilocator.getwifilocator() +``` + +该方法用于获取模组经纬度坐标信息。 + +**返回值描述:** + +成功返回模组经纬度坐标信息,元组格式:`(longtitude, latitude, accuracy)`; + +`longtitude` : 经度 + +`latitude` :纬度 + +`accuracy` :精确度,单位米 + +失败返回错误码说明如下: + +`1` – 当前网络异常,请确认拨号是否正常 + +`2` – 密钥长度错误,必须为16字节 + +`3` – 获取坐标出错。 + + + diff --git a/docs/API_reference/zh/industry/README.md b/docs/API_reference/zh/industry/README.md new file mode 100644 index 0000000000000000000000000000000000000000..830b056b25b7932c0fc1c8748ff2ae05973f581e --- /dev/null +++ b/docs/API_reference/zh/industry/README.md @@ -0,0 +1,7 @@ +# 行业应用相关 API 参考手册 + +本部分介绍了 QuecPython 支持的部分行业相关的库的 API 用法,包括但不限于公网对讲机、电表等行业。后面会根据 QuecPython 支持更多的行业库而随之新增内容。 + +## QuecPython 行业相关库 + +- [POC - 公网对讲机](./poc.md) diff --git a/docs/API_reference/zh/industry/poc.md b/docs/API_reference/zh/industry/poc.md new file mode 100644 index 0000000000000000000000000000000000000000..9fceb862cc5009aa8817b2500bd755e65525797b --- /dev/null +++ b/docs/API_reference/zh/industry/poc.md @@ -0,0 +1,839 @@ +# poc - 对讲服务 + +该库对接的是伯纳德对讲平台,并且只能使用支持 PoC 功能的固件。 + +支持 PoC 功能的模组型号如下: + +| 系列 | 型号 | +| :----- | :----------------------------------------------------------- | +| EC600M | EC600MCN_LA、EC600MCN_LE、EC600MCN_LF、EC600MEU_LA、EC600MLA_LA | +| EC800M | EC800MCN_LA、EC800MCN_LE | +| EC600U | EC600UEU_AB | +| EC800G | EC800GCN_LD | + +> 💡 **Tips** +> - 非商业测试,请联系移远销售人员( li.bao@quectel.com ),申请伯纳德**芯平台**测试账号。 +> - 商业应用请走商务流程。 + +访问 [github 仓库](https://github.com/QuecPython/solution-POC/tree/EC600MCNLE-Demo)获取[示例代码](https://github.com/QuecPython/solution-POC/tree/EC600MCNLE-Demo/code)、[使用说明](https://github.com/QuecPython/solution-POC/blob/EC600MCNLE-Demo/readme.md)和[适用的固件](https://github.com/QuecPython/solution-POC/releases/)。 + + +## 导入 `poc` 模块 + +**代码示例:** + +```python +import poc +``` + +## 初始化 + +### `poc.init(init_cb)` + +该方法用于初始化 poc。 + +**参数描述:** + +- `init_cb` - 初始化回调函数,fun类型。用于通知用户 PoC 是否初始化成功。 + 函数原型:`init_cb(msg)`。 + - `msg` 表示初始化成功与否的结果。 + - `1` - 初始化成功; + - `0` - 初始化失败。 + +**代码示例:** + +```python +def init_cb(msg): + if msg: + print("poc init successfully.") + else: + print("poc init failed.") + +poc.init(init_cb) +``` + +### `poc.get_init_status()` + +该方法用于获取初始化状态。 + +**返回值描述:** + +- `1` - 已初始化; +- `0` - 未初始化。 + +## 参数设置 + +### `poc.set_solution(solution)` + +该方法用于设置方案名。 + +**参数描述:** + +- `solution` - 方案名,str 类型。 + 方案名用来记录本次方案的具体名称,用户可自行定义。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.set_solution_version(version)` + +该方法用于设置方案版本号。 + +**参数描述:** + +- `version` - 方案版本号,str 类型。 + 方案版本号用来记录本次方案的版本号,用户可自行定义。 + +**返回值描述:** + +- `0`- 成功; +- 其它 - 失败。 + +### `poc.set_productInfo(productInfo)` + +该方法用于设置产品信息。 + +**参数描述:** + +- `productInfo` - 产品信息,str 类型。 + 产品信息用来记录对讲产品的具体信息,用户可自行定义。 + +**返回值描述:** + +- `0`- 成功; +- 其它 - 失败。 + +### `poc.set_manufacturer(manufacturer)` + +该方法用于设置制造商信息。 + +**参数描述:** + +- `manufacturer` - 制造商信息,str 类型。 + 制造商信息用来记录对讲方案的制造商信息,用户可自行定义。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.set_notify_mode(value)` + +该方法用于设置通知模式。 + +**参数描述:** + +- `value` - 设置的通知模式,int 类型。 + - `0` - VOICE; + - `1` - TTS。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.set_ptt_status(status)` + +该方法用于设置 PTT 状态。 + +**参数描述:** + +- `status` - 设置 ppt 的状态值,int 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.speak_mode(mode)` + +该方法用于设置/查询语音处理模式。 + +#### 设置模式 + +**参数描述:** + +- `mode` - 需要设置的语音处理模式,int 类型。 + - `0` - 根据用户处理; + - `1` - 根据回调处理。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +#### 查询模式 + +**参数描述:** + +无参数。 + +**返回值描述:** + +当前设置的语音处理模式。 +- `0` - 根据用户处理; +- `1` - 根据回调处理。 + +### `poc.log(value)` + +该方法用于打开/关闭 log。 + +**参数描述:** + +- `value` - 设置 log 的模式,int 类型。 + - `0` - 关闭 log; + - `1` - 打开 log。 + +**返回值描述:** + +无。 + +### `poc.change_logininfo(account, pwd)` + +该方法用于更新登录信息。 + +**参数描述:** + +- `account` - 用户登录账户,str 类型; +- `pwd` - 用户登录密码,str 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +## 参数查询 + +### `poc.member_getbyid(uid)` + +该方法用于查询用户信息。 + +**参数描述:** + +- `uid` - 被查询用户的 id,int 类型。 + 若为`0`,则查询当前用户信息。 + +**返回值描述:** + +列表:`[uid, user_name, online_sta, index]` +- `uid` - 被查询用户的 id,int 类型; +- `user_name` - 被查询用户的名称,str 类型; +- `online_sta` - 被查询用户的在线状态, int 类型; + - `1` - 在线; + - `2` - 离线; + - `3` - 在线在组。 +- `index` - 被查询用户的索引号,int 类型。 + +### `poc.get_loginstate()` + +该方法用于查询当前用户在线状态。 + +**返回值描述:** + +- `1` - 在线; +- `2` - 离线; +- `3` - 在线在组。 + +### `poc.get_logininfo()` + +该方法用于获取登录信息。 + +**返回值描述:** + +元组:`(account, pwd)` +- `account` - 用户登录账户,str 类型; +- `pwd` - 用户登录密码,str 类型。 + +### `poc.get_version()` + +该方法用于获取对讲平台的版本信息。 + +**返回值描述:** + +获取到的版本信息,str 类型。 + +### `poc.ptt_cfg()` + +该方法用于获取用户用来呼叫的 PTT 按键信息。 + +**返回值描述:** + +列表:`[key_type, gpio_num, level]` +- `key_type` - PTT 按键对应的按键类型,int 类型; + - `1` - 普通 GPIO 按键; + - `2` - 键盘按键。 +- `gpio_num` - PTT 按键对应的 GPIO 引脚号,int 类型; +- `level` - PTT 按键对应引脚号的电平状态,int 类型。 + - `0` - 低电平; + - `1` - 高电平。 + +### `poc.current_zone_time(zone)` + +该方法用于获取某个时区的当前时间。 + +**参数描述:** + +- `zone` - 需要获取时间的时区,int 类型。 + +**返回值描述:** + +元组:`(year, month, day, hour, minute, second, millisecond, zone)` +- `year` - 年; +- `month` - 月; +- `day` - 日; +- `hour` - 时; +- `minute` - 分; +- `second` - 秒; +- `millisecond` - 毫秒; +- `zone` - 查询时间的时区。 + +### `poc.send_ping()` + +该方法用于发送 ping 请求。 + +**返回值描述:** + +- `0` - 成功; +- 其他 - 失败。 + +## 登录对讲平台 + +### `poc.login(login_cb)` + +该方法用于登录对讲平台。 + +**参数描述:** + +- `login_cb` - 登录状态回调函数,fun 类型。用于通知用户对讲平台是否登录成功。 + 函数原型:`login_cb(msg)`。 + - `msg` 表示初始化成功与否的结果。 + - `1` - 已登录; + - `0` - 未登录。 + +**返回值描述:** + +- `0` - 成功; +- 小于`0` - 失败。 + +## 退出对讲平台 + +### `poc.logout()` + +该方法用于退出对讲平台。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +## 呼叫 + +### `poc.speak(ctrl)` + +该方法用于呼叫组内用户。 + +**参数描述:** + +- `ctrl` - 控制组内呼叫行为。 + - `1` - 呼叫; + - `0` - 退出呼叫。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.calluser(uid, cb)` + +该方法用于呼叫指定用户。 + +**参数描述:** + +- `uid` - 对方用户 id,int 类型。 +- `cb` - 单呼回调,fun 类型。 + 函数原型:`cb(msg)`。 + - `msg` 表示呼叫指定用户是否成功。 + - `1` - 呼叫成功; + - `0` - 呼叫失败。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +## 群组管理 + +### `poc.jiongroup(gid)` + +该方法用于设备进入群组。 + +**参数描述:** + +- `gid` - 群组 id,int 类型。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.leavegroup()` + +该方法用于设备离开当前群组。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.get_groupcount()` + +该方法用于获取群组数。 + +**返回值描述:** + +群组个数,int 类型。 + +### `poc.get_grouplist(index_begin, count)` + +该方法用于查询群组信息。 + +**参数描述:** + +- `index_begin` - 查询的索引起始值,int 类型; +- `count` - 计划查询的个数,int 类型。 + +**返回值描述:** + +- `-1` - 失败; +- 元组 - 成功,定义为:`(gid, group_name, group_type, index)` + - `gid` - 被查询的群组 id,int 类型; + - `group_name` - 被查询的群组名,str 类型; + - `group_type` - 被查询的群组类型,str 类型; + - `index` - 被查询的群组索引号,int 类型。 + +### `poc.group_getbyindex(index)` + +该方法用于按索引查询群组信息。 + +**参数描述:** + +- `index` - 被查询群组的索引号,int 类型。 + +**返回值描述:** + +列表:`[gid, group_name, group_type, index]` +- `gid` - 被查询的群组 id,int 类型; +- `group_name` - 被查询的群组名,str 类型; +- `group_type` - 被查询的群组类型,str 类型; +- `index` - 被查询的群组索引号,int 类型。 + +### `poc.group_getbyid(gid)` + +该方法用于按组 id 查询群组信息。 + +**参数描述:** + +- `gid` - 群组 id,int 类型。 + 若为 `0`,则查询当前群组信息。 + +**返回值描述:** + +列表:`[gid, group_name, group_type, index]` +- `gid` - 被查询的群组 id,int 类型; +- `group_name` - 被查询的群组名,str 类型; +- `group_type` - 被查询的群组类型,str 类型; +- `index` - 被查询的群组索引号,int 类型。 + +### `poc.get_membercount(gid)` + +该方法用于查询群组内成员个数。 + +**参数描述:** + +- `gid` - 群组 id,int 类型。 + +**返回值描述:** + +成员个数,int 类型。 + +### `poc.get_memberlist(gid, index_begin, count)` + +该方法用于获取群组内成员列表。 + +**参数描述:** + +- `gid` - 群组 id,int 类型; +- `index_begin` - 查询的索引起始值,int 类型; +- `count` - 计划查询的个数,int 类型。 + +**返回值描述:** + +- `-1`- 失败; +- 元组 - 成功,定义为:`(uid, user_name, online_sta, priority, index)` + - `uid` - 组内用户的 id,int 类型; + - `user_name` - 组内用户的名称,str 类型; + - `online_sta` - 组内用户的在线状态, int 类型。 + - `1` - 在线; + - `2` - 离线; + - `3` - 在线在组。 + - `priority` - 组内用户呼叫的优先级,int 类型。 + - `index` - 用户索引号,int 类型。 + +## 音频播放管理 + +### `poc.get_audiostate()` + +该方法用于获取当前音频状态。 + +**返回值描述:** + +- `0` - 空闲; +- `1` - 开始通话; +- `2` - 通话中; +- `3` - 停止通话; +- `4` - 开始接听; +- `5` - 接听中; +- `6` - 停止接听; +- `7` - 开始播放tts; +- `8` - 停止播放tts; +- `9` - 开始播放提示音; +- `10` - 停止播放提示音; +- `11` - 开始录音; +- `12` - 结束录音。 + +### `poc.set_tts_enable(enable)` + +该方法用于使能 tts。 + +**参数描述:** + +- `enable` - 是否使能 tts,int 类型。 + - `1`:使能; + - `0`:不使能。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.play_tts(tts_str, interrupt)` + +该方法用于播放 tts。 + +**参数描述:** + +- `tts_str` - tts 播放的内容,str 类型。 +- `interrupt` - 是否可以被打断,int 类型。 + - `1`:表示中断当前 tts 播放; + - `0`:表示不中断当前 tts 播放。 + +**返回值描述:** + +- `0` - 成功; +- 其它 - 失败。 + +### `poc.set_vol(type, vol)` + +该方法用于设置音量。 + +**参数描述:** + +- `type` - 设置音量的类型,int 类型。 + - 0 - VOICE; + - 1 - TTS; + - 2- TONE。 +- `vol` - 音量大小,int 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.get_vol(type)` + +该方法用于获取音量。 + +**参数描述:** + +- `type` - 获取音量的类型,int 类型。 + - 0 - VOICE; + - 1 - TTS; + - 2- TONE。 + +**返回值描述:** + +音量的大小,int 类型。 + +## 回调注册 + +### `poc.register_join_group_cb(cb)` + +该方法用于注册入组回调。 + +**参数描述:** + +- `cb` - 进组回调,触发源包括主动进组和被动进组,fun 类型。用于通知用户设备是否成功进入群组。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[group_name, gid]`。 + - `group_name` - 当前群组的名字; + - `gid` - 当前群组的 id。 + +### `poc.register_audio_cb(poc_audio_cb)` + +该方法用于注册音频回调。 + +**参数描述:** + +- `poc_audio_cb` - 音频回调,fun 类型。用于通知用户当前的音频信息。 + 函数原型:`poc_audio_cb(msg)`。 + - `msg`为一个列表:`[state, uid, name, flag]`。 + - `state` - 当前语音状态:收听/讲话/TTS/TONE; + - `uid` - 当前操作用户 id,讲话/TTS/TONE时为0; + - `name` - 当前操作用户名字,讲话/TTS/TONE时为NULL; + - `flag` - 如果 state 为 BND_LISTEN_START,flag 为 `1` 表示本机可以打断对方讲话,flag 为 `0` 表示本机不能打断对方讲话。 + +### `poc.register_listupdate_cb(poc_listupdate_cb)` + +该方法注册数据更新回调。 + +**参数描述:** + +- `poc_listupdate_cb` - 数据变化的回调函数,fun 类型。用于通知用户当前数据变化的信息。 + 函数原型:`poc_listupdate_cb(msg)`。 + - `msg`表示列表变化的对象。 + - `1` - 群组列表变化; + - `2` - 成员列表变化。 + +### `poc.register_upgrade_cb(cb)` + +该方法用于注册是否升级的回调。 + +**参数描述:** + +- `cb` - 升级回调函数,fun 类型。用于通知用户是否需要升级。 + 函数原型:`cb(msg)`。 + - `msg`表示是否需要升级。 + - `1` - 需要升级; + - `0` - 不需要升级。 + +### `poc.register_cell_location_change_cb(cb)` + +该方法用于注册位置信息变化回调。 + +**参数描述:** + +- `cb` - 位置信息变化回调,fun 类型。用于通知用户位置信息发生变化。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[location_switch, report_rate]`。 + - `location_switch` - 位置开关的状态,int 类型; + - `report_rate` - 报告频率,int 类型。 + +### `poc.register_error_cb(cb)` + +该方法用于注册异常错误信息的回调。 + +**参数描述:** + +- `cb` - 异常错误信息回调,fun 类型。用于通知用户发生异常错误。 + 函数原型:`cb(info)`。 + - `info`为异常错误信息。 + +### `poc.register_recv_report_sos_ack_cb(cb)` + +该方法用于注册 sos 确认回调。 + +**参数描述:** + +- `cb` - sos 确认回调,fun 类型。用于通知用户 sos 请求的确认结果。 + 函数原型:`cb(result)`。 + - `result`为确认结果。 + - `0` - 成功; + - 其它 - 失败。 + +### `poc.register_recv_report_sos_ack_timeout_cb(cb)` + +该方法用于注册 sos 超时回调。 + +**参数描述:** + +- `cb` - sos 超时回调,fun 类型。用于通知用户 sos 请求回复超时。 + 函数原型:`cb(msg)`。 + - `msg`为超时信息。 + +### `poc.register_recv_sos_alarm_cb(cb)` + +该方法用于注册 sos 报警回调。 + +**参数描述:** + +- `cb` - sos 报警回调,fun 类型。用于通知用户某一用户正在发送 sos 请求。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[uid, uuid, lon, lat, gid]`。 + - `uid` - 用户 id,即请求者 id,int 类型; + - `uuid` - sos 唯一标识,int 类型; + - `lon` - 经度,double 类型; + - `lat` - 维度,double 类型; + - `gid` - 群组 id,即请求者当前在哪个群组,int 类型。 + +### `poc.register_recv_sos_info_cb(cb)` + +该方法用于注册 sos 请求信息回调。 + +**参数描述:** + +- `cb` - sos 请求信息回调,fun 类型。用于通知用户发送的 sos 请求信息。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[name, timestamp, lon, lat]`。 + - `name` - 请求者名称,str 类型; + - `timestamp` - 请求时间,时间戳形式,str 类型; + - `lon` - 经度,double 类型; + - `lat` - 维度,double 类型。 + +### `poc.register_request_invite_ack_cb(cb)` + +该方法用于注册邀请请求的回调。 + +**参数描述:** + +- `cb` - 邀请请求回调,fun 类型。用于通知用户邀请请求的结果。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[invite_id, result, invites, invites_count, reason]`。 + - `invite_id` - 邀请 id,用于唯一标识一个邀请请求,int类型; + - `result` - 邀请结果,int 类型; + - `0` - 正常拒绝; + - `1` - 接受邀请; + - `2` - 免打扰。 + - `invites` - 一个包含多个邀请 id 的数组; + - `invites_count` - invites 数组中的元素个数,int 类型; + - `reason` - 对方拒绝原因,int 类型。 + - `2` - 对方不支持; + - `1` - 对方正在讲话,或者对方不允许被呼叫等错误。 + +### `poc.register_sos_status_cb(cb)` + +该方法用于注册 sos 状态变化回调。 + +**参数描述:** + +- `cb` - sos 状态变化回调,fun 类型。用于通知用户 sos 的状态。 + 函数原型:`cb(state)`。 + - `state`为 sos 的状态。 + - `0` - 成功; + - `1` - 错误; + - `2` - 超时; + - `3` - 没有启用 sos 请求。 + +### `poc.register_recv_broadcast_info_cb(cb)` + +该方法用于注册广播播报信息回调。 + +**参数描述:** + +- `cb` - 广播信息回调,fun 类型。用于播报 TTS 信息。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[flag, tts]`。 + - `flag` - 控制广播播报,int类型; + - `1` - 开始播放广播; + - `0` - 停止播放广播。 + - `tts` - 播报的 tts 信息,str类型。 + +### `poc.register_recv_enclosure_alarm_cb(cb)` + +该方法用于注册接收警报回调。 + +**参数描述:** + +- `cb` - 接收警报回调,fun 类型。用于通知用户警报信息。 + 函数原型:`cb(msg)`。 + - `msg`为一个列表:`[alarm, tips]`。 + - `alarm` - 警报类型,int 类型; + - `1` - 越界; + - `0` - 消除。 + - `tips` - 警报提示信息,str 类型。 + +## sos 功能 & 位置信息 + +### `poc.sos_start(lon, lat)` + +该方法用于启动 sos 功能,适用于国内伯纳德平台。 + +**参数描述:** + +- `lon` - 经度,double 类型; +- `lat` - 纬度,double 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.report_sos(lon, lat, time, alt, speed, dirang)` + +该方法用于发送 sos,适用于海外伯纳德平台和国内、外善理平台。 + +**参数描述:** + +- `lon` - 经度,double 类型; +- `lat` - 纬度,double 类型; +- `time` - 时间,str 类型; +- `alt` - 海拔,double 类型; +- `speed` - 速度,double 类型; +- `dirang`- 方向,double 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 内部错误; +- `-2` - 发送 sos 频繁。 + +### `poc.query_sos_map(w, h, lon, lat)` + +该方法用于查询 sos 地图。 + +**参数描述:** + +- `w` - 宽度,int 类型; +- `h` - 高度,int 类型; +- `lon` - 经度,double 类型; +- `lat` - 纬度,double 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.send_gpsinfo(lon, lat, time, alt, speed, dirang)` + +该方法用于发送定位信息。 + +**参数描述:** + +- `lon` - 经度,double 类型; +- `lat` - 纬度,double 类型; +- `time` - 定位时间,包括(年、月、日、时、分、秒、毫秒),str 类型; +- `alt` - 海拔,double 类型; +- `speed` - 速度,double 类型; +- `dirang`- 方向,double 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 + +### `poc.request_lbs_info(w, h, lon, lat)` + +该方法用于请求位置信息。 + +**参数描述:** + +- `w` - 宽度,int 类型; +- `h` - 高度,int 类型; +- `lon` - 经度,double 类型; +- `lat` - 纬度,double 类型。 + +**返回值描述:** + +- `0` - 成功; +- `-1` - 失败。 \ No newline at end of file diff --git a/docs/API_reference/zh/iotlib/README.md b/docs/API_reference/zh/iotlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f69421c451d2f31421bc87b9059c35c82e1b0330 --- /dev/null +++ b/docs/API_reference/zh/iotlib/README.md @@ -0,0 +1,16 @@ +# QuecPython 蜂窝通信 + +> QuecPython 蜂窝通信库包括所有蜂窝通信相关的功能组件 + +本文描述了 QuecPython 蜂窝通信库中的模块。 + +## QuecPython 蜂窝通信库列表 + +- [dataCall - 拨号](./dataCall.md) +- [sim - SIM卡功能](./sim.md) +- [sms - 短信功能](./sms.md) +- [voiceCall - 电话功能](./voiceCall.md) +- [net - 网络相关功能](./net.md) +- [checkNet - 网络就绪检测](./checkNet.md) +- [ussd - USSD功能](./ussd.md) + diff --git a/docs/API_reference/zh/iotlib/checkNet.md b/docs/API_reference/zh/iotlib/checkNet.md new file mode 100644 index 0000000000000000000000000000000000000000..9dc1293ebf949dba3a2100da720b8d28010ac7ac --- /dev/null +++ b/docs/API_reference/zh/iotlib/checkNet.md @@ -0,0 +1,90 @@ +# checkNet - 网络检测 + +`checkNet`模块提供了方法来检测模组的网络状态是否已经就绪,同时提供了网络异常的排查方法与步骤。 + + + +## 等待网络就绪 + +### `checkNet.waitNetworkReady` + +```python +checkNet.waitNetworkReady(timeout) +``` + +等待模组网络就绪。该方法会依次检测SIM卡状态、模组网络注册状态和PDP Context激活状态;在设定的超时时间之内,如果检测到PDP Context激活成功,会立即返回,否则直到超时才会退出。 + +**参数描述:** + +* `timeout` - 超时时间,整型值,范围1~3600秒,默认`60`秒。 + +**返回值描述:** + +返回一个元组,格式为:`(stage, state)` + +| 参数 | 类型 | 含义 | +| ----- | ---- | ------------------------------------------------------------ | +| stage | 整型 | 表示当前正在检测什么状态:
1 - 正在检测SIM卡状态;
2 - 正在检测网络注册状态;
3 - 正在检测PDP Context激活状态。 | +| state | 整型 | 根据stage值,来表示不同的状态,具体如下:
stage = 1时,state表示 SIM卡的状态,范围0-21,每个状态值的详细说明,请参考[`sim.getStatus()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sim.html#sim.getStatus)方法的返回值说明;
stage = 2时,state表示网络注册状态,范围0-11,每个状态值的详细说明,请参考[`net.getState()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getState%3C/code%3E)方法的返回值说明;
stage = 3时,state表示PDP Context激活状态,0表示没有激活成功,1表示激活成功。 | + +如果网络已经就绪,则返回`(3,1)`,否则可参考如下说明来排查定位问题: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
stage + state + 说明 +
10说明没插卡,或者卡槽松动,需要用户去检查确认。
其他值请参考官方wiki文档中关于sim卡状态值的描述,确认sim卡当前是哪种状态。
2-1这种情况说明在超时时间内,获取模组网络注册状态的API一直执行失败,在确认SIM卡可正常使用且能正常被模组识别的前提下,可联系我们的FAE反馈问题。
0或2这种情况说明在超时时间内,模组一直没有注网成功,这时请按如下步骤排查问题:
(1)首先确认SIM卡状态是正常的,通过 sim 模块的sim.getStatus()接口获取,为1说明正常;
(2)如果SIM卡状态正常,确认当前信号强度,通过net模块的net.csqQueryPoll()接口获取,如果信号强度比较弱,那么可能是因为当前信号强度较弱导致短时间内注网不成功,可以增加超时时间或者换个信号比较好的位置再尝试;
(3)如果SIM卡状态正常,信号强度也较好,请确认使用的SIM卡是否已经欠费或流量不足;
(4)如果SIM卡没有欠费也没有流量不足,请确认使用的是否是物联网卡,如果是,请确认该SIM卡是否存在机卡绑定的情况;
(5)如果按照前述步骤依然没有发现解决问题,请联系我们的FAE反馈问题;最好将相应SIM卡信息,比如哪个运营商的卡、什么类型的卡、卡的IMSI等信息也一并提供,必要时可以将SIM卡寄给我们来排查问题。
其他值请参考官方Wiki文档中net.getState()接口的返回值说明,确认注网失败原因。
30这种情况说明在超时时间内,PDP Context一直没有激活成功,请按如下步骤尝试:
(1)通过 sim 模块的sim.getStatus()接口获取sim卡状态,为1表示正常;
(2)通过 net 模块的net.getState()接口获取注网状态,为1表示正常;
(3)手动调用dataCall.activate(profileID)接口尝试激活,看看能否激活成功;
(4)如果手动激活成功了,但是开机自动激活失败,可联系我司相关人员协助分析。
1这是正常返回情况,说明网络已就绪,可进行网络相关业务操作。
+ + + + + + + + +**示例:** + +```python +import checkNet + +if __name__ == '__main__': + stage, state = checkNet.waitNetworkReady(30) + if stage == 3 and state == 1: + print('Network connection successful.') + else: + print('Network connection failed, stage={}, state={}'.format(stage, state)) +``` + diff --git a/docs/API_reference/zh/iotlib/dataCall.md b/docs/API_reference/zh/iotlib/dataCall.md new file mode 100644 index 0000000000000000000000000000000000000000..c602ef33f02144cd43bb7fe753666e92908bf94c --- /dev/null +++ b/docs/API_reference/zh/iotlib/dataCall.md @@ -0,0 +1,442 @@ +# dataCall - 拨号功能 + +拨号,指的是PDP Context的激活操作,激活成功后,核心网的PDN网关才会分配一个IP地址给模组。 + +`dataCall`模块包含了PDP Context配置和获取、激活、去激活以及获取模组的IP信息等功能。模组烧录QuecPython的固件,开机后,默认会自动执行拨号。如果用户配置了APN,则使用用户配置的APN信息进行拨号;否则使用默认APN进行拨号。 + + + +> 用户使用不同运营商的SIM卡时,应配置对应运营商的APN信息;如果不配置或者配置错误,可能会导致模组注网失败或拨号失败,模组获取不到IP地址,无法上网。配置APN的方式,参考[`dataCall.setPDPContext`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setPDPContext%3C/code%3E)方法。 + + + +**示例:** + +```python +import dataCall +from misc import Power + +# 用户需要配置的APN信息,根据实际情况修改 +usrConfig = {'apn': '3gnet', 'username': '', 'password': ''} + +# 获取第一路的APN信息,确认当前使用的是否是用户指定的APN +pdpCtx = dataCall.getPDPContext(1) +if pdpCtx != -1: + if pdpCtx[1] != usrConfig['apn']: + # 如果不是用户需要的APN,使用如下方式配置 + ret = dataCall.setPDPContext(1, 0, usrConfig['apn'], usrConfig['username'], usrConfig['password'], 0) + if ret == 0: + print('APN 配置成功。') + # 重启后按照配置的信息进行拨号 + Power.powerRestart() + else: + print('APN 配置失败。') + else: + print('APN 已经配置过了。') +else: + print('获取PDP Context失败。') +``` + + + +## APN配置与获取功能 + +### `dataCall.setPDPContext` + +``` +dataCall.setPDPContext(profileID, ipType, apn, username, password, authType) +``` + +配置PDP Context相关信息,配置信息掉电保存。拨号时使用该方法配置的参数进行PDP Context激活。 + +**参数描述:** + +* `profileID` - PDP上下文ID,整型值,范围1~3,一般设置为`1`。 +* `ipType` - IP协议类型,整型值,取值范围见下表: + +| 值 | 含义 | +| ---- | ---------- | +| 0 | IPv4 | +| 1 | IPv6 | +| 2 | IPv4和IPv6 | + +- `apn` - 接入点名称,全称Access Point Name,字符串类型,可为空,为空直接写`''`,范围0~64字节。 + +- `username` - 用户名,字符串类型,可为空,为空直接写`''`,范围0~64字节。 + +- `password` - 密码,字符串类型,可为空,为空直接写`''`,范围0~64字节。 + +- `authType` - APN鉴权方式,整型值,取值范围见下表枚举: + +| 值 | 含义 | +| ---- | --------- | +| 0 | 表示无 | +| 1 | PAP | +| 2 | CHAP | +| 3 | PAP和CHAP | + +**返回值描述:** + +返回一个整型值,`0`表示设置成功,`-1`表示设置失败。 + + + +> 关于BG95系列的profileID参数范围,在NB网络制式下,实际只支持1~2。 +> +> 关于authType参数,仅BG95系列模组支持值3。当设置username, password为非空字符串,authType又为`0`会自动变成`2`;当设置username,password为空字符串,authType又为`非0`会自动变成`0`。 +> +> 由于LTE网络第一路是在注网阶段完成,当更改第一路`ipType` 类型时,需要执行cfun0/1或重启才会生效。 +> +> BC32系列需要在cfun=0的情况下进行配置,且仅支持第一路。 +> +> BC32系列`apn`,`username` ,`password` 的长度范围为0~36字节。 +> +> BG95系列`apn` 的长度范围为0~63字节,且当authType为非0时,不允许 username, password为空字符串。 +> +> 支持该方法的模组:
EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.setPDPContext(1, 0, '3gnet', '', '', 0) +0 +``` + + + +### `dataCall.getPDPContext` + +```python +dataCall.getPDPContext(profileID) +``` + +获取`profileID`对应的那一路PDP Context相关信息。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + + +**返回值描述:** + +获取失败时,返回一个整型值`-1`;获取成功时,返回一个元组,包含PDP Context相关信息,格式如下: + +`(ipType, apn, username, password, authType)` + +元组参数描述见[`dataCall.setPDPContext`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setPDPContext%3C/code%3E)方法的参数描述。 + + + +>支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.getPDPContext(1) +(0, '3gnet', '', '', 0) +``` + + + +## 开机自动拨号功能 + +### `dataCall.setAutoActivate` + +```python +dataCall.setAutoActivate(profileID, enable) +``` + +设置`profileID`指定的那一路开机是否自动进行PDP Context激活。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + +- `enable` - 控制模组是否在开机时自动进行PDP Context激活,整型值,`0`表示关闭,`1`表示使能。 + + + +>如果用户没有使用[`dataCall.setAutoActivate`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setAutoActivate%3C/code%3E)方法和[`dataCall.setAutoConnect`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setAutoConnect%3C/code%3E)配置过,则默认开机对profileID为1的那一路进行自动激活和使能重连;否则按照用户的配置执行。 +> +>BC32系列仅支持第一路,不支持多路拨号。 +> +>支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.setAutoActivate(1, 0) # 关闭profileID为1的那一路开机自动激活PDP Context功能 +>>> dataCall.setAutoActivate(1, 1) # 开启profileID为1的那一路开机自动激活PDP Context功能 +``` + + + +## 拨号自动重连功能 + +### `dataCall.setAutoConnect` + +```python +dataCall.setAutoConnect(profileID, enable) +``` + +设置`profileID`指定的那一路是否使能自动重连功能。自动重连功能是指,因网络异常、信号差等异常场景导致模组与网络断开连接,当异常场景恢复正常后,模组自动进行拨号重连的行为。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + +- `enable` - 控制是否使能自动重连,整型值,`0`表示关闭,`1`表示使能。 + + + +> 如果用户没有使用[`dataCall.setAutoActivate`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setAutoActivate%3C/code%3E)方法和[`dataCall.setAutoConnect`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setAutoConnect%3C/code%3E)配置过,则默认开机对profileID为1的那一路进行自动激活和使能重连;否则按照用户的配置执行。 +> +> BC32系列2G网络下不支持重连功能。 +> +> 支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.setAutoConnect(1, 0) # 关闭profileID为1的那一路自动重连功能 +>>> dataCall.setAutoConnect(1, 1) # 开启profileID为1的那一路自动重连功能 +``` + + + +## DNS配置功能 + +### `dataCall.setDNSServer` + +```python +dataCall.setDNSServer(profileID, simID, priDNS, secDNS) +``` + +配置DNS服务器地址。模组拨号成功后,会自动获取DNS服务器地址,一般无需用户再重新配置。如模组自动获取的DNS服务器地址不可用,可使用该方法重新配置。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + +- `simID` - SIM卡卡槽编号,整型值,`0`表示SIM0,`1`表示SIM1,目前仅支持`0`。 + +- `priDNS` - 主要DNS服务器地址,字符串类型。 + +- `secDNS` - 辅助DNS服务器地址,字符串类型。 + +**返回值描述:** + +返回一个整型值,`0`表示配置成功,`-1`表示配置失败。 + + + +>支持该方法的模组: +> +>EC600N/EC800N/EG912N/EG915N/EC200A/EC200U/EC600U/EG912U/EG915U系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.setDNSServer(1, 0, "8.8.8.8", "114.114.114.114") +0 +``` + + + +## 回调注册功能 + +### `dataCall.setCallback` + +```python +dataCall.setCallback(fun) +``` + +注册回调函数。当网络状态发生变化时,如网络断开、拨号重连成功时,会触发注册的回调函数,告知用户网络状态。 + +**参数描述:** + +* `fun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def netCallback(args): + pass +``` + +| 参数 | 类型 | 含义 | +| ------- | ---- | ------------------------------------------------ | +| args[0] | 整型 | PDP上下文ID,表示当前是哪一路PDP网络状态发生变化 | +| args[1] | 整型 | 网络状态,0表示网络断开,1表示网络连接成功 | + +**返回值描述:** + +返回一个整型值,`0`表示注册成功,`-1`表示注册失败。 + + + +> 支持该方法的模组: +> +> EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95系列。 + + + +**示例:** + +```python +import dataCall + +def netCallback(args): + pdp = args[0] + datacallState = args[1] + if datacallState == 0: + print('### network {} disconnected.'.format(pdp)) + elif datacallState == 1: + print('### network {} connected.'.format(pdp)) + +dataCall.setCallback(netCallback) +``` + + + +## 激活与去激活功能 + +### `dataCall.activate` + +``` +dataCall.activate(profileID) +``` + +激活`profileID`指定的那一路PDP Context。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + + +**返回值描述:** + +返回一个整型值,`0`表示激活成功,`-1`表示激活失败。 + + + +> 模组会在开机时自动进行PDP Context激活,一般不需要用户执行激活操作。如用户关闭了开机自动进行PDP Context激活的功能,则需要用户调用此方法来进行PDP Context激活操作。 +> +> BC32系列仅支持第一路,不支持多路拨号。 +> +> 支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32系列。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.setPDPContext(1, 0, '3gnet', '', '', 0) # 激活之前,应该先配置APN,这里配置第1路的APN +0 +>>> dataCall.activate(1) # 激活第1路 +0 +``` + + + +### `dataCall.deactivate` + +``` +dataCall.deactivate(profileID) +``` + +去激活`profileID`指定的那一路PDP Context。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 + +**返回值描述:** + +返回一个整型值,`0`表示去激活成功,`-1`表示去激活失败。 + + + +> 支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95系列。 + + + +## 获取拨号信息功能 + +### `dataCall.getInfo` + +```python +dataCall.getInfo(profileID, ipType) +``` + +获取拨号信息,包括拨号状态、IP地址、DNS服务器地址等。 + +**参数描述:** + +- `profileID` - PDP上下文ID,整型值,范围1~3。 +- `ipType` - IP协议类型,整型值,取值范围见下表: + +| 值 | 含义 | +| ---- | ---------- | +| 0 | IPv4 | +| 1 | IPv6 | +| 2 | IPv4和IPv6 | + +**返回值描述:** + +获取失败返回整形值`-1`,获取成功返回一个元组,包含拨号信息,具体说明如下: + +`ipType`为0或1,返回值格式为: + +`(profileID, ipType, [state, reconnect, addr, priDNS, secDNS])` + +| 参数 | 类型 | 含义 | +| --------- | ------ | ------------------------------------------------------------ | +| profileID | 整型 | PDP上下文ID | +| ipType | 整型 | IP协议类型,有如下几个值:
0表示IPv4
1表示IPv6
2表示IPv4和IPv6 | +| state | 整型 | IPv4或IPv6的拨号状态
0表示未拨号或拨号失败
1表示拨号成功 | +| reconnect | 整型 | 拨号重连标志,保留参数,暂未使用 | +| addr | 字符串 | IPv4或IPv6的地址,具体取决于输入参数ipType的值:
ipType为0,addr为IPv4地址
ipType为1,addr为IPv6地址 | +| priDNS | 字符串 | 主要DNS服务器地址 | +| secDNS | 字符串 | 辅助DNS服务器地址 | + +`ipType`为2,返回值格式为: + +`(profileID, ipType, [state, reconnect, ipv4Addr, priDNS, secDNS], [state, reconnect, ipv6Addr, priDNS, secDNS])` + +返回的元组中,第一个列表包含的是IPv4的拨号信息,第二个列表包含的是IPv6的拨号信息。 + + + +>返回值 `(1, 0, [0, 0, '0.0.0.0', '0.0.0.0', '0.0.0.0'])` 表示当前没有拨号或者拨号没有成功。 +> +>BC32系列仅支持第一路,不支持多路拨号,且不支持获取IPv6拨号的DNS服务器地址。 +> +>支持该方法的模组:EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EG800P/EC200A/UC200A/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G/EC600E/EC800E/BG95/BC32系列。 +> +>由于需要向老版dataCall.getInfo兼容,实际profileID的最大值是大于3的,具体以实际能够查询的profileID为准。 + + + +**示例:** + +```python +>>> import dataCall +>>> dataCall.getInfo(1, 0) +(1, 0, [1, 0, '10.91.44.177', '58.242.2.2', '218.104.78.2']) +``` + diff --git a/docs/API_reference/zh/iotlib/net.md b/docs/API_reference/zh/iotlib/net.md new file mode 100644 index 0000000000000000000000000000000000000000..a2fdc257743f0ac112293aad0ef9e60aa123958a --- /dev/null +++ b/docs/API_reference/zh/iotlib/net.md @@ -0,0 +1,1019 @@ +# net - 网络相关功能 + +该模块包含了模组网络相关的功能,提供配置和查询网络模式信息等接口,比如获取注网状态,设置搜网模式等。 + + + +>建议用户使用不同运营商的SIM卡时,则配置对应运营商的APN信息;如果不配置或者配置错误,可能会导致模组无法注网。用户具体如何配置APN信息,参考[`dataCall.setPDPContext`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/dataCall.html#%3Ccode%3EdataCall.setPDPContext%3C/code%3E)方法。 + + + +## 获取CSQ信号强度 + +### `net.csqQueryPoll` + +```python +net.csqQueryPoll() +``` + +该方法用于获取csq信号强度。 + +**返回值描述:** + + 成功返回整型的csq信号强度值,失败返回整型值`-1`,返回值为`99`表示异常。 + + + +>信号强度值范围0 ~ 31,值越大表示信号强度越好。 + + + +**示例:** + +```python +>>> import net +>>> net.csqQueryPoll() +31 +``` + + + +## 获取小区信息 + +### `net.getCellInfo` + +```python +net.getCellInfo() +``` + +该方法用于获取邻近小区的信息。 + +**返回值描述:** + + 失败返回整型值`-1`,成功返回包含三种网络系统`(GSM、UMTS、LTE)`的信息的list,如果对应网络系统信息为空,则返回空的List。格式和说明如下: + + `([(flag, cid, mcc, mnc, lac, arfcn, bsic, rssi)], [(flag, cid, licd, mcc, mnc, lac, uarfcn, psc, rssi)], [(flag, cid, mcc, mnc, pci, tac, earfcn, rssi, rsrq),...])` + +* `GSM`网络系统返回值说明 + +| 参数 | 参数意义 | +| ------- | ------------------------------------------------------------ | +| `flag` | 小区类型,范围0 - 3, 0:当前服务小区,1:邻区,2:同频邻区 ,3:异频邻区 | +| `cid` | 返回GSM网络下的cell id信息,0则为空,范围0 ~ 65535 | +| `mcc` | 移动设备国家代码,范围 0 ~ 999
注意:EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95系列的模组,该值需要转化成十六进制,比如下面示例中的十进制数1120,用十六进制表示为0x460,表示移动设备国家代码460,其他型号模组,该值直接用十进制表示,比如移动设备国家代码460,就是用十进制的460来表示。 | +| `mnc` | 移动设备网络代码,范围 0 ~ 99
注意:EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95系列的模组,该值需要转化成十六进制。 | +| `lac` | 位置区码,范围 1 ~ 65535 | +| `arfcn` | 无线频道编号,范围 0 ~ 65535 | +| `bsic` | 基站识别码,范围 0 ~ 63 | +| `rssi` | GSM网络下,该值表示接收电平,描述接收到信号强度,99表示未知或者无法检测到,该值的计算方式如下:
rssi = RXLEV - 111,单位dBm,RXLEV 的范围是 0 ~ 63,所以rssi范围是 -111 ~ -48 dBm; | + +* `UMTS`网络系统返回值说明 + +| 参数 | 参数意义 | +| -------- | ------------------------------------------------------------ | +| `flag` | 小区类型,范围0 - 3,0:当前服务小区,1:邻区,2:同频邻区 ,3:异频邻区 | +| `cid` | 表示UMTS网络下的 Cell identity ,Cell identity = RNC_ID * 65536 + Cell_ID,Cell identity范围 0x0000000 ~ 0xFFFFFFF(注意这里是28bits);即Cell identity前两个字节是RNC_ID,后两个字节是Cell_ID,Cell_ID的范围是0 ~ 65535 | +| `lcid` | URA ID,范围 0 ~ 65535,0表示该信息不存在 | +| `mcc` | 移动设备国家代码,范围 0 ~ 999 | +| `mnc` | 移动设备网络代码,范围 0 ~ 99 | +| `lac` | 位置区码,范围 1 ~ 65535 | +| `uarfcn` | 无线频道编号,范围 0 ~ 65535 | +| `psc` | 主扰码,该参数确定所扫描的小区的主要扰码,范围 0 ~ 511 | +| `rssi` | UMTS网络下,该值表示RSCP即CPICH/PCCPCH 接收信号码功率,该值的计算方式如下:
rssi = RSCP - 115,单位dBm ,范围 -121 ~ -25 dBm; | + +* `LTE`网络系统返回值说明 + +| 参数 | 参数意义 | +| ------ | ------------------------------------------------------------ | +| `flag` | 小区类型,范围0 - 3,0:当前服务小区,1:邻区,2:同频邻区 ,3:异频邻区 | +| `cid` | 表示LTE网络下的小区标识(Cell Identity),也叫ECI(E-UTRAN Cell Identifier),ECI = eNodeB ID *256 + Cell ID组成,范围0x0000000 ~ 0xFFFFFFF(注意是28bits),前20bit表示基站标识(eNodeB ID),后8bit表示LTE小区ID(Cell ID) | +| `mcc` | 移动设备国家代码,范围 0 ~ 999 | +| `mnc` | 移动设备网络代码,范围 0 ~ 99 | +| `pci` | 物理层小区标识号,0 ~ 503 | +| `tac` | 跟踪区域码,0 ~ 65535 | +| `earfcn` | 无线频道编号,范围 0 ~ 65535 | +| `rssi` | LTE网络下,rssi:表示接收的所有信号强度,单位dBm,范围 -140 ~ -44 dBm
注:目前除BC25系列和BG95系列,其它平台均无法获取rssi,使用RSRP代替:
RSRP:表示接收到的有效信号强度,单位dBm,范围 -140 ~ -44 dBm | +| `rsrq` |LTE网络参考信号接收质量,范围 -20 ~ -3
注:理论上rsrq的范围应该是-19.5 ~ -3,但由于计算方法问题,目前能给出的是-20 ~ -3
目前仅BC25系列、BG95系列和EC600E/EC800E系列获取该参数有意义,其它平台该参数无意义| + + + +>该接口搜小区时会一直阻塞,一般是3-5秒,在无信号的地方会更长; +> +>BC32系列模组仅NB网络支持。 + + + +**示例:** + +```python +>>> import net +>>> net.getCellInfo() +([], [], [(0, 232301375, 1120, 17, 378, 26909, 1850, -66, -8), (3, 110110494, 1120, 17, 10, 26909, 2452, -87, -17), (3, 94542859, 1120, 1, 465, 56848, 1650, -75, -10), +(3, 94472037, 1120, 1, 369, 56848, 3745, -84, -20)]) + +>>> net.getCellInfo() +([], [], [(0, 17104243, 460, 4, 121, 19472, 3688, -76, -15)]) +``` + + + +## 网络制式及漫游配置 + +### `net.getConfig` + +```python +net.getConfig() +``` + +该方法用于获取当前网络模式及漫游配置。 + +**返回值描述:** + + 失败返回整型值`-1`,成功返回一个元组,包含当前首选的网络制式与漫游打开状态,说明如下: + +* 网络制式 + +| 值 | 网络制式 | | 值 | 网络制式 | +| ---- | :------------------------ | ---- | ---- | -------------------------------------------- | +| 0 | GSM | | 17 | UMTS_LTE(双链路) | +| 1 | UMTS | | 18 | GSM_UMTS_LTE(双链路) | +| 2 | GSM_UMTS(自动) | | 19 | CATM,BG95系列支持 | +| 3 | GSM_UMTS(GSM 优先) | | 20 | GSM_CATM(GSM 优先), BG95系列支持 | +| 4 | GSM_UMTS(UMTS 优先) | | 21 | CATNB, BG95系列支持 | +| 5 | LTE | | 22 | GSM_CATNB(GSM 优先), BG95/BC32系列支持 | +| 6 | GSM_LTE(自动) | | 23 | CATM_CATNB(CATM 优先), BG95系列支持 | +| 7 | GSM_LTE(GSM 优先) | | 24 | GSM_CATM_CATNB(GSM 优先), BG95系列支持 | +| 8 | GSM_LTE(LTE 优先) | | 25 | CATM_GSM(CATM 优先), BG95系列支持 | +| 9 | UMTS_LTE(自动) | | 26 | CATNB_GSM(CATNB 优先), BG95/BC32系列支持 | +| 10 | UMTS_LTE(UMTS 优先) | | 27 | CATNB_CATM(CATNB 优先), BG95系列支持 | +| 11 | UMTS_LTE(LTE 优先) | | 28 | GSM_CATNB_CATM(GSM 优先), BG95系列支持 | +| 12 | GSM_UMTS_LTE(自动) | | 29 | CATM_GSM_CATNB(CATM 优先), BG95系列支持 | +| 13 | GSM_UMTS_LTE(GSM 优先) | | 30 | CATM_CATNB_GSM(CATM 优先), BG95系列支持 | +| 14 | GSM_UMTS_LTE(UMTS 优先) | | 31 | CATNB_GSM_CATM(CATNB 优先), BG95系列支持 | +| 15 | GSM_UMTS_LTE(LTE 优先) | | 32 | CATNB_CATM_GSM(CATNB 优先), BG95系列支持 | +| 16 | GSM_LTE(双链路) | | 33 | CATNB_GSM(企标), BC32系列支持 | + + + +>BC25系列不支持此方法; +> +>BG95-M1系列仅支持CATM制式; +> +>BG95-M2系列仅支持包含CATM和CATNB两种制式; +> +>BG95-M3/M8系列支持CATM,CATNB和GSM全部三种制式; +> +>BC32系列与企标相关的配置需要重启生效;改变网络制式需要在cfun=0的情况下进行。 + + + +**示例:** + +```python +>>> import net +>>>net.getConfig () +(8, False) +``` + + + +### `net.setConfig` + +```python +net.setConfig(mode [, roaming]) +``` + +该方法用于设置网络制式及漫游配置。 + +**参数描述:** + +* `mode` - 网络制式,整型值,详见上述网络制式表格 + +* `roaming` - 漫游开关,整型值,可选参数(`0`:关闭, `1`:开启) + +**返回值描述:** + + 设置成功返回整型值`0`,设置失败返回整型值`-1`。 + + + +>* roaming为可选参数,不支持的平台,该参数可不写 +>* BC25系列不支持此方法 +>* EC200U/EC600U/EG915U/EG912U系列模组不支持漫游参数配置,且仅支持设置网络制式0/5/6/8,
其中6/8底层都是都是LTE优先,当设置为8时,查询为6。 +>* EC600G/EC800G系列模组不支持漫游参数配置,且仅支持设置网络支持为5/6,其中5/6底层都是都是LTE ONLY,当设置为6时,查询为5。 +>* EC600E/EC800E/EC600K/EC800K/EC600M/EC800M/EG810M/EG800P系列模组仅支持LTE ONLY。 +>* UC200A系列模组仅支持2G/3G。 +>* EC200A/UC200A系列模组设置后掉电不保存。 + + + +**示例:** + +```python +>>> import net +>>>net.setConfig(6) +0 + +>>>net.getConfig () +(6, False) +``` + + + +## 获取网络配置模式 + +### `net.getNetMode` + +```python +net.getNetMode() +``` + +该方法用于获取网络配置模式。 + +**返回值描述:** + +失败返回整型值`-1`,成功返回一个元组,格式为:`(selection_mode, mcc, mnc, act)`参数说明如下: + +| 参数 | 类型 | 参数说明 | +| ---------------- | ------ | ------------------------ | +| `selection_mode` | 整型 | 方式,0 - 自动,1 - 手动 | +| `mcc` | 字符串 | 移动设备国家代码 | +| `mnc` | 字符串 | 移动设备网络代码 | +| `act` | 整型 | 首选网络的ACT模式 | + +`ACT`模式枚举值参照下表: + +| 值 | ACT模式 | +| ---- |--------------------| +| 0 | GSM | +| 1 | COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E UTRAN CA | +| 10 | NONE | + +BG95系列模组`ACT`模式枚举值参照下表: + +| 值 | ACT模式 | +| ---- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | E_UTRAN_NBIOT | +| 11 | E_UTRAN_EMTC | +| 12 | NONE | + +**示例:** + +```python +>>> import net +>>> net.getNetMode() +(0, '460', '46', 7) +``` + + + +## 获取详细信号强度 + +### `net.getSignal` + +```python +net.getSignal([sinrEnable]) +``` + +该方法用于获取详细信号强度。 + +**参数描述:** + +* `sinrEnable` - 使能是否获取sinr数值,整型值,可选参数,取值范围见下表: + +| 取值 | 含义 | +|-----| ------------- | +| 0 | 不获取sinr数值 | +| 1 | 获取sinr数值 | + +**返回值描述:** + + 失败返回整型值`-1`,成功返回一个元组,包含两个List`(GW 、LTE)`,返回值格式和说明如下: + + `([rssi, bitErrorRate, rscp, ecno], [rssi, rsrp, rsrq, cqi, sinr])` + +* `GSM/WCDMA`返回值参数说明: + +| 参数 | 参数意义 | +| -------------- | ------------------------------------------------------------ | +| `rssi` | GSM和WCDMA网络下,该值表示接收电平,描述接收到信号强度,99表示未知或者无法检测到,该值的计算方式如下
rssi = RXLEV - 111,单位dBm,RXLEV 的范围是 0 ~ 63 | +| `bitErrorRate` | 误码率,范围 0 ~ 7,99表示未知或者无法检测到 | +| `rscp` | 接收信号码功率,范围 -121 ~ -25 dBm,255表示未知或者无法检测到 | +| `ecno` | 导频信道,范围 -24 ~ 0,255表示未知或者无法检测到 | + +* `LTE`返回值参数说明: + +| 参数 | 参数意义 | +| ------ | ------------------------------------------------------------ | +| `rssi` | 接收的信号强度,范围 -140 ~ -44 dBm,99表示未知或者无法检测到 | +| `rsrp` | 下行参考信号的接收功率,范围 -140 ~ -44 dBm,99表示未知或者无法检测到 | +| `rsrq` | 下行特定小区参考信号的接收质量,范围 -20 ~ -3 dB,值越大越好 ,255表示未知或者无法检测到 | +| `cqi` | 信道质量,255表示未知或者无法检测到 | +| `sinr` | 干扰信噪比,范围 -10 ~ 40 dB,255表示未知或者无法检测到 | + + + +>* `sinrEnable`为可选参,不支持的平台可不写,不写默认不获取sinr +>* BC25/BC32系列不支持获取sinr,其余模组型号均支持 +>* BC32系列模组仅NB网络支持。 + + + +**示例:** + +```python +>>> import net +>>>net.getSignal() +([99, 99, 255, 255], [-51, -76, -5, 255]) +>>>net.getSignal(0) +([99, 99, 255, 255], [-51, -76, -5, 255]) +>>>net.getSignal(1) +([99, 99, 255, 255], [-51, -76, -5, 255, 18]) +``` + + + +## 获取当前基站时间 + +### `net.nitzTime` + +```python +net.nitzTime() +``` + +该方法用于获取当前基站时间。这个时间是基站在模块开机注网成功时下发的时间。 + +**返回值描述:** + + 失败返回整型值`-1`,成功返回一个元组,包含基站时间与对应时间戳与闰秒数(0表示不可用),格式为:`(date, abs_time, leap_sec)`,说明如下: + +| 参数 | 类型 | 参数意义 | +| ---------- | ------ | ------------------------------------------------------------ | +| `date` | 字符串 | 基站时间,其中关于时区的部分,不同系列有所区别,具体见示例。
如果需要设置和获取时区,请使用`utime`模块的[`setTimeZone(offset)`](https://developer.quectel.com/doc/quecpython/API_reference/zh/stdlib/utime.html#%3Ccode%3Eutime.setTimeZoneEx%3C/code%3E)和[`getTimeZone()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/stdlib/utime.html#%3Ccode%3Eutime.getTimeZoneEx%3C/code%3E)接口,
不同平台,这两个接口的单位都是小时,具体参考[`utime`](https://developer.quectel.com/doc/quecpython/API_reference/zh/stdlib/utime.html)模块的说明。 | +| `abs_time` | 整型 | 基站时间的绝对秒数表示 | +| `leap_sec` | 整型 | 闰秒数 | + +**示例:** + +```python +>>> import net +>>> net.nitzTime() +# EC100Y/EC200N/EC600N/EC600S/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M/EC200A系列的返回值,时区单位小时,这里8即表示东八区 +('21/10/26 06:08:03 8 0', 1635228483, 0) +# BC25/BC32/EC600E/EC800E/EC200U/EC600U/EG912U/EG915U/EC600G/EC800G系列返回值,时区单位15分钟,这里+32即表示东八区 +('20/11/26 02:13:25 +32 0', 1606356805, 0) +# BG95系列的返回值,无时区部分 +('23/02/14 02:25:13', 1676312713, 0) +``` + + + +## 获取运营商信息 + +### `net.operatorName` + +```python +net.operatorName() +``` + +该接口用于获取当前注网的运营商信息。 + +**返回值描述:** + + 失败返回整型值`-1`,成功返回一个元组,包含注网的运营商信息,格式为: `(long_eons, short_eons, mcc, mnc)`,说明如下: + +| 参数 | 类型 | 参数说明 | +| ------------ | ------ | ---------------- | +| `long_eons` | 字符串 | 运营商信息全称 | +| `short_eons` | 字符串 | 运营商信息简称 | +| `mcc` | 字符串 | 移动设备国家代码 | +| `mnc` | 字符串 | 移动设备网络代码 | + +**示例:** + +```python +>>> import net +>>> net.operatorName() +('CHN-UNICOM', 'UNICOM', '460', '01') +``` + + + +## 获取网络注册信息 + +### `net.getState` + +```python +net.getState() +``` + +该接口用于获取当前网络注册信息。 + +**返回值描述:** + + 失败返回整型值`-1`,成功返回一个元组,包含电话和网络注册信息,元组中`voice`开头的表示电话注册信息,`data`开头的表示网络注册信息,格式为:`([voice_state, voice_lac, voice_cid, voice_rat, voice_reject_cause, voice_psc], [data_state, data_lac, data_cid, data_rat, data_reject_cause, data_psc])` + +* 返回值参数说明: + +| 参数 | 参数说明 | +| -------------- | ------------------------------------------------------------ | +| `state` | 网络注册状态,具体见下表 | +| `lac` | 位置区码,范围 1 ~ 65534 | +| `cid` | cell id,范围 0x00000000 ~ 0x0FFFFFFF,具体见上面[`net.getCellInfo()`](hhttps://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)中返回值 | +| ``rat`` | 接入技术,access technology,具体见后面表格 | +| `reject_cause` | 注册被拒绝的原因,EC200U/EC600U/EG915U/BC25系列该参数保留,不作为有效参数 | +| `psc` | 主扰码,Primary Scrambling Code,EC200U/EC600U/EG915U/BC25系列该参数保留,不作为有效参数 | + +* 网络注册状态`state`枚举值见下表: + +| 值 | 状态说明 | +| ---- |------------------------| +| 0 | 没有注册,MT也没有再搜索 | +| 1 | 注册完成,本地网络 | +| 2 | 没有注册,但是MT在尝试搜索 | +| 3 | 拒绝注册 | +| 4 | 未知状态 | +| 5 | 注册完成, 漫游网络 | +| 6 | 注册为“仅限短信”,本地网络 (不适用) | +| 7 | 注册为“仅限短信”,漫游网络(不适用) | +| 8 | 紧急attach仅限紧急承载服务 | +| 9 | 注册为“CSFB不优先”,本地网络 (不适用) | +| 10 | 注册为“CSFB不优先”,漫游网络(不适用) | +| 11 | 仅限紧急承载服务 | + +* 接入技术`access technology` + +| 值 | 说明 | +| ---- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | NONE | + + + +> BG95系列参照下表 + +| 值 | 说明 | +| ---- | ------------------ | +| 0 | GSM | +| 1 | GSM COMPACT | +| 2 | UTRAN | +| 3 | GSM wEGPRS | +| 4 | UTRAN wHSDPA | +| 5 | UTRAN wHSUPA | +| 6 | UTRAN wHSDPA HSUPA | +| 7 | E_UTRAN | +| 8 | UTRAN HSPAP | +| 9 | E_UTRAN_CA | +| 10 | E_UTRAN_NBIOT | +| 11 | E_UTRAN_EMTC | +| 12 | NONE | + +**示例:** + +```python +>>> import net +>>> net.getState() +([11, 26909, 232301323, 7, 0, 466], [0, 26909, 232301323, 7, 0, 0]) +``` + + + +## 获取小区ID + +### `net.getCi` + +```python +net.getCi() +``` + +该方法用于获取附近小区ID。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的cid集合。 + +**返回值描述:** + + 成功返回一个list类型的数组,包含小区id,格式为:`[id, ……, id]`。数组成员数量并非固定不变,位置不同、信号强弱不同等都可能导致获取的结果不一样。 + + 失败返回整型值`-1`。 + +**示例:** + +```python +>>> net.getCi() +[14071232, 0] +``` + + + +### `net.getServingCi` + +```python +net.getServingCi() +``` + +该方法用于获取服务小区ID。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的cid集合。 + +**返回值描述:** + + 成功返回服务小区ID。失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.getServingCi() +94938399 +``` + + + +## 获取小区的MNC + +### `net.getMnc` + +```python +net.getMnc() +``` + +该方法用于获取附近小区的mnc。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的mnc集合。 + +**返回值描述:** + + 成功返回一个list类型的数组,包含小区`mnc`,格式为:`[mnc, ……, mnc]`。数组成员数量并非固定不变,位置不同、信号强弱不同等都可能导致获取的结果不一样。 + + 失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.getMnc() +[0, 0] +``` + + + +### `net.getServingMnc` + +```python +net.getServingMnc() +``` + +该方法用于获取服务小区的mnc。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的mnc集合。 + +**返回值描述:** + + 成功返回服务小区`mnc`。失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.getServingMnc() +1 +``` + + + +## 获取小区的MCC + +### `net.getMcc` + +```python +net.getMcc() +``` + +该方法用于获取附近小区的mcc。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的mcc集合。 + +**返回值描述:** + + 成功返回一个list类型的数组,包含小区`mcc`,格式为:`[mcc, ……, mcc]`。数组成员数量并非固定不变,位置不同、信号强弱不同等都可能导致获取的结果不一样。 + + 失败返回整型值`-1`。 + + + +> EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95/EG915N系列的模组,该值需要转化成十六进制,比如下面示例中的十进制数1120,十六进制即0x460,表示移动设备国家代码460,其他型号模组,该值直接用十进制表示,比如移动设备国家代码460,就是用十进制的460来表示。 + + + +**示例:** + +```python +>>> import net +>>> net.getMcc() +[1120, 0] +``` + + + +### `net.getServingMcc` + +```python +net.getServingMcc() +``` + +该方法用于获取服务小区的mcc。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的mcc集合。 + +**返回值描述:** + + 成功返回服务小区的`mcc`,失败返回整型值`-1`。 + + + +> EC600N/EC600E/EC800E/EC200A/EC600M/EC800M/BG95/EG915N系列的模组,该值需要转化成十六进制,比如下面示例中的十进制数1120,十六进制即0x460,表示移动设备国家代码460,其他型号模组,该值直接用十进制表示,比如移动设备国家代码460,就是用十进制的460来表示。 + + + +**示例:** + +```python +>>> import net +>>> net.getServingMcc() +1120 +``` + + + +## 获取小区的Lac + +### `net.getLac` + +```python +net.getLac() +``` + +该方法用于获取附近小区的Lac。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的lac集合。 + +**返回值描述:** + + 成功返回一个list类型的数组,包含小区lac,格式为:`[lac, ……, lac]`。数组成员数量并非固定不变,位置不同、信号强弱不同等都可能导致获取的结果不一样。 + + 失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.getLac() +[21771, 0] +``` + + + +### `net.getServingLac` + +```python +net.getServingLac() +``` + +该方法用于获取服务小区的Lac。该接口获取结果即为[`net.getCellInfo()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/net.html#%3Ccode%3Enet.getCellInfo%3C/code%3E)接口获取结果中的lac集合。 + +**返回值描述:** + + 成功返回服务小区`lac`,失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.getServingLac() +56848 +``` + + + +## 工作模式配置 + +### `net.getModemFun` + +```python +net.getModemFun() +``` + +该方法用于获取模组当前的功能模式。 + +**返回值描述:** + + 成功返回当前模组工作模式,失败返回整型值`-1`;模组工作模式详细如下: + +| 模式 | 说明 | +| --- | ---------- | +| 0 | 最小功能模式。该模式下,整个射频网络协议栈全部关闭,SIM卡模块停止供电。 | +| 1 | 全功能模式(默认)。该模式下,射频网络协议栈正常运行,设备可以发送和接收RF信号。 | +| 4 | 飞行模式。该模式下,会禁用终端设备的无线射频功能,即禁止设备发送和接收RF信号,但是SIM卡模块依然是正常供电。 | + + + +>BC32系列不支持模式4. + + + +**示例:** + +```python +>>> import net +>>> net.getModemFun() +1 +``` + + + +### `net.setModemFun` + +```python +net.setModemFun(fun [, rst]) +``` + +该方法用于设置当前模组工作模式。 + +**参数描述:** + +* `fun` - 模组工作模式,整型值 +| 模式 | 说明 | +| --- | ---------- | +| 0 | 最小功能模式。该模式下,整个射频网络协议栈全部关闭,SIM卡模块停止供电。 | +| 1 | 全功能模式(默认)。该模式下,射频网络协议栈正常运行,设备可以发送和接收RF信号。 | +| 4 | 飞行模式。该模式下,会禁用终端设备的无线射频功能,即禁止设备发送和接收RF信号,但是SIM卡模块依然是正常供电。 | + +* `rst` - 重启标志,整型值,可选参数 +| 值 | 说明 | +| --- | ---------- | +| 0 | 设置完不重启(默认) | +| 1 | 设置完重启 | + +**返回值描述:** + + 设置成功返回整型值`0`,设置失败返回整型值`-1`。 + +**示例:** + +```python +>>> import net +>>> net.setModemFun(4) +0 +``` + + + +## band设置与获取 + +### `net.setBand` + +```python +net.setBand(netRat, gsmBand, bandTuple) +``` +该方法用于设置需要的band,即在模组支持的前提下,锁定用户指定的band。 + +* `band`值对照表 + +| 网络制式 | band值 | +| --------------- | ------------------------------------------------------------ | +| EGPRS(GSM) | EGSM900 - 0x1
DCS1800 - 0x2
GSM850 - 0x4
PCS1900 - 0x8 | +| LTE/eMTC/NB-IoT | BAND1 - 0x1
BAND2 - 0x2
BAND3 - 0x4
BAND4 - 0x8
BAND5 - 0x10
BAND7 - 0x40
BAND8 - 0x80
BAND12 - 0x800
BAND13 - 0x1000
BAND18 - 0x20000
BAND19 - 0x40000
BAND20 - 0x80000
BAND25 - 0x1000000
BAND26 - 0x2000000
BAND27 - 0x4000000
BAND28 - 0x8000000
BAND31 - 0x40000000
BAND66 - 0x20000000000000000
BAND71 - 0x400000000000000000
BAND72 - 0x800000000000000000
BAND73 - 0x1000000000000000000
BAND85 - 0x1000000000000000000000
| + +**参数描述:** + +* `netRat` - 网络模式,整型值,表示制定要设置的是哪种网络模式下的`band` +| rat值 | 说明 | +| ----- | ----------------------------------------- | +| 0 | 设置GSM网络的band | +| 1 | 设置LTE网络的band | +| 2 | 设置CATM网络的band | +| 3 | 设置NB网络的band | + +* `gsmBand` - `GSM`网络的`band`值,整型值,参照上述`band`值对照表 + +* `bandtuple` - 设置`GSM`网络之外的其他网络模式的`band`值,是一个包含4个元素的元组,每个成员最大不能超过4字节,具体形式:`(band_hh, band_hl, band_lh, band_ll)`,每个元素说明如下: +`band_hh` - band值的高8字节的高4字节 +`band_hl` - band值的高8字节的低4字节 +`band_lh` - band值的低8字节的高4字节 +`band_ll` - band值的低8字节的低4字节 +如果用户最终要设置的`band`值为`band_value`,那么计算方式如下: +`band_hh = (band_value & 0xFFFFFFFF000000000000000000000000) >> 96` +`band_hl = (band_value & 0x00000000FFFFFFFF0000000000000000) >> 64` +`band_lh = (band_value & 0x0000000000000000FFFFFFFF00000000) >> 32` +`band_ll = (band_value & 0x000000000000000000000000FFFFFFFF)` + +**返回值描述:** + + 设置成功返回整型值`0`,失败返回整型值`-1`。 + + + +>* 当前可支持模组型号:BG95/EG912N/EG915N/EC600N/EC800N系列 +>* BG95不支持设置上述模式1(LTE)下的`band` +>* EG912N/EG915N/EC600N/EC800N系列仅支持上述模式0(GSM)和模式1(LTE) + + + +**示例:** + +```python +import net +import utime + +''' +用户可直接使用下面两个接口来设置band和获取band +''' +def set_band(net_rat, band_value): + if net_rat == 0: + retval = net.setBand(0, band_value, (0, 0, 0, 0)) + else: + band_hh = (band_value & 0xFFFFFFFF000000000000000000000000) >> 96 + band_hl = (band_value & 0x00000000FFFFFFFF0000000000000000) >> 64 + band_lh = (band_value & 0x0000000000000000FFFFFFFF00000000) >> 32 + band_ll = (band_value & 0x000000000000000000000000FFFFFFFF) + retval = net.setBand(net_rat, 0, (band_hh, band_hl, band_lh, band_ll)) + return retval + + +def get_band(net_rat): + return net.getBand(net_rat) + +#====================================================================================================== + +''' +设置GSM网络band为0xa,即 DCS1800 + PCS1900 +0xa = 0x2(DCS1800) + 0x8(PCS1900) +''' +def set_gsm_band_example(): + print('Set GSM band to 0xa example:') + gsm_band = get_band(0) + print('GSM band value before setting:{}'.format(gsm_band)) + ret = set_band(0, 0xa) + if ret == 0: + print('Set GSM band successfully.') + else: + print('Set GSM band failed.') + utime.sleep(1) # 设置band需要一定时间,延时一段时间再获取新的结果 + gsm_band = get_band(0) + print('GSM band value after setting:{}'.format(gsm_band)) + return ret + + +''' +设置eMTC网络band为0x15,即设置 BAND1+BAND3+BAND5 +0x15 = 0x1(BAND1) + 0x4(BAND3) + 0x10(BAND5) +''' +def set_camt_band_example(): + print('Set CATM band to 0x15 example:') + catm_band = get_band(2) + print('CATM band value before setting:{}'.format(catm_band)) + ret = set_band(2, 0x15) + if ret == 0: + print('Set CATM band successfully.') + else: + print('Set CATM band failed.') + utime.sleep(1) # 设置band需要一定时间,延时一段时间再获取新的结果 + catm_band = get_band(2) + print('CATM band value after setting:{}'.format(catm_band)) + return ret + + +''' +设置NB-IoT网络band为0x1000800000000000020011,即设置 BAND1+BAND5+BAND18+BAND71+BAND85 +0x1000400000000000020011 = 0x1 + 0x10 + 0x20000 + 0x400000000000000000 + 0x1000000000000000000000 +''' +def set_nb_band_example(): + print('Set NB band to 0x1000400000000000020011 example:') + nb_band = get_band(3) + print('NB band value before setting:{}'.format(nb_band)) + ret = set_band(3, 0x1000400000000000020011) + if ret == 0: + print('Set NB band successfully.') + else: + print('Set NB band failed.') + utime.sleep(1) # 设置band需要一定时间,延时一段时间再获取新的结果 + nb_band = get_band(3) + print('NB band value after setting:{}'.format(nb_band)) + return ret + + +def main(): + set_gsm_band_example() + utime.sleep(1) + set_camt_band_example() + utime.sleep(1) + set_nb_band_example() + + +if __name__ == '__main__': + main() + + +#=================================================================================================== +#运行结果 +Set GSM band to 0xa example: +GSM band value before setting:0xf +Set GSM band successfully. +GSM band value after setting:0xa + +Set CATM band to 0x15 example: +CATM band value before setting:0x10000200000000090e189f +Set CATM band successfully. +CATM band value after setting:0x15 + +Set NB band to 0x1000400000000000020011 example: +NB band value before setting:0x10004200000000090e189f +Set NB band successfully. +NB band value after setting:0x1000400000000000020011 + +``` + + + +### `net.getBand` + +```python +net.getBand(netRat) +``` + +该方法用于获取当前某个网络制式下的band设置值。 + +**参数描述:** + +* `netRat` - 网络模式,整型值,表示制定要设置的是哪种网络模式下的`band` +| rat值 | 说明 | +| ----- | ----------------------------------------- | +| 0 | 设置GSM网络的band | +| 1 | 设置LTE网络的band | +| 2 | 设置CATM网络的band | +| 3 | 设置NB网络的band | + +**返回值描述:** + +返回十六进制字符串形式的band值。 + + + +>* 当前可支持模组型号:BG95/EG912N/EG915N/EC600N/EC800N系列 +>* BG95不支持设置上述模式1(LTE)下的`band` +>* EG912N/EG915N/EC600N/EC800N系列仅支持上述模式0(GSM)和模式1(LTE) + + + +**示例:** + +```python +>>> import net +>>> net.getBand(2) +'0x10000200000000090e189f' # 这是字符串,用户如果需要int型,可通过int(data)来自行转换 +``` + + + +### `net.bandRst` + +```python +net.bandRst() +``` + +该方法用于恢复band初始设定值。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + + + +>当前可支持模组型号:EG912N/EG915N/EC600N/EC800N系列 + + + +**示例:** + +```python +''' +先设置成其他band,调用该接口,看是否成功恢复成初始值 +EG912NENAA平台初始值:gsm_band:0x3(EGSM900/DCS1800 ) lte_band:0x8000000000480800D5(B1/B3/B5/B7/B8/B20/B28/B31/B72 ) +''' +>>> import net +>>> net.bandRst() +0 +``` \ No newline at end of file diff --git a/docs/API_reference/zh/iotlib/sim.md b/docs/API_reference/zh/iotlib/sim.md new file mode 100644 index 0000000000000000000000000000000000000000..e0d1a4081092c272e35c302799398460104c6542 --- /dev/null +++ b/docs/API_reference/zh/iotlib/sim.md @@ -0,0 +1,718 @@ +# sim - SIM卡功能 + +该模块提供sim卡相关功能的接口,如查询sim卡状态、ICCID、IMSI、电话号码等。对于此模块功能的支持,定制型号以实际功能为准。 + + + +> 获取SIM卡ICCID,IMSI时需要SIM卡状态为就绪状态(可通过sim.getStatus()查询状态)。此模块涉及到的PIN码、PUK码等一些列密码的获取请以运营商提供的为准,如果有密码不确定,请和运营商先进行确定。 + + + +## 通用SIM访问功能 + +### `sim.genericAccess` + +``` +sim.genericAccess(simId, cmd) +``` + +通用SIM访问接口 ,用于发送csim指令直接和sim卡交互。 + +**参数描述:** + +* `simId` - SIM卡卡槽编号,整型值,0表示SIM0,1表示SIM1,目前仅支持0。 +* `cmd` - 移动终端以GSM 51.011中描述的格式传递给SIM的命令,字符串类型。 + +**返回值描述:** + +成功: 返回元组数据。格式`(len,data)`,其中`len`为整型,表示`data`的长度。`data`为字符串类型,表示返回的数据内容。 + +失败: 返回整型值`-1`。 + + + +> 仅EC600N/EG912N/EG915N系列支持该方法。 + + + +**示例:** + +```python +>>> import sim +>>> sim.genericAccess(0,'80F2000016') +(48, '623E8202782183027FF08410A0000000871002FF86FF9000') +``` + + + +## 获取SIM卡信息 + +### `sim.getImsi` + +```python +sim.getImsi() +``` + +该方法用于获取sim卡的IMSI。 + + +**返回值描述:** + +成功: 返回字符串类型,值为`IMSI`。 + +失败: 返回整型值`-1`。 + +**示例:** + +```python +>>> import sim +>>> sim.getImsi() +'460105466870381' +``` + + + +### `sim.getIccid` + +```python +sim.getIccid() +``` + +该方法用于获取sim卡的ICCID。 + +**返回值描述:** + +成功: 返回字符串类型,数据值为`ICCID`。 + +失败: 返回整型值`-1`。 + +**示例:** + +```python +>>> import sim +>>> sim.getIccid() +'89860390845513443049' +``` + + + +### `sim.getPhoneNumber` + +```python +sim.getPhoneNumber() +``` + +该方法用于获取sim卡的电话号码,需要先进行写入本SIM卡电话卡号码。 + +**返回值描述:** + +成功: 返回字符串数据类型的电话号码。 + +失败: 返回整型值`-1`。 + + + +>BC25系列不支持此方法 + + + +**示例:** + +```python +>>> import sim +>>> sim.getPhoneNumber() +'+8618166328752' +``` + + + +## 查询SIM卡状态 + +### `sim.getStatus` + +```python +sim.getStatus() +``` + +该方法用于查询当前SIM卡状态。 + +**返回值描述:** + +sim卡状态码,整型值,具体说明如下: + +| 返回值 | 说明 | +| ------ | ------------------------------------------------------------ | +| -1 | API执行异常 | +| 0 | SIM卡不存在/被移除 | +| 1 | SIM已经准备好 | +| 2 | SIM卡已锁定,等待CHV1密码 | +| 3 | SIM卡已被阻拦,需要CHV1密码解锁密码 | +| 4 | 由于SIM/USIM个性化检查失败,SIM卡被锁定 | +| 5 | 由于PCK错误导致SIM卡被阻拦,需要MEP密码解除阻拦 | +| 6 | 需要隐藏电话簿条目的密钥 | +| 7 | 需要解锁隐藏密钥的编码 | +| 8 | SIM卡已锁定,等待CHV2密码 | +| 9 | SIM卡被阻拦,需要CHV2解锁密码 | +| 10 | 由于网络个性化检查失败,SIM卡被锁定 | +| 11 | 由于NCK不正确,SIM卡被阻拦,需要MEP解锁密码 | +| 12 | 由于子网络锁个性化检查失败,SIM卡被锁定 | +| 13 | 由于错误的NSCK,SIM卡被阻拦,需要MEP解锁密码 | +| 14 | 由于服务提供商个性化检查失败,SIM卡被锁定 | +| 15 | 由于SPCK错误,SIM卡被阻拦,需要MEP解锁密码 | +| 16 | 由于企业个性化检查失败,SIM卡被锁定 | +| 17 | 由于CCK不正确,SIM卡被阻止,需要MEP解锁密码 | +| 18 | SIM正在初始化,等待完成 | +| 19 | 有以下六种情况会导致此错误返回码。
1、由于CHV1、CHV2、通用的PIN的使用被阻拦,此三种情况。
2、由于使用代码解锁CHV1、CHV2、通用的PIN被阻拦,此三种情况。 | +| 20 | SIM卡无效 | +| 21 | 未知状态 | + + + +## PIN码验证功能 + +### `sim.enablePin` + +```python +sim.enablePin(pin) +``` + +该方法用于开启PIN码验证。开启后需要输入正确的PIN码进行验证,成功后,sim卡才能正常使用。需要注意最多3次尝试机会,连续3次错误后sim卡被锁定,需要PUK来解锁。 + +**参数描述:** + +- `pin` - PIN码,字符串类型,一般默认是"1234",最大长度不超过15位数字。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + + + +> EC600K/EC800K/EC600M/EC800M系列部分模组不支持PIN码功能:如CC/LC/GC后缀的系列模组。 + + + +**示例:** + +```python +>>> sim.enablePin("1234") +0 +``` + + + +### `sim.disablePin` + +```python +sim.disablePin(pin) +``` + +该方法用于取消PIN码验证。 + +**参数描述:** + +- `pin` - PIN码,字符串类型,一般默认是"1234",最大长度不超过15位数字。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + + + +> EC600K/EC800K/EC600M/EC800M系列部分模组不支持PIN码功能:如CC/LC/GC后缀的系列模组。 + + + +**示例:** + +```python +>>> import sim +>>> sim.disablePin("1234") +0 +``` + + + +### `sim.verifyPin` + +```python +sim.verifyPin(pin) +``` + +PIN码验证:用于SIM卡开启PIN码验证后,如果需要启用SIM卡,可以调用此方法来临时使本次的SIM卡正常使用,下次开机需要重新调用此方法进行验证(或者可以调用取消PIN验证的接口,重新开机后不需要重新PIN验证)。 + +**参数描述:** + +- `pin` - PIN码,字符串类型,一般默认是"1234",最大长度不超过15位数字。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + +> EC600K/EC800K/EC600M/EC800M系列部分模组不支持PIN码功能:如CC/LC/GC后缀的系列模组。 + +**示例:** + +```python +>>> import sim +>>> sim.verifyPin("1234") +0 +``` + + + +### `sim.changePin` + +```python +sim.changePin(oldPin, newPin) +``` + +该方法用于更改sim卡PIN码。 + +**参数描述:** + +- `oldPin` - 旧的PIN码,字符串类型,最大长度不超过15位数字。 +- `newPin` - 新的PIN码,字符串类型,最大长度不超过15位数字。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + +> EC600K/EC800K/EC600M/EC800M系列部分模组不支持PIN码功能:如CC/LC/GC后缀的系列模组。 + +**示例:** + +```python +>>> import sim +>>> sim.changePin("1234", "4321") +0 +``` + + + +## SIM卡解锁 + +### `sim.unblockPin` + +```python +sim.unblockPin(puk, newPin) +``` + +该方法用于SIM卡解锁:当多次输入PIN码错误需要用PUK码解锁。如果PUK码输入错误10次,SIM卡将永久锁定自动报废。 + +**参数描述:** + +- `puk` - PUK码,字符串类型,长度8位数字,最大长度不超过15位数字。 +- `newPin` - 新PIN码,字符串类型,最大长度不超过15位数字。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + +> EC600K/EC800K/EC600M/EC800M系列部分模组不支持PIN码功能:如CC/LC/GC后缀的系列模组。 + +**示例:** + +```python +>>> import sim +>>> sim.unblockPin("12345678", "0000") +0 +``` + + + +## 电话簿功能 + +### `sim.readPhonebook` + +```python +sim.readPhonebook(storage, start, end, username) +``` + +读电话簿:用于获取指定存储位置上的电话本中的一条或多条电话号码记录。 + +**参数描述:** + +- `storage` -电话号码存储位置,整型值,可选参数值如下: + +| 值 | 含义 | +| ---- | ------------------------------------------------------------ | +| 0 | 拨号列表 | +| 1 | 紧急电话号码 | +| 2 | 固定拨号号码 | +| 3 | 上次拨打电话号码 | +| 4 | 未接来电 | +| 5 | 终端设备电话薄 | +| 6 | 终端设备电话薄和SIM/USIM电话薄 | +| 7 | 本SIM卡电话号码(需要获取正确的电话号码进行写入) | +| 8 | 已接来电 | +| 9 | 本SIM卡电话薄 | +| 10 | 选择应用电话薄(如果USIM的应用已激活将选用ADF SUIM下的DF电话薄) | +| 11 | SIM卡中的MBDN | +| 12 | SIM卡中的MN | +| 13 | 系统拨叫号码,网络服务拨号 | +| 14 | 来电信息 | +| 15 | 呼出信息 | + +- `start` - 需要读取电话号码记录的起始编号,整型值,`start`为 `0` 表示不使用编号获取电话号码记,`start`应小于等于`end`。 +- `end` - 需要读取电话号码记录的结束编号,整型值,必须满足:`end - start <= 20`。 +- `username` - 电话号码中的用户名,字符串类型,当 start为 0 时有效,暂不支持中文,最大长度不超过30字节。 + +**返回值描述:** + +成功: 返回元组数据,格式`(record_number, [(index, username, phone_number), ... , (index, username, phone_number)])`,具体如下: + +| 参数 | 类型 | 含义 | +| --------------- | ------ | -------------------- | +| `record_number` | 整型 | 读取的记录数量 | +| `index` | 整型 | 在电话簿中的索引位置 | +| `username` | 字符串 | 电话号码的用户名 | +| `phone_number` | 字符串 | 电话号码 | + +失败:返回整型值`-1`。 + + + +>- 支持平台如下: +> - EC600N/EC200ACN_HA/EC200AAU_HA/EC200ACN_LA/EC200AEU_HA/EG912NEN_AA/EG915NEU_AG。 +>- 按username进行匹配时,并不是按完整的单词进行匹配,只要电话簿中已有记录的name是以username开头,那么就会匹配上。 + + + +**示例:** + +```python +>>> import sim +>>> sim.readPhonebook(9, 1, 4, "") +(4,[(1,'Tom','15544272539'),(2,'Pony','15544272539'),(3,'Jay','18144786859'),(4,'Pondy','15544282538')]) +>>> sim.readPhonebook(9, 0, 0, "Tom") +(1, [(1, 'Tom', '18144786859')]) +>>> sim.readPhonebook(9, 0, 0, "Pony") +(1, [(2, 'Pony', '17744444444')]) +>>> sim.readPhonebook(9, 0, 0, "Pon") #注意,这里只要是包含了‘pon’,都会被匹配上 +(2, [(2, 'Pony', '17744444444'),(4,'Pondy','15544282538')]) +``` + + + +### `sim.writePhonebook` + +```python +sim.writePhonebook(storage, index, username, number) +``` + +写电话簿:用于向选定的存储位置,写入一条电话记录。 + +**参数描述:** + +- `storage` - 电话号码存储位置,整型值,具体可选参数同上[`sim.readPhonebook`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sim.html#%3Ccode%3Esim.readPhonebook%3C/code%3E)中的`storage` : + +- `index` - 需要写入电话号码记录的在电话簿中的编号,整型值,范围`1 ~ 500`。 +- `username` - 电话号码的用户名,字符串类型,长度范围不超过30字节,暂不支持中文名。 +- `number` - 电话号码,字符串类型,最大长度不超过20字节。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + + + +> * 支持型号如下: +> * EC600N/EC200ACN_HA/EC200AAU_HA/EC200ACN_LA/EC200AEU_HA/EG912NEN_AA/EG915NEU_AG。 + + + +**示例:** + +```python +>>> import sim +>>> sim.writePhonebook(9, 1, 'Tom', '18144786859') +0 +``` + + + +## 热插拔功能 + +### `sim.setSimDet` + +```python +sim.setSimDet(switch, triggerLevel) +``` + +SIM卡热插拔开关:用于设置SIM卡热插拔相关配置。 + +**参数描述:** + +- `switch` - 开启或者关闭SIM卡热插拔功能,整型值,`0`:关闭 , `1`:打开。 +- `triggerLevel` - 整型值,根据SIM卡实际的在位电平进行设置,如果SIM卡插入时在位电平为高则设置为1,如果为低设置为0。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + + + +> EC600N系列/EG912N系列/EG915N系列/EC600M系列/EC800M系列/EC200A系列部分模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存。 +> +> EC600G系列/EC800G系列/EC200U系列/EC600U系列/EG912U系列/EG915U系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/8/23之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +> EC600E系列/EC800E系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/9/12之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +> BG95M1/BG95M2/BG95M3/BG95M6/BG95M8系列模组支持SIM卡热插拔功能,配置需要重启才能生效,相关配置掉电保存。 +> +> EG800PCN_LA/EG800KCN_GC/EC800KCN_LC系列模组支持SIM卡热插拔功能,配置立即生效,但是掉电不保存。 +> +> 以下型号不支持此接口: +> +> EC800MCN_LA/EC600MCN_LF/EC600MCN_CC/EC800MCN_GD/EG810MCN_GA/BC25/BG600LM3/EC600KCN_LC/EC800MCN_LF/BG95M9LA。 + + + +**示例:** + +```python +>>> import sim +>>> sim.setSimDet(1, 0) +0 +``` + + + +### `sim.getSimDet` + +```python +sim.getSimDet() +``` + +该方法用于获取SIM卡热插拔相关配置。 + + +**返回值描述:** + +成功: 返回元组数据,格式`(detenable, insertlevel)`,具体说明如下: + +| 参数 | 类型 | 含义 | +| ------------- | ---- | ---------------------------------------------- | +| `detenable` | 整型 | 开启或者关闭SIM卡热插拔功能,0:关闭 ,1:打开 | +| `insertlevel` | 整型 | 高低电平配置(0/1) | + +失败: 返回`-1`,整型。 + + + +>EC600N系列/EG912N系列/EG915N系列/EC600M系列/EC800M系列/EC200A系列部分模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存。 +> +>EC600G系列/EC800G系列/EC200U系列/EC600U系列/EG912U系列/EG915U系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/8/23之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +>EC600E系列/EC800E系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/9/12之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +>BG95M1/BG95M2/BG95M3/BG95M6/BG95M8系列模组支持SIM卡热插拔功能,配置需要重启才能生效,相关配置掉电保存。 +> +>EG800PCN_LA/EG800KCN_GC/EC800KCN_LC系列模组支持SIM卡热插拔功能,配置立即生效,但是掉电不保存。 +> +>以下型号不支持此接口: +> +>EC800MCN_LA/EC600MCN_LF/EC600MCN_CC/EC800MCN_GD/EG810MCN_GA/BC25/BG600LM3/EC600KCN_LC/EC800MCN_LF/BG95M9LA。 + + + +**示例:** + +```python +>>> import sim +>>> sim.getSimDet() +(1, 0) +``` + + + + + +## SIM卡切卡功能 + +### `sim.getCurSimid` + +```python +sim.getCurSimid() +``` + +该方法用于获取当前卡的SIM卡卡槽编号(simId)。 + +**返回值描述:** + +成功: 返回当前`simId`(`0`或`1`,分别表示`SIM1`或者`SIM2`),整型。 + +失败: 返回`-1`,整型。 + + + +>支持该方法的型号: +> +>EC600MCN/EC600MLA/EC800MCN_L/EG810MCN_GA/EG810MEU_LA/EC600ECN_LC/EC800GCN_LD/EG915NEA_AC。 +> +>EC200U/EC600U/EG912U/EG915U部分模组支持双卡单持功能,但是sim卡2的引脚存在复用情况,使用前请参考GPIO相关说明。 + + + +**示例:** + +```python +>>> import sim +>>> sim.getCurSimid() #获取当前卡,当前是卡1 +0 +``` + + + +### `sim.switchCard` + +```python +sim.switchCard(simId) +``` + +该方法用于sim卡切卡。 + +**参数描述:** + +- `simId` - SIM卡卡槽编号,整型值,0表示SIM1,1表示SIM2。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`-1`表示失败。 + + + +>支持该方法的模组: +> +>EC600MCN/EC600MLA/EC800MCN_L/EG810MCN_GA/EG810MEU_LA/EC600ECN_LC/EC800GCN_LD/EG915NEA_AC。 +> +>EC200U/EC600U/EG912U/EG915U部分模组支持双卡单持功能,但是sim卡2的引脚存在复用情况,使用前请参考GPIO相关说明。 +> +>注意当目标卡是当前卡时,[`sim.switchCard`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sim.html#%3Ccode%3Esim.switchCard%3C/code%3E)直接返回-1,不触发此接口设置的回调函数。 +> +>部分模组(如EC800GCN_LD系列)无法检测sim卡2是否已经插入,当sim卡2不存在时,允许切卡到sim卡2。 + + + +**示例:** + +```python +>>> import sim +>>> sim.getCurSimid() #获取当前卡,当前是卡1 +0 +>>> sim.switchCard(1) #切到卡2 +0 +>>> sim.getCurSimid() #获取当前卡,成功切到卡2 +1 +``` + + + +## 回调注册功能 + +### `sim.setCallback` + +```python +sim.setCallback(usrFun) +``` + +热插拔注册监听回调函数:用于注册监听回调函数。在开启SIM卡热插拔功能的情况下,当SIM卡有插拔动作,将调用此方法注册的回调函数。 + +**参数描述:** + +* `usrFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def usrFun(args): + pass +``` + +| 参数 | 类型 | 含义 | +| ------ | ---- | --------------------------------------------------------- | +| `args` | 整型 | 当前SIM卡插拔状态:`1` 表示SIM卡插入;`2` 表示 SIM卡拔出 | + +**返回值描述:** + +返回一个整型值,`0`表示注册成功,`-1`表示注册失败。 + + + +> EC600N系列/EG912N系列/EG915N系列/EC600M系列/EC800M系列/EC200A系列部分模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存。 +> +> EC600G系列/EC800G系列/EC200U系列/EC600U系列/EG912U系列/EG915U系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/8/23之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +> EC600E系列/EC800E系列模组支持SIM卡热插拔功能,配置立即生效,且相关配置掉电保存(2023/9/12之后的固件版本掉电保存,之前的固件版本掉电不保存)。 +> +> BG95M1/BG95M2/BG95M3/BG95M6/BG95M8系列模组支持SIM卡热插拔功能,配置需要重启才能生效,相关配置掉电保存。 +> +> EG800PCN_LA/EG800KCN_GC/EC800KCN_LC系列模组支持SIM卡热插拔功能,配置立即生效,但是掉电不保存。 +> +> 以下型号不支持此接口: +> +> EC800MCN_LA/EC600MCN_LF/EC600MCN_CC/EC800MCN_GD/EG810MCN_GA/BC25/BG600LM3/EC600KCN_LC/EC800MCN_LF/BG95M9LA。 + + + +**示例:** + +```python +import sim + +def usrCallback(args): + simstates = args + print('sim states:{}'.format(simstates)) + +sim.setCallback(usrCallback) +``` + + + +### `sim.setSwitchcardCallback` + +```python +sim.setSwitchcardCallback(usrFun) +``` + +该方法用于注册监听SIM卡切卡状态回调函数:注册监听回调函数,响应SIM卡切卡动作。 + +**参数描述:** + +* `usrFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def usrFun(args): + pass +``` + +| 参数 | 类型 | 含义 | +| ---- | ---- | ----------------------------------------------------------- | +| args | 整型 | 切换SIM卡结果:`7` -表示切换SIM成功,`8`- 表示切换SIM卡失败 | + +**返回值描述:** + +返回一个整型值,`0`表示注册成功,`-1`表示注册失败。 + + + +> 支持该方法的模组: +> +> EC600MCN/EC600MLA/EC800MCN_L/EG810MCN_GA/EG810MEU_LA/EC600ECN_LC/EC800GCN_LD/EG915NEA_AC。 +> +> EC200U/EC600U/EG912U/EG915U部分模组支持双卡单持功能,但是sim卡2的引脚存在复用情况,使用前请参考GPIO相关说明。 +> +> 注意当目标卡是当前卡时切卡方法[`sim.switchCard`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sim.html#%3Ccode%3Esim.switchCard%3C/code%3E)直接返回-1,不触发此接口设置的回调函数。 + + + +**示例:** + +```python +import sim + +def usrCallback(args): + switchcard_state = args + print('sim switchcard states:{}'.format(switchcard_state)) + +sim.setSwitchcardCallback(usrCallback) +``` diff --git a/docs/API_reference/zh/iotlib/sms.md b/docs/API_reference/zh/iotlib/sms.md new file mode 100644 index 0000000000000000000000000000000000000000..b307a6e215019fab46f0317ba064a61952110df0 --- /dev/null +++ b/docs/API_reference/zh/iotlib/sms.md @@ -0,0 +1,497 @@ +# sms - 短信功能 + +该模块提供短信功能相关方法,包括读取、发送、删除短信等方法。 + +> 以下型号不支持此模块功能,对于定制版本,根据实际功能为准: +> +> EC800GCN_LD/EC800GCN_LB/EC800MCN_LE/EC800MCN_GA/EC600MCN_LF/EC600MCN_LA/EC800MCN_GD/EC600MCN_CC/EG810MCN_GA/EC600MCN_LE/BC25/EC600GCN_LD/EC600KCN_LC/EC800MCN_LF/EC600GCN_LD。 + + + +## 发送短信 + +### `sms.sendTextMsg` + +``` +sms.sendTextMsg(phoneNumber, msg, codeMode) +``` + +该方法用于发送TEXT类型的消息(不支持发送空短信)。 + +**参数描述:** + +* `phoneNumber` - 接收方手机号码,字符串类型,最大长度不超过20字节。 +* `msg` - 待发送消息,字符串类型,单条短信长度不超过140个字节。 +* `codeMode` -使用的字符编码方式,字符串类型,取值范围如下: + +| 值 | 含义 | +| -------- | ---------------------------------------------- | +| `'GSM'` | GSM编码方式,用于发送英文短信 | +| `'UCS2'` | UCS2编码方式,可以用于发送中文短信以及英文短信 | + +**返回值描述:** + +返回一个整型值,`0`表示发送成功,`-1`表示发送失败。 + + + +> 仅以下系列支持长短信: +> +> EC600N/EG912N/EG915N/EC200A系列短信内容UCS2编码最多支持420字节,GSM编码最多支持960个字节长度。 +> +> EC200U/EC600U/EG912U/EG915U/BG95系列短信内容UCS2编码最多支持280个字节,GSM编码最多支持640个字节的短信长度。 +> +> 其余系列短信内容UCS2编码最多支持70个字节,GSM编码最多支持160个字节的短信长度。 + +**示例:** + +```python +# -*- coding: UTF-8 -*- +import sms + +sms.sendTextMsg('18158626517', '这是一条中文测试短信!', 'UCS2') +sms.sendTextMsg('18158626517', 'Hello, world.', 'GSM') +sms.sendTextMsg('18158626517', '这是一条夹杂中文与英文的测试短信,hello world!', 'UCS2') +``` + + + +### `sms.sendPduMsg` + +``` +sms.sendPduMsg(phoneNumber, msg, codeMode) +``` + +该方法用于发送PDU类型的消息(不支持发送空短信)。 + +**参数描述:** + +* `phoneNumber` - 接收方手机号码,字符串类型,最大长度不超过20字节。 +* `msg` - 待发送消息,字符串类型,单条短信长度不超过140个字节。 +* `codeMode` -使用的字符编码方式,字符串类型,取值范围如下: + +| 值 | 含义 | +| -------- | ---------------------------------------------- | +| `'GSM'` | GSM编码方式,用于发送英文短信 | +| `'UCS2'` | UCS2编码方式,可以用于发送中文短信以及英文短信 | + +**返回值描述:** + +返回一个整型值,`0`表示发送成功,`-1`表示发送失败。 + + + +> 仅以下系列支持长短信: +> +> EC600N/EG912N/EG915N/EC200A系列短信内容UCS2编码最多支持420字节,GSM编码最多支持960个字节长度。 +> +> EC200U/EC600U/EG912U/EG915U/BG95系列短信内容UCS2编码最多支持280个字节,GSM编码最多支持640个字节的短信长度。 +> +> 其余系列短信内容UCS2编码最多支持70个字节,GSM编码最多支持160个字节的短信长度。 + + + +**示例:** + +```python +# -*- coding: UTF-8 -*- +import sms + +sms.sendPduMsg('18158626517', 'send pdu msg by GSM mode.', 'GSM') +sms.sendPduMsg('18158626517', 'send pdu msg by UCS2 mode.', 'UCS2') +sms.sendPduMsg('18158626517', '这是一条中文测试短信!通过PDU-UCS2模式', 'UCS2') +``` + + + +## 删除短信 + +### `sms.deleteMsg` + +``` +sms.deleteMsg(index [, delmode]) +``` + +该方法用于删除指定索引的消息。 + +**参数描述:** + +* `index` - 索引号,整型值,需要删除短信的索引号。 +* `delmode` - 模式,整型值,可选参数,当不写时默认为0,具体如下: + +| 值 | 说明 | +| ---- | ------------------------- | +| 0 | 删除指定`index`索引的短信 | +| 4 | 删除全部短信 | + +**返回值描述:** + +返回一个整型值,`0`表示删除成功,`-1`表示删除失败。 + + + +> EC600G/EC800G系列仅支持sms.deleteMsg(index)方式调用,不支持sms.deleteMsg(index,delmode)方式调用。 + + + +**示例:** + +```python +>>> import sms +>>> sms.deleteMsg(2) #删除索引号为2的那一条短信 +0 +>>> sms.deleteMsg(1,4) #删除所有短信 +0 +``` + + + +## 短信存储位置配置 + +### `sms.setSaveLoc` + +``` +sms.setSaveLoc(mem1, mem2, mem3) +``` + +该方法用于设置短信的存储位置。 + +**参数描述:** + +* `mem1` - 读取和删除消息所在的位置,字符串类型,支持如下参数: + +| 值 | 含义 | +| ------ | --------------------- | +| `"SM"` | SIM消息存储
| +| `"ME"` | 移动设备信息存储
| +| `"MT"` | 暂不支持 | + +* `mem2` - 写入和发送消息所在的位置,字符串类型,支持参数同上`mem1`的值。 + +* `mem3` - 接收消息的存储位置,字符串类型,支持参数同上`mem1`的值。 + +**返回值描述:** + +返回一个整型值,`0`表示设置成功,`-1`表示设置失败。 + + + +> 更改短信存储位置时,请保持`mem1`、`mem2`、`mem3`的内容统一,均为`SM`或`ME`。 + + + +**示例:** + +```python +>>> import sms +>>> sms.setSaveLoc('SM', 'SM', 'SM') +0 +``` + + + +### `sms.getSaveLoc` + +``` +sms.getSaveLoc() +``` + +该方法用于获取当前模块短信存储位置相关信息。 + +**返回值描述:** + +成功: 返回元组数据,格式`([loc1, current_nums, max_nums],[loc2, current_nums, max_nums],[loc3, current_nums, max_nums])`,如下表: + +| 参数 | 类型 | 含义 | +| -------------- | ------ | ------------------------------------------------------------ | +| `loc1` | 字符串 | 读取和删除消息所在的位置,具体含义同[`sms.setSaveLoc`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sms.html#%3Ccode%3Esms.setSaveLoc%3C/code%3E)中`mem1`的值 | +| `loc2` | 字符串 | 写入和发送消息所在的位置,具体含义同[`sms.setSaveLoc`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sms.html#%3Ccode%3Esms.setSaveLoc%3C/code%3E)中`mem1`的值 | +| `loc3` | 字符串 | 接收消息的存储位置,具体含义同[`sms.setSaveLoc`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sms.html#%3Ccode%3Esms.setSaveLoc%3C/code%3E)中`mem1`的值 | +| `current_nums` | 整型 | 当前空间已有短信数量 | +| `max_nums` | 整型 | 当前空间最大短信存储数量 | + +失败:返回`-1`。 + +**示例:** + +```python +>>> sms.getSaveLoc() +(['SM', 2, 50], ['SM', 2, 50], ['SM', 2, 50]) +>>> sms.setSaveLoc('ME','ME','ME') +0 +>>> sms.getSaveLoc() +(['ME', 14, 180], ['ME', 14, 180], ['ME', 14, 180]) +``` + + + +## 获取短信的数量 + +### `sms.getMsgNums` + +``` +sms.getMsgNums() +``` + +该方法用于获取短信的数量。 + +**返回值描述:** + +成功: 返回短信数量值。失败: 返回`-1`。 + +**示例:** + +```python +>>> import sms +>>> sms.getMsgNums() # 执行本行前,先发送一条短信到模块 +1 +``` + + + +## 获取短信内容 + +### `sms.searchPduMsg` + +``` +sms.searchPduMsg(index) +``` + +该方法用于以PDU方式获取短信内容。 + +**参数描述:** + +* `index` - 需要获取短信的索引,整型值,范围`0 ~ MAX-1`,`MAX`为模块存储短信的最大数量。 + +**返回值描述:** + +成功: 返回字符串类型的PDU数据,为短信内容,包含收到短信的时间,所以相同短信内容的PDU数据是不同的。 + +失败: 返回整型`-1`。 + +**示例:** + +```python +>>> import sms +>>> sms.sendPduMsg('+8618226172342', '123456789aa', 'GSM') # 自己给自己发送一条短信 +>>> sms.searchPduMsg(0) # 以PDU方式获取短信内容,下面PDU格式短信需要解码后才能正常显示短信内容 +'0891683110305005F0240BA19169256015F70000022141013044230B31D98C56B3DD70B97018' +``` + + + +### `sms.searchTextMsg` + +``` +sms.searchTextMsg(index) +``` + +该方法用于以TEXT方式获取短信内容。 + +**参数描述:** + +* `index` - 需要获取短信的索引,整型值,范围`0 ~ MAX-1`,`MAX`为模块存储短信的最大数量。 + +**返回值描述:** + +成功: 返回元组数据,格式`(phoneNumber, msg, msgLen)`,具体参数如下: + +| 参数 | 类型 | 含义 | +| ------------- | ------ | -------------- | +| `phoneNumber` | 字符串 | 短信来源手机号 | +| `msg` | 字符串 | 短信内容 | +| `msgLen` | 整型 | 短信消息长度 | + +失败: 返回整型值`-1`。 + +**示例:** + +```python +>>> import sms +>>> sms.sendPduMsg('+8618226172342', '123456789aa', 'GSM') # 自己给自己发送一条短信 +>>> sms.searchTextMsg(0) # 以TEXT方式获取短信内容 +('+8618226172342', '123456789aa', 22) +``` + + + +## PDU短信解码 + +### `sms.getPduLength` + +```python +sms.getPduLength(pduMsg) +``` + +该方法用于获取指定PDU短信的长度。 + +**参数描述:** + +- `pduMsg` - PDU短信,字符串类型。 + +**返回值描述:** + +成功: 返回PDU短信长度,整型值。 + +失败: 返回`-1`。 + +**示例:** + +```python +>>> import sms +>>> sms.searchPduMsg(0) +'0891683108501505F0040D91688122162743F200000211529003332318C16030180C0683C16030180C0683E170381C0E87' +>>> sms.getPduLength(sms.searchPduMsg(0)) #注意,是获取PDU短信长度,不是上面字符串的长度 +40 +``` + + + +### `sms.decodePdu` + +```python +sms.decodePdu(pduMsg, pduLen) +``` + +该方法用于PDU解码,解析[`sms.searchPduMsg()`](https://developer.quectel.com/doc/quecpython/API_reference/zh/iotlib/sms.html#%3Ccode%3Esms.searchPduMsg%3C/code%3E)接口读取到的PDU数据。 + +**参数描述:** + +- `pduMsg` - PDU短信,字符串类型。 + +- `pduLen` - PDU短信长度,整型值。 + +**返回值描述:** + +成功: 返回元组数据,格式`(phoneNumber, msg, time, msgLen)`,具体参数如下: + +| 参数 | 类型 | 含义 | +| ------------- | ------ | -------------- | +| `phoneNumber` | 字符串 | 短信来源手机号 | +| `msg` | 字符串 | 短信内容 | +| `time` | 整型 | 收到短信的时间 | +| `msgLen` | 整型 | 短信消息长度 | + +失败: 返回整型值`-1`。 + +**示例:** + +```python +>>> import sms +>>>sms.decodePdu('0891683110305005F00405A10110F000081270319043442354516C76CA77ED4FE1FF1A00320030003200315E7496328303975E6CD596C68D445BA34F2067086D3B52A863D09192FF1A4E3B52A88FDC79BB975E6CD596C68D44FF0C5171540C5B8862A47F8E597D751F6D3B3002',20) +>>>('10010', '公益短信:2021年防范非法集资宣传月活动提醒:主动远离非法集资,共同守护美好生活。', '2021-07-13 09:34:44', 118) +``` + + + +## 短信中心号码配置 + +### `sms.getCenterAddr` + +```python +sms.getCenterAddr() +``` + +该方法用于获取短信中心号码。 + + +**返回值描述:** + +成功: 返回字符串类型的短信中心号码。 + +失败: 返回整型值`-1`。 + +**示例:** + +```python +>>> import sms +>>> sms.getCenterAddr() +'+8613800551500' +# 如果设置的短信中心号码不带+,实际查询和使用默认添加 + +``` + + + +### `sms.setCenterAddr` + +```python +sms.setCenterAddr(addr) +``` + +该方法用于设置短信中心号码。若无特殊需求,不建议更改短信中心号码。 + +**参数描述:** + +- `addr` - 需要设置的短信中心号码,字符串类型。 + + +**返回值描述:** + +返回一个整型值,`0`表示设置成功,`-1`表示设置失败。 + + + +## 回调注册功能 + +### `sms.setCallback` + +```python +sms.setCallback(usrFun) +``` + +该方法用于注册监听回调函数,当接收到短信时,调用此方法注册的回调函数。 + +**参数描述:** + +* `usrFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def usrFun(args): + pass +``` + +| 参数 | 类型 | 参数说明 | +| --------- | ------ | -------------------- | +| `args[0]` | 整型 | 当前SIM卡卡槽的simId | +| `args[1]` | 整型 | 短信索引 | +| `args[2]` | 字符串 | 短信存储位置 | + +**返回值描述:** + +返回一个整型值,`0`表示设置成功,`-1`表示设置失败。 + +**示例:** + +```python +# 示例一 +import sms + +def cb(args): + index = args[1] + storage = args[2] + print('New message! storage:{},index:{}'.format(storage, index)) + +sms.setCallback(cb) + +# 示例二 +# 2021-09-09之前发布的版本使用方法不同,如下所示,参照示例二: +import sms + +def cb(args): + ind_flag = args[0] + if ind_flag == 4097: + mes_buf, mes_len = args[1], args[2] + print('New message! ind_flag:{},mes_buf:{},mes_len:{}'.format(ind_flag, mes_buf, mes_len)) + elif ind_flag == 4099: + mes_type, storage, index = args[1], args[2], args[3] + print('New message! ind_flag:{},mes_type:{},storage:{},index:{}'.format(ind_flag, mes_type, storage, index)) + elif ind_flag == 4100: + mes_buf = args[1] + print('New message! ind_flag:{},mes_buf:{}'.format(ind_flag, mes_buf)) + elif ind_flag == 4101: + storage,index = args[1], args[2] + print('New message! ind_flag:{},storage:{},index:{}'.format(ind_flag, storage, index)) + +sms.setCallback(cb) +``` + diff --git a/docs/API_reference/zh/iotlib/ussd.md b/docs/API_reference/zh/iotlib/ussd.md new file mode 100644 index 0000000000000000000000000000000000000000..32e36d89ad373ade96e42d66a034c36cff07c255 --- /dev/null +++ b/docs/API_reference/zh/iotlib/ussd.md @@ -0,0 +1,236 @@ +# USSD - 非结构化补充数据业务 + +USSD(Unstructured Supplementary Service Data,非结构化补充数据业务)是一种基于全球移动通信系统GSM(Global System for Mobile Communications)网络的、实时在线的新型交互会话数据业务;它基于SIM卡,利用GSM网络的信令通道传送数据,是在GSM的短消息系统技术基础上推出的新业务,在业务开拓方面的能力远远强于SMS系统。 + +USSD使用字符组成代码,最长可支持182个字符.用户可以通过从各种菜单中进行选择来直接通过手机进行交互.与SMS消息不同,在USSD会话期间,USSD消息会创建实时连接.这意味着只要通信线路保持畅通,USSD就可以进行双向信息通信.因此,查询和回答几乎是即时的. + +USSD在会话过程中一直保持通话连接,提供透明通道,不进行存储转发;而SMS在物理承载层没有会话通道,是一个存储转发系统,用户完成一次查询需要进行多次会话过程.由于USSD与GPRS类似,在交互中保持一个会话过程,每次数据发送不需要重新建立信道,所以USSD系统对用户的呼叫请求是即时响应,使响应时间大大加快,主要的响应时延已转移为应用服务器一端,响应时间比短消息快. + + + +> 要支持USSD有3个条件: +> 1. 终端设备要支持USSD功能; +> 2. SIM卡支持; +> 3. 网络要支持,需要有USSD服务器; +> +> 中国境内目前运营商均不支持USSD功能,其它地区请咨询当地运营商。 +> +> 目前仅EC200UEU_AA和EG915ULA_AB_VOLTE支持USSD功能。 + + + +**示例:** + +```Python +>>> import ussd + +>>> def ussdCallback(args): +... print(args) +... +>>> ussd.setCallback(ussdCallback) # 注册回调函数 + +>>> ussd.send("*101#") # 向网络发送USSD指令 *101# +0 +>>> +(4, '', 0, 4) # 回调收到网络端回复的内容 + +>>> ussd.getSessionState() #查询是否处于连续会话状态 +False + +``` + +## 回调注册功能 + +### `ussd.setCallback` + +``` +ussd.setCallback(fun) +``` + +注册回调函数。在回调函数中接收针对网络端或网络发起操作的 USSD 响应,只要收到网络端的USSD消息,均会触发此回调。 + +**参数描述:** + +* `fun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```python +def ussdCallback(args): + pass +``` + +| 参数 | 类型 | 含义 | +| --------- | ------ | ------------------------------------------------------------ | +| `args[0]` | 整型 | 网络响应状态。
`0`响应成功,返回网络回复的字符串类型内容,见`args[1]`;
`1`响应成功,结束会话;
`2`、`3`响应成功,无回复内容;
`4`本地错误/网络拒绝/网络返回错误。 | +| `args[1]` | 字符串 | 收到的网络端响应USSD消息内容。只有`args[0]`为0时为正常字符串,其它为空字符串; | +| `args[2]` | 整型 | 网络下发USSD的 DCS。 DCS: 小区广播数据编码方案。 | +| `args[4]` | 整型 | 异常状态错误码。 | + +**示例:** + +```python +import ussd + +def ussdCallback(args): + resp_type = args[0] + ussd_str = args[1] + dcs = args[2] + err_code = args[3] + if resp_type == 0: + print('### USSD Network successful return:',ussd_str) + elif resp_type == 1: + print('### USSD end of session.' + elif resp_type in [2,3]: + print('### USSD Network successful return None') + else: + print('### USSD Network return error,err_code:',err_code) +ussd.setCallback(ussdCallback) +``` + + + +## 发送USSD指令 + +### `ussd.send` + +``` +ussd.send(reqstr) +``` + +该方法用于向网络发送USSD指令,默认DCS等于15。网络回复的结果直接在回调函数中展示。 + +**参数描述:** + +* `reqstr`- 发送至网络的 USSD,字符串类型,不可为空,范围1~159字节。 + +**返回值描述:** + +返回一个整型值,`0`表示发送成功,`-1`表示发送失败。 + +**示例:** + +```python +>>> ussd +>>> ussd.send("*101#") # 向网络发送USSD指令。 +0 +``` + + + +## 查询会话状态 + +### `ussd.getSessionState` + +``` +ussd.getSessionState() +``` + +该方法用于查询USSD的会话状态,当处于连续会话状态时,进一步的用户操作。 + +**返回值描述:** + + 返回布尔类型,`False`非连续会话状态,无需进一步的用户操作(网络发起的 USSD 通知,或设备发起的操作后无需进一步的信息); + +`True`连续会话状态,需要进一步的用户操作(网络发起的 USSD 请求或 设备发起操作后需要进一步信息)。 + + + +> 当`ussd.getSessionState()`返回值为`True`时,网络端会一直保存与用户交互的会话通道,需要用户进一步操作,有两种操作方式: +> +> 1. 继续使用`ussd.send`发送USSD指令,与网络端交互; +> 2. 使用`ussd.stopSession`结束连续会话状态; + +**示例:** + +```python +>>> import ussd +>>> ussd.getSessionState() +False +``` + + + +## 结束连续会话状态 + +### ``ussd.stopSession`` + +``` +ussd.stopSession() +``` + +该方法用于结束连续会话状态,释放网络端保存的USSD会话通道,会触发结束会话的USSD回调函数,`args[0]`等于1。 + +**返回值描述:** + +返回一个整型值,`0`表示结束会话成功,`-1`表示失败或无需结束会话状态。 + +```python +>>> import ussd +>>> ussd.getSessionState() +True +>>> ussd.stopSession() +0 +``` + + + +## DCS配置与查询 + +### `ussd.getDcs` + +``` +ussd.getDcs() +``` + +该方法用于查询发送USSD指令的小区广播数据编码方案。 + +**返回值描述:** + + 返回发送USSD指令小区广播数据编码方案DCS,整型,范围 1~ 17, 68, 72, 240。 + + + +>DCS: 3GPP TS 23.038 小区广播数据编码方案。默认值:15,一般无需设置。 + + + +**示例:** + +```python +>>> import ussd +>>> ussd.getDcs() +15 +``` + + + +### `ussd.setDcs` + +``` +ussd.getDcs(Dcs) +``` + +该方法用于设置发送USSD指令的DCS。 + +**参数描述:** + +* `Dcs`- 小区广播数据编码方案,整型,范围 `0~ 17, 68, 72, 240`;当为0时,表示恢复默认值。 + +**返回值描述:** + + 返回一个整型值,`0`表示成功,`-1`表示失败。 + +**示例:** + +```python +>>> import ussd +>>> ussd.getDcs() +15 +>>> import ussd +>>> ussd.setDcs(1) +0 +>>> ussd.getDcs() +1 +``` + + + diff --git a/docs/API_reference/zh/iotlib/voiceCall.md b/docs/API_reference/zh/iotlib/voiceCall.md new file mode 100644 index 0000000000000000000000000000000000000000..718b932762a3a5be51c16c8cf6e53d50865b7614 --- /dev/null +++ b/docs/API_reference/zh/iotlib/voiceCall.md @@ -0,0 +1,773 @@ +# voiceCall - 电话功能 + +该模块提供电话功能相关接口。 + + + +>* 支持voiceCall功能的模组: +> EC600N系列:EC600NCN_LC/EC600NCN_LD/EC600NCN_LF +> EG912N系列:EG912NEN_AA +> EG915N系列:EG915NEU_AG/EG915NEA_AC +> EC200A系列:EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA +> EC200U系列:EC200UAU_AA/EC200UAU_AB/EC200UCN_AA/EC200UEU_AA/EC200UEU_AB +> EC600U系列:EC600UEU_AB/EC600UEC_AC/EC600ULA_AC +> EG912U系列:EG912UGL_AA/EG912UGL_AC +> EG915U系列:EG915UEU_AB/EG915ULA_AB +> * BC25/BC32/EC600G/EC800G/BG95系列模组不支持voiceCall功能。 +> * EC600M/EC800M/EG810M系列模组需要支持VOLTE功能固件才支持voiceCall功能。 +> * 其他系列模组需要定制版本才能支持voiceCall功能。 + + + +## 设置自动应答时间 + +### `voiceCall.setAutoAnswer` + +```python +voiceCall.setAutoAnswer(seconds) +``` + +该方法用于设置自动应答时间。 + +**参数描述:** + +* `seconds` - 自动应答时间,整型值,单位/s,范围:0-255。 + +**返回值描述:** + + 成功返回整型`0`,失败返回整型`-1`。 + + + +> EC200U/EC600U/EG912U/EG915U系列的模组,设置的`seconds`代表的是来电自动应答前的振铃次数。单位是“振铃次数”而不是秒。 +> +> 如果是基于voLTE的IMS电话,`seconds` 代表的是是否使能自动应答,`0`:关闭自动应答;`非0`:开启自动应答,无应答时间的设置。 + + + +**示例:** + +```python +>>> import voiceCall +>>> voiceCall.setAutoAnswer(5) +0 +``` + + + +## 拨打电话 + +### `voiceCall.callStart` + +```python +voiceCall.callStart(phonenum) +``` + +该方法用于主动拨打电话。 + +**参数描述:** + +* `phonenum` - 接收方电话号码,字符串类型。 + +**返回值描述:** + + 成功返回整型`0`,失败返回整型`-1`。 + +**示例:** + +```python +>>> import voiceCall +>>> voiceCall.callStart("13855169092") +0 +``` + + + +## 接听电话 + +### `voiceCall.callAnswer` + +```python +voiceCall.callAnswer() +``` + +该方法用于接听电话。 + +**返回值描述:** + + 成功返回整型`0`,失败返回整型`-1`。 + +**示例:** + +```python +>>> voiceCall.callAnswer() +0 +``` + + + +## 挂断电话 + +### `voiceCall.callEnd` + +```python +voiceCall.callEnd() +``` + +该方法用于挂断电话。 + +**返回值描述:** + + 成功返回整型`0`,失败返回整型`-1`。 + +**示例:** + +```python +>>> import voiceCall +>>> voiceCall.callEnd() +0 +``` + + + +## 回调注册功能 + +### `voiceCall.setCallback` + +```python +voiceCall.setCallback(voicecallFun) +``` + +该方法用于注册回调函数。监听不同的通话状态并通过回调反馈给用户。 + +**参数描述:** + +* `voicecallFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: +```python +def voicecallFun(args): + pass +``` +`args[0]` - 通话状态,整型值,回调函数的参数个数并不是固定的,而是根据第一个参数`args[0]`来决定,如下表: + +| 值 | 参数个数 | args[0]值说明 | 其他参数说明 | +| ---- | -------- | --------------------------------------------- | ------------------------------------------------------------ | +| 1 | 1 | voicecall初始化成功(底层完成,无需用户干预) | | +| 2 | 3 | 来电通知,响铃 | `args[1]`:呼叫识别号码
`args[2]`:电话号码 | +| 3 | 3 | 通话接通 | `args[1]`:呼叫识别号
`args[2]`:电话号码 | +| 4 | 3 | 通话挂断 | `args[1]`:呼叫识别号码
`args[2]`:通话挂断原因 | +| 5 | 1 | 未知错误 | | +| 6 | 5 | 呼叫等待 | `args[1]`:呼叫识别号码
`args[2]`:电话号码
`args[3]`:号码类型[129/145],129:非国际号码,145:国际号码
`args[4]`:CLI状态 | +| 7 | 1 | 呼出中 | | +| 8 | 4 | 呼出失败 | `args[1]`:呼叫识别号码
`args[2]`:呼叫失败原因
`args[3]`:指示是否可以从网络端获得in-band tones | +| 9 | 3 | 等待 | `args[1]`:呼叫识别号码
`args[2]`:电话号码 | +| 10 | 8 | 来电通知,响铃(volte通话) | `args[1]`:呼叫识别号码
`args[2]`:呼叫方向(MO/MT)
`args[3]`:通话状态
`args[4]`:业务类型(这里一般都是0,表示voice call,语音通话业务)
`args[5]`:多方通话标志
`args[6]`:电话号码
`args[7]`:号码类型
`args[8]`:保留 | +| 11 | 8 | 通话接通(volte通话) | `args[1] ~ args[8]`:具体说明同上 | +| 12 | 8 | 通话挂断(volte通话) | `args[1] ~ args[8]`:具体说明同上 | +| 13 | 8 | 呼叫等待(volte通话) | `args[1] ~ args[8]`:具体说明同上 | +| 14 | 8 | 呼出中(volte通话) | `args[1] ~ args[8]`:具体说明同上 | +| 15 | 8 | 呼出中,对方未响铃(volte通话) | `args[1] ~ args[8]`:具体说明同上 | +| 16 | 8 | 等待(volte通话) | `args[1] ~ args[8]`:具体说明同上 | + + + +关于`args[0]`的值为10-16时,`args[1]`-`args[8]`的详细说明: + +| args[n] | 说明 | 类型 | 参数值 | +| ------- | ------------ | ------ | ------------------------------------------------------------ | +| args[1] | 呼叫识别号码 | 整型 | 用于区分活跃呼叫的唯一数字ID。通常取值1-n,其中n是模块支持的最大并发呼叫数量。 | +| args[2] | 呼叫方向 | 整型 | 0 - 主叫(MO)
1 - 被叫(MT) | +| args[3] | 通话状态 | 整型 | 0 - 激活状态
1 - 呼叫保持状态
2 - 主叫,拨号状态
3 - 主叫,回铃音状态
4 - 被叫,来电状态
5 - 被叫,呼叫等待状态
6 - 通话挂断状态 | +| args[4] | 业务类型 | 整型 | 0 - 语音呼叫
1 - 数据呼叫
2 - 传真 | +| args[5] | 多方通话标志 | 整型 | 0 - 不在多方通话中
1 - 在多方通话中 | +| args[6] | 电话号码 | 字符串 | 对端电话号码 | +| args[7] | 号码类型 | 整型 | 129 - 非国际号码/未知类型
145 - 国际号码(包含字符“+”)
161 - 国家号码 | +| args[8] | 保留 | 整型 | 保留 | + + + +**返回值描述:** + +注册成功返回整型`0`,失败返回整型`-1`。 + +**示例:** + +```python +>>> import voiceCall +def voice_callback(args): + if not isinstance(args, tuple): + print('voicecall is GSM call, args:', args) + elif args[0] == 10: + print('voicecall incoming call, PhoneNO: ', args[6]) + elif args[0] == 11: + print('voicecall connected, PhoneNO: ', args[6]) + elif args[0] == 12: + print('voicecall disconnect') + elif args[0] == 13: + print('voicecall is waiting, PhoneNO: ', args[6]) + elif args[0] == 14: + print('voicecall dialing, PhoneNO: ', args[6]) + elif args[0] == 15: + print('voicecall alerting, PhoneNO: ', args[6]) + elif args[0] == 16: + print('voicecall holding, PhoneNO: ', args[6]) + else: + print('voicecall is GSM call, args:', args) + +>>> voiceCall.setCallback(voice_callback) +0 +>>> voiceCall.callStart('10086') +0 +``` + + + +>* 1、以上仅适用2021-09-09之后发布的支持语音通话的版本 +>* 2、QPY_V0004_EC600N_CNLC_FW_VOLTE(2021-09-09发布)之前发布的版本都按照以下规则使用voiceCall + + + +`args[0]` - 通话状态,整型值,参数个数及其他参数含义如下表: + +| 值 | 参数个数 | args[0]值说明 | 其他参数说明 | +| ---- | -------- | --------------------------- | ------------------------------------------------------------ | +| 4103 | 8 | 来电通知,响铃(volte通话) | `args[1]`:呼叫识别号码
`args[2]`:呼叫方向(MO/MT)
`args[3]`:通话状态
`args[4]`:业务类型(这里一般都是0,表示voice call,语音通话业务)
`args[5]`:多方通话标志,0:非多方通话 1:多方通话
`args[6]`:电话号码
`args[7]`:号码类型[129/145],129:非国际号码,145:国际号码 | +| 4104 | 8 | 通话接通(volte通话) | `args[1] ~ args[7]`:具体说明同上 | +| 4105 | 8 | 通话挂断(volte通话) | `args[1] ~ args[7]`:具体说明同上 | +| 4106 | 8 | 呼叫等待(volte通话) | `args[1] ~ args[7]`:具体说明同上 | + +**示例:** + +```python +>>> import voiceCall +def voice_callback(args): + if args[0] == 4106: + print('voicecall is waiting') + elif args[0] == 4105: + print('voicecall disconnect') + elif args[0] == 4104: + print('voicecall connected, CallNO: ', args[6]) + elif args[0] == 4103: + print('voicecall incoming call, PhoneNO: ', args[6]) +``` + + + +## 来电自动挂断功能 + +### `voiceCall.setAutoCancel` + +```python +voiceCall.setAutoCancel(enable) +``` + +该方法用于使能来电自动挂断功能。 + +**参数描述:** + +* `enable` - 开启或者关闭来电自动挂断功能,`1`:开启,`0`:关闭 (默认不开启)。 + +**返回值描述:** + + 成功返回整型`0`,失败返回整型`-1`。 + + + +>EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA系列模组支持该功能。 + + + +**示例:** + +```python +>>> import voiceCall +#手机呼叫模块,默认不会自动挂断 +>>> voiceCall.getAutoCancelStatus() +0 + +#设置自动挂断功能,手机呼叫模块,默认自动挂断 +>>> voiceCall.setAutoCancel(1) +0 +>>> voiceCall.getAutoCancelStatus() +1 +``` + + + +### `voiceCall.getAutoCancelStatus` + +```python +voiceCall.getAutoCancelStatus() +``` + +该方法用于获取来电自动挂断使能状态。 + +**返回值描述:** + +`0`:来电自动挂断使能关闭,来电不会被模组自动挂断。 + +`1`:来电自动挂断使能开启,来电会被模组自动挂断。 + + + +> EC200AAU_HA/EC200ACN_DA/EC200ACN_HA/EC200ACN_LA/EC200AEU_HA系列模组支持该功能。 + + + +**示例:** + +```python +>>> import voiceCall +#手机呼叫模块,默认不会自动挂断 +>>> voiceCall.getAutoCancelStatus() +0 + +#设置自动挂断功能,手机呼叫模块,默认自动挂断 +>>> voiceCall.setAutoCancel(1) +0 +>>> voiceCall.getAutoCancelStatus() +1 +``` + + + +## DTMF识别功能 + +### `voiceCall.startDtmf` + +```python +voiceCall.startDtmf(dtmf, duration) +``` + +该方法用于设置DTMF音。 + +**参数描述:** + +* `dtmf` - DTMF字符串,字符串类型,最大字符数:6个,有效字符数有:`0-9、A、B、C、D、*、#`。 +* `duration` - 持续时间,整型值,范围:100-1000,单位:毫秒。 + +**返回值描述:** + + 设置成功返回整型`0`,设置失败返回整型`-1`。 + + + +>该方法仅在语音通话过程中使用生效 +> +>支持单次发送多个字符(2024/4/2之后单次最多发送6个字符。) + + + +**示例:** + +```python +>>> import voiceCall +>>> voiceCall.startDtmf('A',100) +0 +``` + + + +### `voiceCall.dtmfDetEnable` + +```python +voiceCall.dtmfDetEnable(enable) +``` + +该方法用于使能DTMF识别功能,默认不开启DTMF识别。 + +**参数描述:** + +* `enable` - 使能开关,整型值,取值`0/1`,`0`:不开启DTMF识别,`1`:开启DTMF识别。 + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`。 + + + +>支持voiceCall功能的模组型号中,EC600N/EC800N/EG912N/EG915N系列支持该方法。 + + + +### `voiceCall.dtmfSetCb` + +```python +voiceCall.dtmfSetCb(dtmfFun) +``` + +该方法用于注册DTMF识别功能的回调接口。 + +**参数描述:** + +* `dtmfFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: + +```Python +def dtmfFun(args): + pass +``` + +| 参数 | 类型 | 含义 | +| ------- | ---- | ------------------------------------------ | +| `args` | 字符串 | 对端输入的DTMF字符 | + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`。 + + + +>支持voiceCall功能的模组型号中,EC600N/EC600S/EC800N/EG912N/EG915N系列支持该方法。 + + + +**示例:** + +```python +>>> import voiceCall +>>> def cb(args): +... print(args) + +>>> voiceCall.dtmfSetCb(cb) +0 +>>> voiceCall.dtmfDetEnable(1) +0 +>>> voiceCall.callStart('13855169092') +0 +>>> +1 #手机端按下1,callback中会收到按下的字符“1” + +8 #手机端按下8 + +9 #手机端按下9 +``` + + + +## 设置呼叫转移 + +### `voiceCall.setFw` + +```python +voiceCall.setFw(reason, fwmode, phonenum) +``` + +该方法用于控制呼叫转移补充业务。 + +**参数描述:** + +* `reason` - 呼叫转移的条件,整型值,具体如下说明: + +| 值 | 参数说明 | +| -- | ------------- | +| 0 | 无条件的 | +| 1 | 用户忙 | +| 2 | 用户无响应 | +| 3 | 用户不可达 | + +* `fwMode` - 对呼叫转移的控制,整型值,具体如下说明: + +| 值 | 参数说明 | +| -- | ------------- | +| 0 | 禁用 | +| 1 | 启用 | +| 2 | 查询状态 | +| 3 | 注册 | +| 4 | 擦除 | + +* `phonenum` - 呼叫转移的目标电话,字符串类型 + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`。 + +> ​ 呼叫转移功能需要先向sim卡运营商开通呼叫转移功能后,启用呼叫转移才能使用。 + + + +## 切换语音通道 + +### `voiceCall.setChannel` + +```python +voiceCall.setChannel(device) +``` + +该方法用于设置通话时的声音输出通道,默认是通道0,即听筒。 + +**参数描述:** + +* `device` - 输出通道,整型值,具体如下说明: + +| 值 | 参数说明 | +| -- | ------------- | +| 0 | 听筒 | +| 1 | 耳机 | +| 2 | 喇叭 | + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`。 + +**示例:** + +```python +>>> voiceCall.setChannel(2) #切换到喇叭通道 +0 +``` + + + +## 音量大小配置 + +### `voiceCall.getVolume` + +```python +voiceCall.getVolume() +``` + +该方法用于获取电话当前音量大小。 + +**返回值描述:** + +返回整型音量值。 + + + +### `voiceCall.setVolume` + +```python +voiceCall.setVolume(volume) +``` + +该方法用于设置电话音量大小。 + +**参数描述:** + +* `volume` - 音量等级,整型值,范围`(0 ~ 11)`,数值越大,音量越大。 + +**返回值描述:** + +设置成功返回整型`0`,失败返回整型`-1`。 + + + +## 自动录音功能 + + +### `voiceCall.setAutoRecord` + +```python +voiceCall.setAutoRecord(enable, recordType, recordMode, filename) +``` + +该接口用于使能自动录音功能。默认关闭自动录音,自动录音使能需要在通话前设置完毕。 + +**参数描述:** + +* `enable` - 使能开关,整型值,取值0或1,`0`:关闭自动录音功能 ,`1`:开启自动录音功能。 +* `recordType` - 录音文件类型,整型值,具体如下: + +| 值 | 说明 | +| -------------- | ---- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - 模式,整型值,具体如下: + +| 值 |说明 | +|-----|--------| +| 0 | 表示录制的是下行链路通道的音频数据,即对端的声音。 | +| 1 | 表示录制的是上行链路通道的音频数据,即本端的声音。 | +| 2 | 表示录制的是上行链路通道和下行链路通道的混合音频流。 | + +* `filename` - 期望存储的文件名,字符串类型,需包含完整路径。 + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`, 不支持该接口返回字符串`"NOT SUPPORT"`。 + +**示例:** + +```python +>>> voiceCall.setAutoRecord(1,0,2,'U:/test.amr') +0 +``` + + + +> EC200U/EC600U/EG912U/EG915U系列模组,`recordMode`实际仅支持模式2。 +> +> QuecPython目前不支持在创建文件时,自动创建子目录。比如`filename`为'U:/record/test.amr',如果usr目录下实际没有'record'目录存在,则需要用户先使用`uos.mkdir('/usr/record')`来创建'record'目录。 + + + +### `voiceCall.startRecord` + +```python +voiceCall.startRecord(recordType, recordMode, filename) +``` + +该方法用于开始通话录音。 + +**参数描述:** + +* `recordType` - 录音文件类型,整型值,具体如下: + +| 值 | 说明 | +|-----| ---- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - 模式,整型值,具体如下: + +| 值 |说明 | +|------|--------| +| 0 | 表示录制的是下行链路通道的音频数据,即对端的声音。 | +| 1 | 表示录制的是上行链路通道的音频数据,即本端的声音。 | +| 2 | 表示录制的是上行链路通道和下行链路通道的混合音频流。 | + +* `filename` - 期望存储的文件名,字符串类型,需包含完整路径。 + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`,不支持该接口返回字符串`"NOT SUPPORT"`。 + +**示例:** + +```python +>>> import voiceCall +>>> voiceCall.startRecord(0,2,'U:/test.amr') +0 +``` + + + +> EC200U/EC600U/EG912U/EG915U系列模组,`recordMode`实际仅支持模式2。 +> +> QuecPython目前不支持在创建文件时,自动创建子目录。比如`filename`为'U:/record/test.amr',如果usr目录下实际没有'record'目录存在,则需要用户先使用`uos.mkdir('/usr/record')`来创建'record'目录。 + + + +### `voiceCall.stopRecord` + +```python +voiceCall.stopRecord() +``` + +该方法用于停止通话录音。 + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`, 不支持该接口返回字符串`"NOT SUPPORT"`。 + +**示例:** + +```python +>>> voiceCall.stopRecord() +0 +``` + + + +### `voiceCall.readRecordStream` + +```python +voiceCall.readRecordStream(readBuf, bufLen) +``` + +该方法用于读取录音流数据。 + +**参数描述:** + +* `readBuf` - 存储读取到的数据,用于保存读取到的数据。 + +* `bufLen` - 期望读取的字符串长度(不能超过readBuf申请的字节长度)。 + +**返回值描述:** + +读取成功返回读取到的数据长度,读取失败返回整型`-1`,不支持该接口返回字符串`"NOT SUPPORT"`。 + + + +>* 录音流第一包数据均是对应格式文件的文件头 +>* wav格式录音流第一包数据不包含文件大小,需结束录音后自行计算 + + + +### `voiceCall.startRecordStream` + +```python +voiceCall.startRecordStream(recordType, recordMode, callbackFun) +``` + +该方法用于开始通话录音(流形式)。 + +**参数描述:** + +* `recordType` - 录音文件类型,整型值,具体如下: + +| 值 | 说明 | +|-------| ---- | +| 0 | AMR | +| 1 | WAV | + +* `recordMode` - 模式,整型值,具体如下: + +| 值 |说明 | +|------|--------| +| 0 | RX | +| 1 | TX | +| 2 | MIX | + +* `callbackFun` - 回调函数名,回调函数格式以及回调函数的参数说明如下: +```python +def recordStreamCallback(args): + pass +``` +| 参数 | 类型 | 含义 | +| ------- | ---- | -------------------- | +| `args[0]` | 字符串 | 录音流数据 | +| `args[1]` | 整型 | 录音流数据长度 | +| `args[2]` | 整型 | 录音状态
-1:录音出错
0:开始录音
1:返回录音数据
2:录音暂停
3:录音结束
4:空间满 | + +**返回值描述:** + +设置成功返回整型`0`,设置失败返回整型`-1`,不支持该接口返回字符串`"NOT SUPPORT"`。 + + + +>* 录音流第一包数据均是对应格式文件的文件头 +>* wav格式录音流第一包数据不包含文件大小,需结束录音后自行计算 + + + +**示例:** + +```python +>>> import voiceCall +>>> import audio + +>>> f=open('usr/mia.amr','w') + +>>> def cb(para): +... if(para[2] == 1): +... read_buf = bytearray(para[1]) +... voiceCall.readRecordStream(read_buf,para[1]) +... f.write(read_buf,para[1]) +... del read_buf +... elif(para[2] == 3): +... f.close() +... +>>> voiceCall.callStart('13855169092') +0 +>>> voiceCall.startRecordStream(0,2,cb) +0 +# 此处挂断电话(MO/MT侧挂断都可以) +>>> uos.listdir('usr') +['system_config.json', 'mia.amr'] +>>> aud=audio.Audio(0) +>>> aud.setVolume(11) +0 +>>> aud.play(2,1,'U:/mia.amr') +0 +``` \ No newline at end of file diff --git "a/docs/API_reference/zh/media/README/QuecPython\346\236\266\346\236\204.png" "b/docs/API_reference/zh/media/README/QuecPython\346\236\266\346\236\204.png" new file mode 100644 index 0000000000000000000000000000000000000000..acc9d53eb3c2578f858de146888971b0112701cd Binary files /dev/null and "b/docs/API_reference/zh/media/README/QuecPython\346\236\266\346\236\204.png" differ diff --git a/docs/API_reference/zh/medialib/README.md b/docs/API_reference/zh/medialib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c9e7a5464250cf01a7d8fd2d9589af151a491a94 --- /dev/null +++ b/docs/API_reference/zh/medialib/README.md @@ -0,0 +1,11 @@ +# QuecPython 多媒体 + +> QuecPython 多媒体库包括拍照、音频、二维码等功能组件 + +本文描述了 QuecPython 多媒体库中的模块。 + +## QuecPython 多媒体库列表 + +- [camera - 摄像头](./camera.md) +- [audio - 音频播放](./audio.md) +- [qrcode - 二维码显示](./qrcode.md) \ No newline at end of file diff --git a/docs/API_reference/zh/medialib/audio.Audio.md b/docs/API_reference/zh/medialib/audio.Audio.md new file mode 100644 index 0000000000000000000000000000000000000000..e58cff7681ae088eebcbe3d3addd4750d7c3b9b3 --- /dev/null +++ b/docs/API_reference/zh/medialib/audio.Audio.md @@ -0,0 +1,301 @@ +# class Audio - 音频播放 + +该类提供音频播放功能。 + +> 目前支持型号:EC600N系列、EC800N系列、EC600M-CN(LA、LE)、EC800M-CN(LA、LE、GA)、EG810MCN_GA、EC600U系列、EC200U系列、EG912U、EG915U、EG915N-EUAG。 + +## 构造函数 + +### `audio.Audio` + +```python +class audio.Audio(device) +``` + +创建Audio对象。 + +**参数描述:** + +- `device` - 输出通道,int类型,0表示听筒,1表示耳机,2表示喇叭。具体模块所支持通道详见下表。 + +**模块输出通道对应表:** + +| 模块型号 | 听筒 | 耳机 | 喇叭 | +| --------------------- | ------ | ------ | ------ | +| EC200N/EC600N/EC800N | 支持 | 不支持 | 不支持 | +| EC600M-CN(LA、LE) | 支持 | 不支持 | 不支持 | +| EC800M-CN(LA、LE、GA) | 支持 | 不支持 | 不支持 | +| EG810M | 支持 | 不支持 | 不支持 | +| EG915N/EG912N | 支持 | 不支持 | 不支持 | +| EG912U | 支持 | 不支持 | 不支持 | +| EC200U | 不支持 | 不支持 | 支持 | +| EC600U | 支持 | 支持 | 支持 | +| EG915U | 支持 | 支持 | 不支持 | +| EC600S | 支持 | 不支持 | 不支持 | +| EC600K/EC800K | 支持 | 不支持 | 不支持 | +| EC800G-CN(GA、TT、LA) | 支持 | 支持 | 支持 | +| EC600G-CN(LA) | 支持 | 支持 | 支持 | + +## 方法 + +### `Audio.set_pa` + +```python +Audio.set_pa(gpio,num) +``` + +该方法用于设置输出pa的gpio。 + +**参数描述:** + +- `gpio` - 输出的gpio,int类型,参照[Pin](../peripherals/machine.Pin.md)。 +- `num` - 上电脉冲数,int类型。 + +**返回值描述:** + +`1` 表示成功,`0`表示失败。 + +### `Audio.play` + +```python +Audio.play(priority, breakin, filename) +``` + +该方法用于音频文件播放。 + +支持mp3、amr和wav格式文件播放。支持优先级0 ~ 4,数字越大优先级越高,每个优先级组可同时最多加入10个播放任务,与TTS播放共用同一个播放队列。 + +> **说明:**由于TTS和音频文件播放共用同一个播放队列,所以TTS中设置的播放优先级、打断模式不仅仅是和其他TTS播放任务比较,还会和音频文件播放任务的优先级和打断模式比较,反之,音频文件播放中设置的播放优先级与打断模式对TTS任务同样是有效的。 + +**参数描述:** + +- `priority` - 播放优先级,int类型。支持优先级0 ~ 4,数值越大优先级越高。 +- `breakin` - 打断模式,int类型。0表示不允许被打断,1表示允许被打断。 +- `filename` - 模式,string类型。待播放的文件名称,包含文件存放路径。点此查看文件播放路径的说明。 + +**返回值描述:** + +`0` 表示播放成功; + +`-1`表示播放失败; + +`1` 表示无法立即播放,加入播放队列; + +`-2`表示无法立即播放,且该请求的优先级组队列任务已达上限,无法加入播放队列。 + +**文件播放路径的说明:** + +用户分区路径固定为’U:/‘开头,表示用户分区的根目录,如果用户在根目录下新建audio目录,并将音频文件存放在根目录下的audio目录,那么播放接口中,传入的路径参数应该是:'U:/audio/music.mp3'。 + +### `Audio.stop` + +```python +Audio.stop() +``` + +该方法用于停止当前正在播放的音频。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Audio.stopAll` + +```python +Audio.stopAll() +``` + +该方法用于停止整个队列的播放。即当前如果正在播放Audio或者音频,并且队列中还有其他待播放内容,调用该方法后,不仅会停止当前播放的内容,还会清除这个队列的内容,不再播放任何内容。如果当前正在播放,且播放队列为空,那么调用该方法效果等同与[stop()](https://developer.quectel.com/doc/quecpython/API_reference/zh/medialib/audio.Audio.html#%3Ccode%3EAudio.stop%3C/code%3E)接口。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Audio.setCallback` + +```python +Audio.setCallback(cb) +``` + +该方法用于注册用户的回调函数,用于通知用户音频文件播放状态。 + +> 该回调函数中不要进行耗时以及阻塞性的操作,建议只进行简单、耗时短的操作。 + +**参数描述:** + +`cb` - 用户回调函数,function类型,函数原型: + +```python +def cb(event): + pass +``` + +**回调函数参数描述**: + + - `event` - 播放状态,int类型,点此查看回调函数参数event说明表。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +**回调函数参数event说明表** + +| event | 表示状态 | +| ----- | -------- | +| 0 | 开始播放 | +| 7 | 播放完成 | + +### `Audio.getState` + +```python +Audio.getState() +``` + +该方法用于获取audio初始化状态。 + +**返回值描述:** + +`0` 表示audio初始化完成,`-1`表示audio初始化未完成。 + +### `Audio.getVolume` + +```python +Audio.getVolume() +``` + +该方法用于获取当前播放音量大小,音量值在区间[0 ~ 11],0表示静音。 + +**返回值描述:** + +整型音量大小值。 + +### `Audio.setVolume` + +```python +Audio.setVolume(vol) +``` + +该方法用于设置播放音量大小,音量值在区间[0 ~ 11],0表示静音。 + +**参数描述:** + +- `vol` - 音量大小,int类型,区间[0 ~ 11]。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Audio.playStream` + +```python +Audio.playStream(format, buf) +``` + +该方法用于音频流播放,支持mp3、amr和wav格式的音频流播放。 + +> 说明:播放 AMR 格式音频流时,若音频来源于文件,建议在开始读取文件后跳过开头 6 个字节(即文件头),否则可能导致播放失败。 + +**参数描述:** + +- `format` - 音频流格式,int类型,`2` - `WAVPCM`,`3` - `MP3`,`4` - `AMRNB`。 +- `buf` - 音频流内容,音频流二进制文件内容。 + +**返回值描述:** + +`0`表示播放成功,`-1`表示播放失败。 + +### `Audio.stopPlayStream` + +```python +Audio.stopPlayStream() +``` + +该方法用于停止音频流播放。 + +**参数描述:** + +无 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Audio.aud_tone_play` + +```python +Audio.aud_tone_play(tone, time) +``` + +该方法用于播放tone音,播放一段时间(time)后自动停止播放。 + +> EC600N/EC800N系列模组调用该接口为立即返回,EC600U/EC200U系列模组调用该接口为阻塞等待。 + +**参数描述:** + +- `tone` - tone类型,int型,`0~15`:按键音(0~9、A、B、C、D、#、*),`16`:拨号音。 +- `time` - 播放时长,单位ms,int型,`0` : 不停止一直播放。 + +**返回值描述:** + +`0` 表示播放成功,`-1`表示播放失败。 + +### `Audio.aud_tone_play_stop` + +```python +Audio.aud_tone_play_stop() +``` + +该方法用于主动停止播放tone音。 + +**返回值描述:** + +`0` 表示停止播放成功,`-1`表示停止播放失败。 + +**示例:** + +```python +# -*- coding: UTF-8 -*- +import audio +from machine import Pin +import utime +import uos + +def audio_cb(event): + if event == 0: + print('audio-play start.') + elif event == 7: + print('audio-play finish.') + +aud = audio.Audio(0) +aud.setCallback(audio_cb) +# 设置pa +aud.set_pa(Pin.GPIO15,2) +# 播放MP3 +aud.play(2, 1, 'U:/music.mp3') +utime.sleep(5) +aud.stop() + +# 音频流播放 +size = 10*1024 # 保证一次填充的音频数据足够大以便底层连续播放 +format = 4 + +def play_from_fs(): + file_size = uos.stat("/usr/test.amr")[6] # 获取文件总字节数 + print(file_size) + with open("/usr/test.amr", "rb")as f: + if format == 4: + f.read(6) # 跳过6字节的AMR文件头 + while 1: + b = f.read(size) # read + if not b: + break + aud.playStream(format, b) + utime.sleep_ms(20) + + +play_from_fs() +# 等待播放完成 +utime.sleep_ms(5000) +# 停止本次播放以便不影响下次播放 +aud.stopPlayStream() +``` diff --git a/docs/API_reference/zh/medialib/audio.PCM.md b/docs/API_reference/zh/medialib/audio.PCM.md new file mode 100644 index 0000000000000000000000000000000000000000..ce8df4dc6a759b72c1414396fc2ad2323b22c4e8 --- /dev/null +++ b/docs/API_reference/zh/medialib/audio.PCM.md @@ -0,0 +1,438 @@ +# class PCM - PCM音频数据编码 + +该类提供PCM音频数据的读写接口,PCM数据可用于音频编码。 + +> 所有支持audio的型号均支持PCM。 + +## 创建对象 + +### `audio.Audio.PCM` + +```python +class audio.Audio.PCM(mic_dev, channel, samplerate, flag,mode, periodcnt) +``` + +创建Audio对象。 + +**参数描述:** + + +* 参数说明详见下表 + +| 参数 | 参数类型 | 参数说明 | +| ------------ | -------- | ------------------------------------------------------------ | +| `mic_dev` | int | mic通道:
`0` - 听筒
`1` - 耳机
`2` - 自动 | +| `channel` | int | 通道数:
`1`:单声道( PCM.MONO)
`2`:立体音(PCM.STEREO) | +| `samplerate` | int | 采样率:
8000, 16000 | +| `flag` | int | 模式:
`0`:只读(PCM.READONLY)
`1`:只写(PCM.WRITEONLY)
`2`:读写(PCM.WRITEREAD) | +| `mode` | int | 阻塞(缺省值为1):
`1`:阻塞式(PCM.BLOCK)
`2`:非阻塞式(PCM.NOBLOCK) | +| `periodcnt` | int | 缓存buf大小,取值范围:`[2,25]`
单位为帧。 一帧20ms,缺省值为3(即默认最多储存3帧数据) | + +**示例:** + +```python +from audio import Audio +pcm = Audio.PCM(1, Audio.PCM.MONO, 8000, Audio.PCM.WRITEREAD, Audio.PCM.BLOCK) +``` + +## 方法 + +### `PCM.read` + +```python +PCM.read(size) +``` + +该方法用于读取模组MIC录音的PCM数据。 + +**参数描述:** + +- `size` - 最大读取数据量,int类型,单位字节。(单次读取的数据量不超过设置的缓存buf大小) + +> 注:录音时间可根据采样率,通道数,采样精度计算,具体计算公式为: +> +> 时间(s)=想要获取的数据量(byte) / (采样率(hz) * 通道数(channel) * 采样精度(byte/sample) ) +> +> 例如:设置采样率8000,单声道,想读取数据size=320。模组PCM采样精度为2,所以该接口录音时间为0.02s + +**返回值描述:** + +成功返回数据buffer; + +失败则返回`-1`。 + +### `PCM.write` + +```python +PCM.write(buff) +``` + +该方法用于写入将要进行播放的PCM数据。 + +**参数描述:** + +- `buff` - 需要写入的PCM数据,bytearray类型。 + +**返回值描述:** + +成功返回写入的数据量; + +失败则返回`-1`。 + +**示例:** + +```python +from audio import Audio +pcm = Audio.PCM(1, Audio.PCM.MONO, 8000, Audio.PCM.WRITEREAD, Audio.PCM.BLOCK) + +pcm_buf = pcm.read(320) +pcm.write(pcm_buf) +``` + +### `PCM.close` + +```python +PCM.close() +``` + +该方法用于关闭PCM,释放相应资源。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `PCM.setVolume` + +```python +PCM.setVolume(vol) +``` + +该方法用于设置播放音量大小,音量值在区间[0 ~ 11],0表示静音。 + +**参数描述:** + +- `vol` - 音量大小,int类型,区间[0 ~ 11]。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +> 注:该方法设置的是audio播放音量,与Audio.setVolume设置音量效果相同 + +### `PCM.getVolume` + +```python +PCM.getVolume() +``` + +该方法用于获取当前播放音量大小,音量值在区间[0 ~ 11],0表示静音。 + +**返回值描述:** + +整型音量大小值。 + + + +## 音频编码-G711 + +该模块用于G711格式的录音和音频播放。 + +### 构造函数 + +```python +class G711(pcm) +``` + +创建G711对象。 + +**参数描述:** + +- `device` - PCM对象,obj类型,见[PCM](#创建对象)。(G711默认只支持8K采样率,创建PCM对象时请注意此问题) + +**示例:** + +```python +import G711 +import audio + +pcm = audio.Audio.PCM(0, 1, 8000, 2) +g711 = G711(pcm) +``` + +### `G711.read` + +该方法用于读取G711格式录音数据,单次输出一帧录音数据(一帧录音时间为20ms,8k采样率下数据长度为160字节)。 + +```python +G711.read(format) +``` + +**参数描述:** + +- `format` - 编码格式,int类型,`0`:A-LAW,`1`:U-LAW。 + +**返回值描述:** + +成功则返回音频buffer; + +失败则返回`-1`。 + +> 注:通常PCM数据按G711格式编码后数据量只有原先的1/2,反之G711解码为PCM后数据量为原先的2倍。 + + +### `G711.write` + +该方法用于将G711音频数据解码,并播放。 + +```python +G711.write(buffer, format) +``` + +**参数描述:** + +- `format` - 音频数据的编码格式,int类型,`0`:A-LAW,`1`:U-LAW。 +- `buff` - 需要解码的音频数据,bytearray类型。 + +**返回值描述:** + +成功返回写入的解码后的数据量; + +失败则返回`-1`。 + +**示例:** + +```python +import G711 +import audio +import uos + +pcm = audio.Audio.PCM(0, 1, 8000, 2) +g711 = G711(pcm) +#g711 code +def g711_compress(frame): + f = open("/usr/test.g711", "wb") + count = frame + while count: + count-=1 + g711_buf = g711.read(0) + print("len:",len(g711_buf)) + if(len(g711_buf) > 0): + f.write(g711_buf) + f.close() +#g711 decode +def g711_decompression(): + file_size = uos.stat("/usr/test.g711")[6] # get file size + print(file_size) + with open("/usr/test.g711", "rb")as f: + while 1: + b = f.read(320) + if not b: + break + write_len = g711.write(b, 0) + f.close() + +if __name__ == "__main__": + g711_compress(200) + g711_decompression() +``` + + + +## 音频编码-G722 + +该模块用于G722格式的录音和音频播放。 + +### 构造函数 + +```python +class G722(pcm, bitrate) +``` + +创建G722对象。 + +**参数描述:** + +- `device` - PCM对象,obj类型,见[PCM](#创建对象)。(G722默认支持16K采样率,创建PCM对象时请注意此问题) +- `bitrate` - 比特率,int类型,可选值:`64000` , `56000`,`48000`。 + +**示例:** + +```python +import G722 +import audio + +pcm = audio.Audio.PCM(0, 1, 16000, 2) +g722 = G722(pcm, 64000) +``` + +### `G722.read` + +该方法用于读取G722格式录音数据,单次输出一帧录音数据(一帧录音时间为20ms,16k采样率下数据长度为160字节)。 + +```python +G722.read() +``` + +**返回值描述:** + +成功则返回音频buffer; + +失败则直接报错。 + +> 注:通常PCM数据按G722编码后数据量只有原先的1/4,反之G722解码为PCM后数据量为原先的4倍。 + +### `G722.write` + +该方法用于将G722音频数据解码成PCM,并放入播放缓存中进行播放。 + +```python +G722.write(buffer) +``` + +**参数描述:** + +- `buff` - 需要解码的音频数据,bytearray类型。 + +**返回值描述:** + +成功返回写入的数据量; + +失败则返回`-1`。 + +**示例:** + +```python +import audio +import G722 +import uos + +pcm = audio.Audio.PCM(0, 1, 16000, 2, 1) +g722 = G722(pcm, 64000) +#g722 code +def g722_compress(frame): + f = open("/usr/test.g722", "wb") + count = frame + while count: + count-=1 + g722_buf = g722.read() + print("len:",len(g722_buf)) + if(len(g722_buf) > 0): + f.write(g722_buf) + f.close() +#g722 decode +def g722_decompression(): + file_size = uos.stat("/usr/test.g722")[6] # get file size + print("size=",file_size) + with open("/usr/test.g722", "rb")as f: + while 1: + b = f.read(160) + if not b: + break + write_len = g722.write(b) + f.close() + +if __name__ == "__main__": + g722_compress(200) + g722_decompression() +``` + + + +## 音频编码-G729 + +该模块用于G729格式的录音和音频播放。 + +### 构造函数 + +```python +class G729(pcm) +``` + +创建G729对象。(G729默认支持8K采样率,创建PCM对象时请注意此问题) + +**参数描述:** + +- `device` - PCM对象,obj类型,见[PCM](#创建对象)。 + +**示例:** + +```python +import G729 +import audio + +pcm = audio.Audio.PCM(0, 1, 8000, 2) +g729 = G729(pcm) +``` + +### `G729.read` + +该方法用于读取G722格式录音数据,单次输出一帧录音数据(一帧录音数据长度为20字节)。 + +```python +G729.read() +``` + +**返回值描述:** + +成功则返回音频buffer; + +失败则直接报错。 + +> 注:通常PCM数据按G729编码后数据量只有原先的1/16,反之G729解码为PCM后数据量为原先的16倍。 + + +### `G729.write` + +该方法用于将G729音频数据解码成PCM,并放入播放缓存中进行播放。 + +```python +G729.write(buffer) +``` + +**参数描述:** + +- `buff` - 需要解码的音频数据,bytearray类型。 + +**返回值描述:** + +成功返回写入的数据量; + +失败则返回`-1`。 + +**示例:** + +```python +import audio +import G729 +import uos + +pcm = audio.Audio.PCM(0, 1, 8000, 2, 1) +g729 = G729(pcm) +#g729 code +def g729_compress(frame): + f = open("/usr/test.g729", "wb") + count = frame + while count: + count-=1 + g729_buf = g729.read() + print("len:",len(g729_buf)) + if(len(g729_buf) > 0): + f.write(g729_buf) + f.close() +#g729 decode +def g729_decompression(): + file_size = uos.stat("/usr/test.g729")[6] # get file size + print("size=",file_size) + with open("/usr/test.g729", "rb")as f: + while 1: + b = f.read(20) + if not b: + break + write_len = g729.write(b) + f.close() + +if __name__ == "__main__": + g729_compress(200) + g729_decompression() +``` + diff --git a/docs/API_reference/zh/medialib/audio.Record.md b/docs/API_reference/zh/medialib/audio.Record.md new file mode 100644 index 0000000000000000000000000000000000000000..41c15e206ec7f2a95f2048c69f5678f9d3f89791 --- /dev/null +++ b/docs/API_reference/zh/medialib/audio.Record.md @@ -0,0 +1,460 @@ + + +# class Record - 录音 + +该类提供录音功能。 + +> 目前支持型号:EC600N系列、EC800N系列、EC600M-CN(LA、LE)、EC800M-CN(LA、LE、GA)、EG810MCN_GA、EC600U系列、EC200U系列、EG912U、EG915U、EG915N-EUAG。 + +## 构造函数 + +### `audio.Record` + +```python +class audio.Record(device) +``` + +创建Record对象。 + +> 如果传参,请与audio.Audio(device)的参数保持一致。 + +**参数描述:** + +- `device` - 输出通道,int类型,0表示听筒,1表示耳机,2表示喇叭,缺省值为`0`。具体模块所支持通道详见下表。 + +**模块输出通道对应表** + +| 模块型号 | 听筒 | 耳机 | 喇叭 | +| --------------------- | ------ | ------ | ------ | +| EC200N/EC600N/EC800N | 支持 | 不支持 | 不支持 | +| EC600M-CN(LA、LE) | 支持 | 不支持 | 不支持 | +| EC800M-CN(LA、LE、GA) | 支持 | 不支持 | 不支持 | +| EG810M | 支持 | 不支持 | 不支持 | +| EG915N/EG912N | 支持 | 不支持 | 不支持 | +| EG912U | 支持 | 不支持 | 不支持 | +| EC200U | 不支持 | 不支持 | 支持 | +| EC600U | 支持 | 支持 | 支持 | +| EG915U | 支持 | 支持 | 不支持 | +| EC600S | 支持 | 不支持 | 不支持 | +| EC600K/EC800K | 支持 | 不支持 | 不支持 | +| EC800G-CN(GA、TT、LA) | 支持 | 支持 | 支持 | +| EC600G-CN(LA) | 支持 | 支持 | 支持 | + +## 方法 + +### `Record.start` + +```python +Record.start(file_name,seconds) +``` + +该方法用于开始录音,录音数据储存为文件。 + +> 注:该方法录制AMR、WAV格式的文件时,默认采样率为8000,录制MP3格式时,默认采样率为22050。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 +- `seconds` - 需要录制时长,单位:秒,int类型。 + +**返回值描述:** + +`0`表示成功。 + +`-1`表示文件覆盖失败。 + +`-2`表示文件打开失败。 + +`-3`表示文件正在使用。 + +`-4`表示通道设置错误。 + +`-5`表示定时器资源申请失败。 + +`-6` 表示音频格式检测错误。 + +### `Record.stop` + +```python +Record.stop() +``` + +该方法用于停止录音。 + +**返回值描述:** + +`0` 表示播放成功,`-1`表示播放失败。 + +### `Record.getFilePath` + +```python +Record.getFilePath(file_name) +``` + +该方法用于读取录音文件的路径。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 + +**返回值描述:** + +成功返回string类型的录音文件路径。 + +`-1`表示目标文件不存在。 + +`-2`表示文件名长度为0。 + +### `Record.getData` + +```python +Record.getData(file_name, offset, size) +``` + +该方法用于读取录音数据。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 +- `offset` - 读取数据的偏移量,int类型。 +- `size` - 读取大小,单位字节,int类型。注意 :需小于10K。 + +**返回值描述:** + +成功返回录音数据,bytearray类型。 + +失败返回值说明如下: + +`-1`表示读取数据错误。 + +`-2`表示文件打开失败。 + +`-3`表示偏移量设置错误。 + +`-4`表示文件正在使用。 + +`-5`表示设置超出文件大小(offset+size > file_size)。 + +`-6`表示读取size 大于10K。 + +`-7`表示内存不足10K。 + +### `Record.getSize` + +```python +Record.getSize(file_name) +``` + +该方法用于读取录音文件大小。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 + +**返回值描述:** + +若获取成功,返回文件大小 ,单位字节。 + +失败返回值如下: + +`-1`表示获取文件大小失败。 + +`-2`表示文件打开失败。 + +`-3`表示文件正在使用 。 + +`-4`表示文件名长度为0。 + +### `Record.Delete` + +```python +Record.Delete(file_name) +``` + +该方法用于删除录音文件。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 + +**返回值描述:** + +`0`表示成功。 + +`-1`表示文件不存在。 + +`-2`表示文件正在使用。 + +### `Record.exists` + +```python +Record.exists(file_name) +``` + +该方法用于判断录音文件是否存在。 + +**参数描述:** + +- `file_name` - 录音文件名,string类型。 + +**返回值描述:** + +`true`表示文件存在。 + +`false`表示文件不存在。 + +### `Record.isBusy` + +```python +Record.isBusy() +``` + +该方法用于判断是否正在录音。 + +**返回值描述:** + +`0`表示不在录音,`1`表示正在录音。 + +### `Record.end_callback` + +```python +Record.end_callback(cb) +``` + +该方法用于设置录音结束回调。 + +**参数描述:** + +`cb` - 录音结束回调函数,function类型,函数原型: + +```python +def cb(audio_msg): + pass +``` + +**回调函数参数描述**: + + - `audio_msg` - 录音信息,list类型,其中元素如下: + + ​ `audio_msg[0]`:`file_path` ,文件路径,string类型。 + + ​ `audio_msg[1]`:`audio_len` , 录音长度,int类型。 + + ​ `audio_msg[2]`:`audio_state` ,录音状态,int类型,点此查看回调函数参数audio_state说明表。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +**audio_state说明表:** + +| event | 说明 | +| ----- | -------- | +| -1 | 发生错误 | +| 0 | 录音开始 | +| 3 | 录音结束 | + +### `Record.gain_set` + +```python +Record.gain_set(code_gain,dsp_gain) +``` + +该方法用于设置录音增益。 + +> 目前仅EC200N/EC600N/EC800N/EC600S/EG915N/EC600M/EC800M/EG810M/EG800P系列模组支持该功能。 + +**参数描述:** + +- `code_gain` - 上行编解码器增益,int型,[0,4]。 +- `dsp_gain` - 上行数字增益,int型,`-36~12` 。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Record.gain_get` + +```python +Record.gain_get() +``` + +该方法获取设置的录音增益。 + +> 目前仅EC200N/EC600N/EC800N/EC600S/EG915N/EC600M/EC800M/EG810M/EG800P系列模组支持该功能。 + +**参数描述:** + +无参数 + +**返回值描述:** + +返回值是一个元组,返回值形式为:`(code_gain, dsp_gain)` + +- `code_gain` - 上行编解码器增益。 +- `dsp_gain` - 上行数字增益。 + +### `Record.amrEncDtx_enable` + +```python +Record.amrEncDtx_enable(on_off) +``` + +该方法用于配置amr录音DTX功能开关。 + +> 目前仅EC600N/EC800N系列模组支持该功能。 + +**参数描述:** + +- `on_off` - 开关,int型,`1`:开启,`0`:关闭 。 +- 不传参数 - 获取当前配置 + +**返回值描述:** + +不传参:返回当前配置。 + +传参:参数正确无返回,参数错误抛异常。 + +### `Record.stream_start` + +```python +Record.stream_start(format, samplerate, time) +``` + +该方法用于开始录音音频流。注意:录制音频流的同时,应及时读取音频流。目前是采用循环buf,最大缓存8K字节数据,不及时读取,会导致数据丢失。 + +**参数描述:** + +- `format` - 音频格式,int型,见常量。不同的模组项目所能支持录制的音频格式不同,支持情况需咨询移远技术人员。 +- `samplerate` - 采样率,int型,除MP3格式外,目前支持8000 和 16000,MP3格式下只支持22050 。 +- `time` - 录音时长,int型,单位 S (秒),设置为0表示持续录音,直到使用`Record.stream_stop`接口停止。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `Record.stream_read` + +```python +Record.stream_read(read_buf, len) +``` + +该方法用于读取录音流。 + +**参数描述** + +- `read_buf` - 录音流buf,bytearray型 。 +- `len` - 读取的长度,int类型。 + +**返回值描述:** + +成功返回实际读取的字节数,失败返回整型-1。 + +### `Record.stream_stop` + +```python +Record.stream_stop() +``` + +该方法用于停止录音流录制。 + +**参数描述** + +无参数。 + +**返回值描述:** + +成功返回实际读取的字节数,失败返回整型-1。 + +## 常量 + +| 常量 | 值 | 说明 | +| ---------------- | ---- | ----------------------------------------------------------- | +| `Record.PCM` | 1 | 录制PCM格式的音频数据 | +| `Record.WAV` | 2 | 录制WAV格式的音频数据,录制该格式时录制时间需设置为`0` | +| `Record.MP3` | 3 | 录制MP3格式的音频数据 | +| `Record.AMRNB` | 4 | 录制AMR-NB格式的音频数据,录制该格式时采样率需设置为`8000` | +| `Record.AMRWB` | 5 | 录制AMR-WB格式的音频数据,录制该格式时采样率需设置为`16000` | +| `Record.OGGOPUS` | 11 | 录制OggOpus格式的音频数据 | + +**示例:** + +```python +# -*- coding: UTF-8 -*- +#文件录音 +import utime +import audio +from machine import Pin + + +flag = 1 +''' +外接喇叭播放录音文件,参数选择0 +''' +aud = audio.Audio(0) +tts = audio.TTS(0) + +aud.setVolume(11) + +def record_callback(args): + global flag + print('file_name:{}'.format(args[0])) + print('file_size:{}'.format(args[1])) + print('record_sta:{}'.format(args[2])) + + record_sta = args[2] + if record_sta == 3: + print('The recording is over, play it') + tts.play(1, 0, 2, '录音结束,准备播放录音文件') + aud.play(1, 0, record.getFilePath('recordfile.wav')) + flag = 0 + elif record_sta == -1: + print('The recording failure.') + tts.play(1, 0, 2, '录音失败') + flag = 0 + +record = audio.Record() +record.end_callback(record_callback) +record.start('recordfile.wav', 10) + +while 1: + if flag: + utime.sleep_ms(200) + else: + break +``` + +```python +# -*- coding: UTF-8 -*- +#录音流 +import audio +''' +外接喇叭播放录音文件,参数选择0 +''' +rec = audio.Record(0) +aud = audio.Audio(0) + +record_time = 10 +buf = bytearray(0) #空buff用来缓存音频 +aud_type = rec.AMRNB + +aud.setVolume(10) + +def stream_rec_cb(para): + global buf + print("para:", para) + if(para[0] == 'stream'): + if(para[2] == 1): + read_buf = bytearray(para[1]) + rec.stream_read(read_buf,para[1]) + buf += read_buf + del read_buf + elif (para[2] == 3): + pass + aud.stopPlayStream() + aud.playStream(aud_type, buf) + +rec.end_callback(stream_rec_cb) +rec.stream_start(aud_type, 8000, record_time) +``` + diff --git a/docs/API_reference/zh/medialib/audio.TTS.md b/docs/API_reference/zh/medialib/audio.TTS.md new file mode 100644 index 0000000000000000000000000000000000000000..6e72bc0c22370cbdd3bfa15a47f8fba6ad1cb89a --- /dev/null +++ b/docs/API_reference/zh/medialib/audio.TTS.md @@ -0,0 +1,414 @@ + + +# class TTS - 文本到语音播放 + +该类提供从文本到语音播放功能。 + +> 目前支持型号:EC600N系列、EC800N系列、EC600M-CN(LA、LE)、EC800M-CN(LA、LE、GA)、EG810MCN_GA、EC600U-CN系列、EC200U-CN系列。 + +## 构造函数 + +### `audio.TTS` + +```python +class audio.TTS(device) +``` + +创建TTS对象。 + +**参数描述:** + +- `device` - 输出通道,int类型,0表示听筒,1表示耳机,2表示喇叭。具体模块所支持通道详见下表。 + +**模块输出通道对应表:** + +| 模块型号 | 听筒 | 耳机 | 喇叭 | +| --------------------- | ------ | ------ | ------ | +| EC200N/EC600N/EC800N | 支持 | 不支持 | 不支持 | +| EC600M-CN(LA、LE) | 支持 | 不支持 | 不支持 | +| EC800M-CN(LA、LE、GA) | 支持 | 不支持 | 不支持 | +| EG810M | 支持 | 不支持 | 不支持 | +| EG915N/EG912N | 支持 | 不支持 | 不支持 | +| EG912U | 支持 | 不支持 | 不支持 | +| EC200U | 不支持 | 不支持 | 支持 | +| EC600U | 支持 | 支持 | 支持 | +| EG915U | 支持 | 支持 | 不支持 | +| EC600S | 支持 | 不支持 | 不支持 | +| EC600K/EC800K | 支持 | 不支持 | 不支持 | +| EC800G-CN(GA、TT、LA) | 支持 | 支持 | 支持 | +| EC600G-CN(LA) | 支持 | 支持 | 支持 | + +## 方法 + +### `TTS.close` + +```python +TTS.close() +``` + +该方法用于关闭TTS功能。 + +**返回值描述:** + +`0` 表示关闭成功,`-1`表示关闭失败。 + +### `TTS.play` + +```python +TTS.play(priority, breakin, mode, str) +``` + +该方法用于开始语音播放。点此查看TTS.play方法使用实例。 + +支持优先级0 ~ 4,数字越大优先级越高,每个优先级组可同时最多加入10个播放任务;播放策略说明如下: + +1. 如果当前正在播放任务A,并且允许被打断,此时有高优先级播放任务B,那么会打断当前低优先级播放任务A,直接播放高优先级任务B。 + +2. 如果当前正在播放任务A,并且不允许被打断,此时有高优先级播放任务B,那么B播放任务将会加入到播放队列中合适的位置,等待A播放完成,再依次从队列中按照优先级从高到低播放其他任务。 + +3. 如果当前正在播放任务A,且不允许被打断,此时来了一个同优先级播放任务B,那么B会被加入到该优先级组播放队列队尾,等待A播放完成,再依次从队列中按照优先级从高到低播放其他任务。 + +4. 如果当前正在播放任务A,且允许被打断,此时来了一个同优先级播放任务B,那么会打断当前播放任务A,直接播放任务B。 + +5. 如果当前正在播放任务A,且任务A的优先级组播放队列中已经有几个播放任务存在,且该优先级组播放队列最后一个任务N是允许被打断的,此时如果来了一个同样优先级的播放任务B,那么任务B会直接覆盖掉任务N;也就是说,某个优先级组,只有最后一个元素是允许被打断的,即breakin为1,其他任务都是不允许被打断的。 + +6. 如果当前正在播放任务A,不管任务A是否允许被打断,此时来了一个优先级低于任务A的请求B,那么将B加入到B对应优先级组播放队列。 + +**参数描述:** + +- `priority` - 播放优先级,int类型。支持优先级0 ~ 4,数值越大优先级越高。 +- `breakin` - 打断模式,int类型。0表示不允许被打断,1表示允许被打断。 +- `mode` - 模式,int类型。由低四位和高四位构成,其中低四位是编码模式,高四位是WTTS模式。点此查看TTS模式说明表。 +- `str` - 待播放字符串,string类型。 + +**返回值描述:** + +`0` 表示播放成功; + +`-1`表示播放失败; + +`1` 表示无法立即播放,加入播放队列; + +`-2`表示无法立即播放,且该请求的优先级组队列任务已达上限,无法加入播放队列。 + +**TTS模式说明表:** + +| 模式 | 说明 | +| -------- | ------------------------------------------------------------ | +| 编码模式 | 1 - UNICODE16(UTF-16大端模式)
2 - UTF-8
3 - UNICODE16(UTF-16小端模式) | +| WTTS模式 | 仅600N系列支持VOLTE的版本支持,
wtts_enable - wtts总开关
wtts_ul_enable - wtts上行使能
wtts_dl_enable - wtts下行使能 | + +**TTS.play方法使用实例:** + +- **TTS播放策略实例:** + +```python +>>> import audio +>>> tts = audio.TTS(1) +# case1:正在播放任务A,且A允许被打断,此时任务B到来,且优先级高于任务A,那么A会被打断,直接播放B +>>> tts.play(1, 1, 2, '111') #任务A +0 +>>> tts.play(2, 0, 2, '222') #任务B +0 + +# case2:正在播放任务A,且A不允许被打断,此时任务B到来,且优先级高于任务A,那么B会被加入播放队列,等待A播放完成播放B(假设播放队列之前为空) +>>> tts.play(1, 0, 2, '111') #任务A +0 +>>> tts.play(2, 0, 2, '222') #任务B +1 + +# case3:正在播放任务A,且A允许被打断,此时任务B到来,且优先级和A优先级一样,那么A会被打断,直接播放B +>>> tts.play(2, 1, 2, '222') #任务A +0 +>>> tts.play(2, 0, 2, '333') #任务B +0 + +# case4:正在播放任务A,且A不允许被打断,此时任务B到来,且优先级和A优先级一样,那么B会被加入播放队列,等待A播放完成播放B(假设播放队列之前为空) +>>> tts.play(2, 0, 2, '222') #任务A +0 +>>> tts.play(2, 0, 2, '333') #任务B +1 + +# case5:正在播放A,且A不允许被打断,此时任务B到来,且任务B允许被打断,优先级与A相同,那么任务B会被加入到播放队列中,此时任务C到来,且优先级和A、B相同,此时C会被加入播放队列中,且直接覆盖率任务B,A播放完成下一个播放的是C(假设播放队列之前为空) +>>> tts.play(2, 0, 2, '222') #任务A +0 +>>> tts.play(2, 1, 2, '333') #任务B +1 +>>> tts.play(2, 0, 2, '444') #任务C +1 + +# 播放UTF16BE模式的语音 +>>> tts.play(1,1,1,'6B228FCE4F7F752879FB8FDC901A4FE16A2157573002') +0 + +# 播放UTF16LE模式的语音 +>>> tts.play(1,1,3,'226BCE8F7F4F2875FB79DC8F1A90E14F216A57570230') +0 + +# 支持VOLTE的版本,可以播放tts到远端 +>>> import voiceCall +>>> voiceCall.callStart('1xxxxxxxxxx') +0 + +# 待电话接通后 +# 播放tts语音至通话远端 +>>> tts.play(1,1,tts.wtts_enable|tts.wtts_ul_enable|2, '12345') +0 +``` + +- **TTS播放中文示例:** + + > python文件开头需要加上`# -*- coding: UTF-8 -*-`。 + +```python +# -*- coding: UTF-8 -*- +import audio + +tts = audio.TTS(1) +str1 = '移联万物,志高行远' +tts.play(4, 0, 2, str1) +``` + +- **TTS播放文本标注实例:** + + 如遇TTS播放时不能达到预期的,可以通过文本标注的方式让TTS播放符合预期。 + + 数字播放的方式: + +```python +# 格式:[n*] (*=0/1/2) +# TTS引擎自动决定是以号码形式播放还是以数值的形式播放 +>>> tts.play(1,1,2, '12345') +0 + +# TTS引擎以号码形式播放 +>>> tts.play(1,1,2, '[n1]12345') +0 + +# TTS引擎以数值形式播放 +>>> tts.play(1,1,2, '[n2]12345') +0 +``` + +- **TTS语速设置实例:** + +```python +# 格式:[s*] (*=0 ~ 10) +# TTS引擎以默认语速5播放语音 +>>> tts.play(1,1,2, '12345') +0 + +# TTS引擎以默认语速的一半播放语音 +>>> tts.play(1,1,2, '[s0]12345') +0 + +# TTS引擎以默认语速的2倍语速播放语音 +>>> tts.play(1,1,2, '[s10]12345') +0 +``` + +- **TTS语调设置实例:** + +```python +# 格式:[t*] (*=0 ~ 10) +# TTS引擎以默认语调5播放语音 +>>> tts.play(1,1,2, '12345') +0 + +# TTS引擎以默认语调基频减64Hz播放语音 +>>> tts.play(1,1,2, '[t0]12345') +0 + +# TTS引擎以默认语调基频加128Hz播放语音 +>>> tts.play(1,1,2, '[t10]12345') +0 +``` + +- **汉字指定拼音实例:** + +```python +# 格式:[=*] (*=拼音) +# 汉字:声调用后接一位数字 1 ~ 5 分别表示 阴平、阳平、上声、去声和轻声 5个声调。 +>>> tts.play(1,1,2, '乐[=le4]') +0 + +>>> tts.play(1,1,2, '乐[=yue4]') +0 +``` + + + +### `TTS.stop` + +```python +TTS.stop() +``` + +该方法用于停止TTS播放。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `TTS.stopAll` + +```python +TTS.stopAll() +``` + +该方法用于停止整个队列的播放。即当前如果正在播放TTS或者音频,并且队列中还有其他待播放内容,调用该方法后,不仅会停止当前播放的内容,还会清除这个队列的内容,不再播放任何内容。如果当前正在播放,且播放队列为空,那么调用该方法效果等同与stop()接口。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `TTS.setCallback` + +```python +TTS.setCallback(cb) +``` + +该方法用于注册用户的回调函数,用于通知用户TTS播放状态。 + +> 该回调函数中不要进行耗时以及阻塞性的操作,建议只进行简单、耗时短的操作。 + +**参数描述:** + +`cb` - 用户回调函数,function类型,函数原型: + +```python +def cb(event): + pass +``` + +**回调函数参数描述**: + + - `event` - 播放状态,int类型,点此查看回调函数参数event说明表。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +**回调函数参数event说明表:** + +| event | 表示状态 | +| ----- | -------- | +| 2 | 开始播放 | +| 3 | 停止播放 | +| 4 | 播放完成 | + +### `TTS.getVolume` + +```python +TTS.getVolume() +``` + +该方法用于获取当前播放音量大小,音量值在区间[0 ~ 9],0表示静音,默认值4。 + +**返回值描述:** + +成功则返回整型音量大小值,`-1`表示失败。 + +### `TTS.setVolume` + +```python +TTS.setVolume(vol) +``` + +该方法用于设置播放音量大小,音量值应在区间[0 ~ 9],0表示静音。 + +> 说明:该接口设置的音量是在 Audio.setVolume 的基础上增加的增益,两边的设置都会影响 TTS 播放的实际音量效果。 + +**参数描述:** + +- `vol` - 音量大小,int类型,区间[0 ~ 9]。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `TTS.getSpeed` + +```python +TTS.getSpeed() +``` + +该方法用于获取当前播放速度,速度值在区间[0 ~ 9],值越大,速度越快,默认值4。 + +**返回值描述:** + +成功则返回整型音量大小值,`-1`表示失败。 + +### `TTS.setSpeed` + +```python +TTS.setSpeed(speed) +``` + +该方法用于设置TTS播放速度,速度值应在区间[0 ~ 9]。 + +**参数描述:** + +- `speed` - 速度值,int类型,区间[0 ~ 9]。 + +**返回值描述:** + +`0` 表示成功,`-1`表示失败。 + +### `TTS.getState` + +```python +TTS.getState() +``` + +该方法用于获取TTS状态。 + +**返回值描述:** + +`0` 表示当前无tts播放,`-1`表示当前有tts正在播放。 + +**示例:** + +```python +# -*- coding: UTF-8 -*- +import log +from audio import TTS +import utime + + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +tts_Log = log.getLogger("TTS") + +#定义回调函数 +def UsrFunc(event): + if event == 2: + print("开始播放") + elif event == 3: + print("停止播放") + elif event == 4: + print("播放完成") + +if __name__ == '__main__': + # 参数1:device (0:听筒,1:耳机,2:喇叭) + tts = TTS(0) + + #注册用户回调函数 + tts.setCallback(UsrFunc) + + # 获取当前播放音量大小 + volume_num = tts.getVolume() + tts_Log.info("Current TTS volume is %d" %volume_num) + + # 设置音量为6 + volume_num = 6 + tts.setVolume(volume_num) + + # 参数1:优先级 (0-4) + # 参数2:打断模式,0表示不允许被打断,1表示允许被打断 + # 参数3:模式 低四位:(1:UNICODE16(Size end conversion) 2:UTF-8 3:UNICODE16(Don't convert)),高四位:wtts_enable,wtts_ul_enable, wtts_dl_enable + # 参数4:数据字符串 (待播放字符串) + tts.play(1, 1, 2, 'QuecPython') # 执行播放 + tts.play(1,1,tts.wtts_enable|tts.wtts_ul_enable|2, '12345') + tts.close() # 关闭TTS功能 +``` diff --git a/docs/API_reference/zh/medialib/audio.md b/docs/API_reference/zh/medialib/audio.md new file mode 100644 index 0000000000000000000000000000000000000000..7fd02055e77c5270d2982bf061d25a287c8ef9db --- /dev/null +++ b/docs/API_reference/zh/medialib/audio.md @@ -0,0 +1,13 @@ +# audio - 音频播放 + +该模块包含各种音频功能,支持音频播放、TTS文本到语音播放、录音等功能。 + +## Classes + +- [class TTS - 文本到语音播放](./audio.TTS.md) + +- [class Audio - 音频播放](audio.Audio.md) + +- [class Record - 录音](audio.Record.md) + +- [class PCM - 音频数据编码](audio.PCM.md) diff --git a/docs/API_reference/zh/medialib/camera.CamCapture.md b/docs/API_reference/zh/medialib/camera.CamCapture.md new file mode 100644 index 0000000000000000000000000000000000000000..7a288165c5f4b3dfd6994f558e5bb1decd1ffa29 --- /dev/null +++ b/docs/API_reference/zh/medialib/camera.CamCapture.md @@ -0,0 +1,111 @@ +# class camCapture - 摄像头拍照 + +该类提供摄像头的拍照及保存功能。 + +> 使用该功能前,需要初始化LCD。 + +## 构造函数 + +### `camera.camCapture` + +```python +class camera.camCapture(model,cam_w,cam_h,perview_level,lcd_w,lcd_h) +``` + +创建camCapture对象。 + +**参数描述:** + +- `model` - camera型号,int类型,0或1,点此查看摄像头型号对应表。 +- `cam_w` - camera水平分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `cam_h` - camera垂直分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `perview_level` - 预览等级,int类型,型号EC600N系列、EC800N系列、EC600M系列、EC800M系列、EG810M系列可填写1或2,等级越高,图像越流畅,消耗资源越大;其他型号只可填写1。 +- `lcd_w` - LCD水平分辨率,int类型,请按照所使用的LCD的规格填写。 +- `lcd_h` - LCD垂直分辨率,int类型,请按照所使用的LCD的规格填写。 + +**摄像头型号对应表:** + +| 编号 | 摄像头型号 | 通信方式 | +| ---- | ---------- | -------- | +| 0 | gc032a | spi | +| 1 | bf3901 | spi | + +## 方法 + +### `camCapture.open` + +```python +camCapture.open() +``` + +该方法用于使能摄像头的拍照功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示打开使能成功,其他表示打开使能失败。 + +### `camCapture.close` + +```python +camCapture.close() +``` + +该方法用于关闭使能摄像头的拍照功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示关闭使能成功,其他表示关闭使能失败。 + +### `camCapture.start` + +```python +camCaputre.start(width, height, pic_name) +``` + +该方法用于拍照保存。 + +**参数描述:** + +- `width` - 保存图片水平分辨率,int类型。 +- `height` - 保存图片垂直分辨率,int类型。 +- `pic_name` - 图片名,string类型。图片无需加后缀.jpeg,会自动添加。 + +**返回值描述:** + +`0` 表示拍照保存成功,其他表示开始拍照保存失败。 + +> 拍照结果还是以回调函数参数为主。 + +### `camCapture.callback` + +```python +camCapture.callback(cb) +``` + +该方法用于设置拍照回调函数。 + +**参数描述:** + +`cb` - 拍照回调函数,回调函数原型: + +```python +def cb(result_list): + pass +``` + +**回调函数参数描述:** + +- `result_list[0]` - 拍照保存结果,int类型,`0`表示成功, 其它表示失败 +- `result_list[1]` - 保存的照片名称,string类型。 + +**返回值描述:** + +`0` 表示设置拍照回调函数成功,其他表示设置拍照回调函数失败。 diff --git a/docs/API_reference/zh/medialib/camera.CamDecoder.md b/docs/API_reference/zh/medialib/camera.CamDecoder.md new file mode 100644 index 0000000000000000000000000000000000000000..7e4cbc133eb794a620803426519534b2f1a10022 --- /dev/null +++ b/docs/API_reference/zh/medialib/camera.CamDecoder.md @@ -0,0 +1,156 @@ +# class camScandecode - 摄像头扫码 + +该类提供摄像头的扫码功能。 + +> 如果开启预览,需要先初始化LCD。 + +## 构造函数 + +### `camera.camScandecode` + +```python +class camera.camScandecode(model,decode_level,cam_w,cam_h,perview_level,lcd_w,lcd_h) +``` + +创建camScandecode对象。 + +**参数描述:** + +- `model` - camera型号,int类型,0或1,点此查看摄像头型号对应表。 +- `decode_level` - 解码等级,int类型,型号EC600N系列、EC800N系列、EC600M系列、EC800M系列、EG810M系列可填写1或2,等级越高,图像越流畅,消耗资源越大;其他型号只可填写1。 +- `cam_w` - camera水平分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `cam_h` - camera垂直分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `perview_level` - 预览等级,int类型,型号EC600N系列、EC800N系列、EC600M系列、EC800M系列、EG810M系列可填写1或2,等级越高,图像越流畅,消耗资源越大;其他型号只可填写1。 +- `lcd_w` - LCD水平分辨率,int类型,请按照所使用的LCD的规格填写。 +- `lcd_h` - LCD垂直分辨率,int类型,请按照所使用的LCD的规格填写。 + +**摄像头型号对应表:** + +| 编号 | 摄像头型号 | 通信方式 | +| ---- | ---------- | -------- | +| 0 | gc032a | spi | +| 1 | bf3901 | spi | + +## 方法 + +### `camScandecode.open` + +```python +camScandecode.open() +``` + +该方法用于使能摄像头的扫码功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示打开使能成功,其他表示打开使能失败。 + +### `camScandecode.close` + +```python +camScandecode.close() +``` + +该方法用于关闭使能摄像头的扫码功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示关闭使能成功,其他表示关闭使能失败。 + +### `camScandecode.start` + +```python +camScandecode.start() +``` + +该方法用于开始摄影头扫码。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示开始扫码,其他表示开始扫码失败。 + +### `camScandecode.stop` + +```python +camScandecode.stop() +``` + +该方法用于结束摄像头扫码。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示结束扫码扫码,其他表示结束扫码失败。 + +### `camScandecode.pause` + +```python +camScandecode.pause() +``` + +该方法用于暂停摄像头扫码。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示暂停扫码成功,其他表示暂停扫码失败。 + +### `camScandecode.resume` + +```python +camScandecode.resume() +``` + +该方法用于继续摄像头扫码。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示继续扫码成功,其他表示继续扫码失败。 + +### `camScandecode.callback` + +```python +camScandecode.callback(cb) +``` + +该方法用于设置识别回调函数。 + +**参数描述:** + +`cb` - 识别回调函数,回调函数原型: + +```python +def cb(result_list): + pass +``` + +**回调函数参数描述:** + +- `result_list[0]` - 扫码结果,int类型,`0`表示成功, 其它表示失败 +- `result_list[1]` - 扫码内容,string类型。 + +**返回值描述:** + +`0` 表示设置识别回调函数成功,其他表示设置识别回调函数失败。 \ No newline at end of file diff --git a/docs/API_reference/zh/medialib/camera.CamPreview.md b/docs/API_reference/zh/medialib/camera.CamPreview.md new file mode 100644 index 0000000000000000000000000000000000000000..d3e0a3793231416ec93bc0f1058e00a6560435e7 --- /dev/null +++ b/docs/API_reference/zh/medialib/camera.CamPreview.md @@ -0,0 +1,67 @@ + + +# class camPreview - 摄像头预览 + +该类提供摄像头的预览功能。 + +> 使用该功能前,需要初始化LCD。 + +## 构造函数 + +### `camera.camPreview` + +```python +class camera.camPreview(model,cam_w,cam_h,lcd_w,lcd_h,perview_level) +``` + +创建camPreview对象。 + +**参数描述:** + +- `model` - camera型号,int类型,点此查看摄像头型号对应表。 +- `cam_w` - camera水平分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `cam_h` - camera垂直分辨率,int类型,请按照对应摄像头型号的规格填写。 +- `lcd_w` - LCD水平分辨率,int类型,请按照所使用的LCD的规格填写。 +- `lcd_h` - LCD垂直分辨率,int类型,请按照所使用的LCD的规格填写。 +- `perview_level` - 预览等级,int类型,型号EC600N系列、EC800N系列、EC600M系列、EC800M系列、EG810M系列可填写1或2,等级越高,图像越流畅,消耗资源越大;其他型号只可填写1。 + +**摄像头型号对应表:** + +| 编号 | 摄像头型号 | 通信方式 | +| ---- | ---------- | -------- | +| 0 | gc032a | spi | +| 1 | bf3901 | spi | + +## 方法 + +### `camPreview.open` + +```python +camPreview.open() +``` + +该方法用于打开摄像头的预览功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示打开预览成功,其他表示打开预览失败。 + +### `camPreview.close` + +``` +camPreview.close() +``` + +该方法用于关闭摄像头的预览功能。 + +**参数描述:** + +无。 + +**返回值描述:** + +`0` 表示打开预览成功,其他表示打开预览失败。 \ No newline at end of file diff --git a/docs/API_reference/zh/medialib/camera.md b/docs/API_reference/zh/medialib/camera.md new file mode 100644 index 0000000000000000000000000000000000000000..ae0ee5352820cbc59583acfa966316ae10557626 --- /dev/null +++ b/docs/API_reference/zh/medialib/camera.md @@ -0,0 +1,15 @@ +# camera - 摄像头 + +该模块包含了摄像头预览,照相机,扫码功能。 + +> 目前支持型号:EC600N系列、EC800N系列、EC600M系列、EC800M系列、EG810M系列、EC600U-CN系列、EC200U-CN系列。 +> +> 如果需要预览,在初始化camera对象之前,请先参照[machine模块的lcd类的内容](machine.LCD.md)正确初始化LCD对象。 + +## Classes + +- [class CamPreview - 摄像头预览](./camera.CamPreview.md) + +- [class CamDecoder - 摄像头扫码](camera.CamDecoder.md) + +- [class CamCapture - 摄像头拍照](camera.CamCapture.md) \ No newline at end of file diff --git a/docs/API_reference/zh/medialib/qrcode.md b/docs/API_reference/zh/medialib/qrcode.md new file mode 100644 index 0000000000000000000000000000000000000000..efc791a0f3a8125dea71b991b26301a4f6a36b68 --- /dev/null +++ b/docs/API_reference/zh/medialib/qrcode.md @@ -0,0 +1,63 @@ +# qrcode- 二维码显示 + +根据输入的内容,生成对应的二维码。 + +## 二维码显示功能 + +### `qrcode.show` + +```python +qrcode.show(qrcode_str,magnification,start_x,start_y,Background_color,Foreground_color,Rotate) +``` + +显示二维码到LCD。 + +**参数描述:** + +- `qrcode_str`-string类型,二维码内容; +- `magnification`-int类型,放大倍数[1,6]; +- `start_x`-int类型,二维码显示起始x坐标; +- `start_y`-int类型,二维码显示起始y坐标; +- `Background_color`-int类型,前景色(不设置即默认为0xffff); +- `Foreground_color`-int类型,背景色(不设置即默认为0x0000)。 +- `Rotate`-int类型,旋转角度,[见常量](#常量)(不设置即默认为0)。 + +**返回值描述:** + +`0`表示成功,`-1`表示生成二维码失败,`-2`表示放大失败,`-3`表示显示失败。 + +## 生成二维码数据 + +### `qrcode.getQRData` + +```python +qrcode.getQRData(qrcode_str,magnification,Background_color,Foreground_color) +``` + +生成并获取二维码显示数据。 + +**参数描述:** + +- `qrcode_str`-string类型,二维码内容; +- `magnification`-int类型,放大倍数[1,6]; +- `Background_color`-int类型,前景色(不设置即默认为0xffff); +- `Foreground_color`-int类型,背景色(不设置即默认为0x0000)。 + +**返回值描述:** + +`-1`表示生成二维码失败。 + +成功返回元组`(side_length, data)` + +- `side_length`:二维码边长。 +- `data`:二维码显示数据。 + +## 常量 + +| 常量 | 值 | 说明 | +| ------------------- | ---- | ------------------------ | +| `qrcode.ROTATE_0` | 0 | 二维码不旋转显示 | +| `qrcode.ROTATE_90` | 1 | 二维码顺时针旋转90°显示 | +| `qrcode.ROTATE_180` | 2 | 二维码顺时针旋转180°显示 | +| `qrcode.ROTATE_270` | 3 | 二维码顺时针旋转270°显示 | + diff --git a/docs/API_reference/zh/networklib/Lwm2m.md b/docs/API_reference/zh/networklib/Lwm2m.md new file mode 100644 index 0000000000000000000000000000000000000000..b5c8b15cd8415a817a856e0a9dfa6b0b5f9d5433 --- /dev/null +++ b/docs/API_reference/zh/networklib/Lwm2m.md @@ -0,0 +1,221 @@ +# lwm2m-轻型物联网 +## 创建对象 +轻型物联网协议,提供在云平台管理设备的功能,例如检查设备在线状态,观测当前信号情况,重启设备等。 + +>以下型号支持此模块功能,对于定制的功能,根据实际功能为准: +> +>EC200UEU_AB_SANX/BG95M8_SANX/EC200AAU_HA_SANX/EG912NEN_AA。 + +### `lwm2m` + +```python +lw=lwm2m() +``` + +创建lwm2m对象。 + +**参数描述:** + +无参数。 + +**返回值描述:** + +返回lwm2m对象。 + + +## 初始化对象 + +### `lwm2m.init` + +```python +lwm2m.init() +``` + +初始化对象。 + +**参数描述:** + +无参数。 + +**返回值描述:** + +成功返回整型数值0,失败返回整型数值-1。 + +## 配置对象 + +### `lwm2m.config` + +```python +lwm2m.config(config_type,config_list) +``` + +配置功能模块参数。 + +**参数描述:** + +* `config_type` - 配置类型 ,枚举型,lwm2m对象下的枚举数值,详见下表。 + +| 配置类型 | 对应的config_list参数 | 备注 | +| ---------- | ------------------------------------------------------------------- | ----------------- | +| lwm2m.Epnamemode | [mode] | | +| lwm2m.Reset | [] | 空list | +| lwm2m.Security | [serverID,SSID,server_addr,bootstrap,security_mode,psk_id,psk_key] | | +| lwm2m.Server | [serverID,life_time,pmin,pmax,disable_timeout,storing,binding_mode] | | +| lwm2m.Urc | [URC_onoff] | 如果要抓取URC,必须配置开启 | +| lwm2m.Fota | [download,update] | 如果要抓取URC,配置成均不自动 | + +* `config_list` - 配置参数列表 ,列表数据类型,列表元素值详见下表。 + +| 字段名 | 字段类型 | 字段说明 | +| --------------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| serverID | 整型 | 0 - Bootstrap server
1 - DM server
| +| SSID | 整型 | 100 - Bootstrap server
1000 - Diagnostics server
| +| server_addr | 字符串 | 服务器地址,格式为:"address:port",最长支持256 | +| bootstrap | 整型 | 0 - 不用bootstrap(仅当serverID不为0)
1 - 使用bootstrap (仅当serverID为0) | +| security_mode | 整型 | 加密方法:
0 - Pre-share key mode
3 - No security mode | +| psk_id | 字符串 | security_mode为0时有用 | +| psk_key | 字符串 | security_mode为0时有用 | +| life_time | 整型 | 生存时间,取值范围1~86400,默认值86400,单位秒 | +| pmin | 整型 | pmin默认周期,取值范围1~86400,默认值86400,单位秒 | +| pmax | 整型 | pmax默认周期,取值范围1~86400,默认值86400,单位秒 | +| disable_timeout | 整型 | 与 LwM2M 服务器断开连接后到下一个连接的时间间隔。范围为 1-86400,默认值为 86400,单位为秒
实测断开后可以立刻启动连接,功能无效(上送给服务端的,服务端未限制) | +| storing | 整型 | 是否保存服务器信息
0 - 不保存
1 - 保存 | +| binding_mode | 字符串 | 和服务器连接方式,目前仅支持基于UDP的连接方式
"U" - UDP方式
"UQ" - UDP有队列模式方式
"S" - SMS方式
"SQ" - SMS有队列模式方式
"US" - UDP和SMS方式
"UQS" - UDP和SMS有队列模式方式 | +| mode | 整型 | 终端设备名字格式
3 - 格式为: urn:imei:xxxxx,配置epname格式 | +| download | 整型 | 下载模式
0 - 手动下载
1 - 自动下载 | +| update | 整型 | 更新模式
0 - 手动更新
1 - 自动更新 | +| URC_onoff | 整型 | 是否开启lwm2m的urc上报
0 - 禁用URC上报
1 - 启用URC上报 | + + +**返回值描述:** + +成功返回整型数值0,失败返回整型数值-1,不支持返回整型数值-2。 + +## 注册 + +### `lwm2m.register` + +```python +lwm2m.register() +``` + +向lwm2m服务器发送登录请求,登录成功或失败结果会通过回调函数上送登录成功消息。 + +**参数描述:** + +无参数 + +**返回值描述:** + +执行成功返回0,执行失败返回-1。注册结果需要调用查询接口进行查询。 + +## 注销 + +### `lwm2m.unregister` + +```python +lwm2m.unregister() +``` + +向lwm2m服务器发送退出登录请求,成功或失败结果通过回调函数进行通知。 + +**参数描述:** + +无参数。 + +**返回值描述:** + +执行成功返回0,执行失败返回-1。注销结果需要调用查询接口进行查询。 + +## 查询注册状态 + +### `lwm2m.stat` + +```python +lwm2m.stat() +``` + +查询当前登录状态。 + +**参数描述:** + +无参数。 + +**返回值描述:** + +未注册状态返回整型值0,注册中状态返回整型值1,已注册状态返回整型值2,注销中状态返回整型值3,登录失败状态返回整型值4。 + +## 发送心跳 + +### `lwm2m.update` + +```python +lwm2m.update(ssid) +``` + +向lwm2m服务器发送心跳包,内部会有自动心跳流程,不建议主动调用此接口。 + +**参数描述:** + +* `ssid` - 配置的ssid或者是BS登录阶段BS下发的ssid,整型值。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。update结果通过回调函数通知。 + +## 注册回调函数 + +### `lwm2m.register_call` + +```python +lwm2m.register_call(usrfun) +``` + +注册回调函数,此回调函数会通知上层应用登录结果,以及服务器下发的消息。 + +**参数描述:** + +* `usrfun` - 设置消息回调函数,function类型,当服务端响应时触发该方法。 + +**回调函数参数** + +* `list` - 回调函数通知消息数据,list类型,详细介绍如下: + +| 元素 | 数据类型 | 备注 | +| ------- | ---- | ------------------------------------------------------- | +| list[0] | 整型 | 事件类型(可以不处理忽略) | +| list[1] | 整型 | 事件编码(可以不处理忽略) | +| list[2] | 整型 | 抓取到的URC字符串数据(具体事件说明请参考[事件说明](#事件说明),以此参数判断Lwm2m的连接事件为准 | + +**返回值描述:** + +成功返回0,失败返回-1。注意如果要删除已经注册的回调函数,传入参数None。 + +## 事件说明 + +事件类型不同的平台可能稍有不同,例如APN某些平台没有,不影响功能,不影响使用。 + +| 事件类型 | 说明 | 备注 | +| -------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------ | +| +QLWURC: "pdp active",result,apn | PDP的激活结果。在向lwm2m发送注册请求之前,应激活 PDP 服务器 | result:string类型
"successfully"
"failed"
apn:string类型
APN值 | +| +QLWURC: "initial",result,ssid | 客户端与lwm2m服务器连接的初始化结果 | result:string类型
"successfully"
"failed"
ssid:整型类型
0-所有的服务器
其他值-其他的特殊服务器 | +| +QLWURC: "dtls",result,ssid | 使用加密方法时的DTLS握手结果 | 同上 | +| +QLWURC: "bootstraping" | 当 Bootstrap 工作时,将报告此 URC | | +| +QLWURC: "bootstrap",result,ssid | Bootstrap 的工作结果 | 同上 | +| +QLWURC: "registering" | 当客户端在lwm2m服务器上注册时将报告此 URC | 同上 | +| +QLWURC: "ready",result,ssid | 向lwm2m服务器发送注册请求后的注册结果 | 同上 | +| +QLWURC: "update",result,ssid | 向lwm2m服务器发送更新请求后的更新结果 | 同上 | +| +QLWURC: "deregister",ssid,code
+QLWURC: "deregister",code | 向lwm2m服务器发送注销请求后的注销结果 | ssid:整型类型
0-所有的服务器
其他值-其他的特殊服务器
code:整型
0 - 成功
1 - 失败
3 - 未知错误 | +| +QLWURC: "fota/pkgurl",url | lwm2m服务器下发的url地址 | | +| +QLWURC: "apn_changed",APN | lwm2m服务器下发的apn值 | | +| +QLWURC: "user_name_changed",user | lwm2m服务器下发的用户名 | | +| +QLWURC: "secret_changed",password | lwm2m服务器下发的密码 | | +| +QLWURC: "authentication_type_changed", | lwm2m服务器下发的鉴权方式 | | +| +QLWURC: "lifetime_changed",lifetime | lwm2m服务器下发的存活周期(心跳周期) | | +| +QLWURC: "current_time_changed",data_time | lwm2m服务器下发的时间戳 | | + +--- + +## 获取示例代码 + +*[点击下载示例代码](https://github.com/QuecPython/examples/tree/main/network-comm/net-protocols/lwm2m/example_lwm2m.py)* diff --git a/docs/API_reference/zh/networklib/README.md b/docs/API_reference/zh/networklib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e7ddfdb61cf58df5d94cef49ab5acfd36281ed8c --- /dev/null +++ b/docs/API_reference/zh/networklib/README.md @@ -0,0 +1,16 @@ +# QuecPython 网络应用 + +> QuecPython 网络应用库包括网络应用相关的功能组件 + +本文描述了 QuecPython 网络应用库中的模块。 + +## QuecPython 网络应用库列表 + +- [ussl - SSL加密通信](./ussl.md) +- [request - HTTP客户端](./request.md) +- [umqtt - MQTT客户端](./umqtt.md) +- [uwebsocket - websocket客户端](./uwebsocket.md) +- [uping - 发送ping包](./uping.md) +- [ntptime - 网络时间同步](./ntptime.md) +- [lwm2m - 轻量级 M2M 协议](./Lwm2m.md) +- [ftplib - ftp 客户端](./ftp.md) diff --git a/docs/API_reference/zh/networklib/ftp.md b/docs/API_reference/zh/networklib/ftp.md new file mode 100644 index 0000000000000000000000000000000000000000..37e957103b2969887cb7f76475d0c68806a131d7 --- /dev/null +++ b/docs/API_reference/zh/networklib/ftp.md @@ -0,0 +1,508 @@ +# ftplib - FTP 客户端 + +FTP(File Transfer Protocol)是一种用于在计算机网络中传输文件的标准协议,它基于客户端-服务器模型,通过控制连接和数据连接实现文件的上传、下载和管理操作。 + +> ftplib是python源码实现,如对应固件版本未默认支持。用户可使用源码[ftplib.py](https://github.com/QuecPython/ftplib),放默认目录/usr下,使用时,将from ftplib import FTP 改为from usr.ftplib import FTP. + +## 构造函数 + +### `ftplib.FTP` + +```python +class ftplib.FTP(host=None, port=None, user=None, passwd=None, acct=None,timeout=None) +``` + +构建 FTP 连接对象。 + +> 1. 实例化参数时如主动传入 `host` 与 `port`,将在对象构建成功后主动调用 `connect` 方法连接服务端,连接失败会触发异常,未传入时需自行调用 `connect` 方法。 +> 2. 在主动连接基础上传入 `user` 与 `port` 会在连接成功后调用 `login` 方法登录服务端,未传入需自行调用 `login` 方法。 + +**参数描述:** + +- `host` - 可选参数,FTP 服务端地址,字符串类型,未传入时需自行调用 `connect` 方法连接服务端。 +- `port` - 可选参数,FTP 服务端端口,整型,默认端口为 21。 +- `user` - 可选参数,客户端登录用户名,字符串类型,若未指定则匿名访问,默认为 `'anonymous'`。 +- `passwd`- 可选参数,客户端登录密码,字符串类型,如果 `user` 为 `'anonymous'`,那么默认的 `passwd` 是 `'anonymous@'`。 +- `acct`- 可选参数,账户,字符串类型,默认为空,一般不做设置。 +- `timeout`- 可选参数,连接超时,整型,单位为秒。 + +**返回值描述:** + +- 返回 FTP 对象。 + +**示例:** + +```python +# 未抛出异常则包含该功能 +from ftplib import FTP + +# 不传入参数创建FTP对象 +ftp = FTP() + +# 传入参数创建 FTP 对象,会根据参数 host 和 user 来进行服务段连接和登录,登录需在连接成功之后 +host = 'xxx.xxx.xxx.xxx' +port = 21 +ftp = FTP(host='xxx.xxx.xxx.xxx', port=21, user='xxx', passwd='xxx') +``` + +## 设置调试输出级别 + +### `ftp.set_debuglevel` + +```python +ftp.set_debuglevel(level) +``` + +设置实例的调试级别,它控制着调试信息的数量。默认值 0 不产生调试信息。值 1 产生中等数量的调试信息,通常每个请求产生一行。大于或等于 2 的值产生的调试信息最多,FTP 控制连接上发送和接收的每一行都将被记录下来。 + +**参数描述:** + +- `level` - 可选参数,调试级别,整型,默认为 0。 + +**返回值描述:** + +- 无。 + +**示例:** + +```python +ftp.set_debuglevel(1) +``` + +## 连接FTP服务器 + +### `ftp.connect` + +```python +ftp.connect(host, port, timeout) +``` + +FTP 客户端发起连接服务端请求。 + +**参数描述:** + +- `host` - 必填参数,FTP 服务端地址,字符串类型,未传入时需自行调用 `connect` 方法连接服务端。 +- `port` - 可选参数,FTP 服务端端口,整型,默认端口为 21。 +- `timeout` - 可选参数,连接超时,整型,单位为秒。 + +**返回值描述:** + +- 返回以 `220` 开头的字符串,则表示连接成功(如 `'220 (vsFTPd 3.0.3)'`),否则表示连接失败。 + +**示例:** + +```python +host = 'xxx.xxx.xxx.xxx' +port = 21 + +ftp.connect(host=host, port=port) +# 220 (vsFTPd 3.0.3) +``` + +## 登录 FTP 服务器 + +### `ftp.login` + +```python +ftp.login(user, passwd) +``` + +FTP客户端发起登录服务端请求,登录请求需在及连接建立成功后进行。 + +**参数描述:** + +- `user` - 可选参数,客户端登录用户名,字符串类型,若未指定则匿名访问,默认为 `'anonymous'`。 +- `passwd `- 可选参数,客户端登录密码,字符串类型,如果 `user` 为 `'anonymous'`,那么默认的 `passwd` 是 `'anonymous@'`。 + +**返回值描述:** + +- 返回以 `230` 开头的字符串表示登录成功(如 `'230 Login successful.'`),否则表示登录失败。 + +**示例:** + +```python +user = 'xxx' +passwd = 'xxx' + +ftp.login(user=user, passwd=passwd) +# 230 Login successful. +``` + +## FTP 操作指令 + +### `ftp.nlst` + +```python +ftp.nlst(*args) +``` + +返回文件名列表,默认返回当前服务器目录。 + +**参数描述:** + +- `args` - 可选参数,待列出的目录(默认为当前服务器目录),列表类型。 + +**返回值描述:** + +- 文件名列表。 + +**示例:** + +```python +ftp.nlst() +# ['FTP-TEST', 'system_config.json'] +``` + +### `ftp.dir` + +```python +ftp.dir(*args) +``` + +获取当前目录中的内容列表。 + +**参数描述:** + +- `args` - 可选参数,需要返回的目录,列表类型。 + +**返回值描述:** + +- 目录下的内容列表。 + +**示例:** + +```python +ftp.dir() +# -rw-r--r-- 1 1002 1002 12 Jul 26 10:07 FTP-TEST +# -rw------- 1 1002 1002 17 Jul 28 16:40 +``` + +### `ftp.pwd` + +```python +ftp.pwd() +``` + + 获取当前 FTP 服务器目录。 + +**返回值描述:** + +- 当前 FTP 服务器目录。 + +**示例:** + +```python +ftp.pwd() +# /home/ftpuser +``` + +### `ftp.rename` + +```python +ftp.rename(fromname, toname) +``` + +重命名 FTP 服务器上的文件。 + +**参数描述:** + +- `fromname` - 必填参数,待修改的文件名,字符串类型。 +- `toname` - 必填参数,重命名后的文件名,字符串类型。 + +**返回值描述:** + +- 返回以 `250` 打头的字符串,表示重命名成功(如 `'250 Rename successful.'`),否则表示重命名失败。 + +**示例:** + +```python +from_name = ftp.pwd() + '/system_config.json' +to_name = ftp.pwd() + '/system.json' +ftp.rename(from_name, to_name) +# 250 Rename successful. +``` + +### `ftp.delete` + +```python +ftp.delete(file_name) +``` + +删除 FTP 服务器上的文件。 + +**参数描述:** + +- `file_name` - 必填参数,待删除的文件名,字符串类型。 + +**返回值描述:** + +- 返回以 `250` 打头的字符串,表示删除成功(如 `'250 Delete operation successful.'`),否则表示删除失败。 + +**示例:** + +```python +file_name = ftp.pwd() + '/system.json' +ftp.delete(file_name) +# 250 Delete operation successful. +``` + +### `ftp.mkd` + +```python +ftp.mkd(pathname) +``` + +在 FTP 服务器上创建目录。 + +**参数描述:** + +- `pathname` - 必填参数,待创建的的目录文件路径,字符串类型。 + +**返回值描述:** + +- 返回创建成功的路径信息,字符串格式。 + +**示例:** + +```python +new_dir = ftp.pwd() + '/test_dir' +ftp.mkd(new_dir) +# /home/ftpuser/test_dir +``` + +### `ftp.cwd` + +```python +ftp.cwd(pathname) +``` + +设置服务器端的当前目录。 + +**参数描述:** + +- `pathname` - 必填参数,设置的目录路径,字符串类型。 + +**返回值描述:** + +- 返回以 `250` 打头的字符串,表示设置成功(如 `'250 Directory successfully changed.'`),否则表示设置失败。 + +**示例:** + +```python +target_dir = ftp.pwd() + '/test_dir' +ftp.cwd(target_dir) +# 250 Directory successfully changed. +``` + +### `ftp.quit` + +```python +ftp.quit() +``` + +关闭 FTP 服务器连接。 + +**返回值描述:** + +- 返回以 `221` 打头的字符串,表示关闭连接成功(如 `'221 Goodbye.'`),否则表示关闭连接失败。 + +**示例:** + +```python +ftp.quit() +# 221 Goodbye. +``` + +## 文件下载 + +### `ftp.retrbinary` + +```python +ftp.retrbinary(cmd, callback, blocksize) +``` + +使用`RETR filename` FTP 命令,以二进制模式将文件从 FTP 服务器下载到本地,处理二进制文件(如图片、视频、音频等)时建议使用。 + +**参数描述:** + +- `cmd` - 必填参数,传输命令,由 `RETR +文件名`组成(中间有空格),字符串类型。 +- `callback` - 必填参数,接收远端文件数据的回调函数。 + - **函数原型:** `function(msg)` + - **参数描述:** + - `msg` :字节类型,用于接收 FTP 服务端传输到本地的文件数据。 +- `blocksize` - 可选参数,设置每次传输的最大字节数,默认为 `2048K` 。 + +**返回值描述:** + +- 返回以 `226` 打头的字符串,表示下载文件成功(如 `226 Transfer complete`),否则表示下载文件失败。 + +**示例:** + +```python +path = 'usr/' # 模组用户分区的根目录为'usr' +filename = 'ftp_file.bin' # 待下载的文件名 + +# 打开并创建一个文件 +save_fp = open(path + filename, 'wb+') +# 查询服务端当前路径 +server_path = ftp.pwd() +# 建立下载连接,save_fp.write为写文件操作,作为回调函数传入 +res = ftp.retrbinary('RETR ' + server_path + '/' + filename, save_fp.write) +# 完成下载 +msg = 'Down %s to device %s.' +if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True +else: + print(msg % (filename, 'falied')) + return False +``` + +### `ftp.retrlines` + +```python +ftp.retrlines(cmd, callback) +``` + +使用 `RETR filename` FTP命令,以文本模式下载文件,通常用于下载文本文件。 + +**参数描述:** + +- `cmd` - 必填参数,传输命令,由 `RETR +文件名` 组成(中间有空格),字符串类型。 +- `callback` - 必填参数,接收远端文件数据的回调函数。 + - **函数原型:** `function(msg)` + - **参数描述:** + - `msg` :字节类型,用于接收 FTP 服务端传输到本地的文件数据。 + +**返回值描述:** + +- 返回以 `226` 打头的字符串,表示下载文件成功(如 `226 Transfer complete`),否则表示下载文件失败。 + +**示例:** + +```python +path = 'usr/' # 模组用户分区的根目录为'usr' +filename = 'ftp_file.txt' # 待下载的文件名 + +# 打开并创建一个文件 +save_fp = open(path + filename, 'wb+') +# 查询服务端当前路径 +server_path = ftp_obj.pwd() +# 建立下载连接,save_fp.write为写文件操作,作为回调函数传入 +res = ftp_obj.retrlines('RETR ' + server_path + '/' + filename, save_fp.write) +# 完成下载 +msg = 'Down %s to device %s.' +if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True +else: + print(msg % (filename, 'falied')) + return False +``` + +## 文件上传 + +### `ftp.storbinary` + +```python +ftp.storbinary(cmd, fp, blocksize) +``` + +以二进制形式向 FTP 服务器上传文件。 + +**参数描述:** + +- `cmd` - 必填参数,传输命令,由 `STOR +文件名` 组成(中间有空格),字符串类型。 +- `fp` - 必填参数,本地文件句柄。 +- `blocksize` - 可选参数,每次读取文件的最大字节数,默认为 `2048K` 。 + +**返回值描述:** + +- 返回以 `226` 打头的字符串,表示上传文件成功(如 `226 Transfer complete`),否则表示上传文件失败。 + +**示例:** + +```python +path = 'usr/' # 模组用户分区的根目录为'usr' +filename = 'ftp_file.bin' + +# 判断文件是否存在 +if filename in uos.listdir('usr/'): + print('文件存在') + with open(path + filename, 'rb') as fp: + # cmd应为STOR 命令。fp是一个文件对象 (以二进制模式打开)。 + res = ftp.storbinary('STOR ' + filename, fp) + msg = 'Upload %s to FTP Server %s.' + if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True + else: + print(msg % (filename, 'falied')) + return False +else: + print('文件路径不存在') +``` + +### `ftp.storlines` + +```python +ftp.storlines(cmd, fp) +``` + +以 ASCII 码形式向 FTP 服务器上传文件。 + +**参数描述:** + +- `cmd` - 必填参数,传输命令,由 `STOR +文件名` 组成(中间有空格),字符串类型。 +- `fp` - 必填参数,本地文件句柄。 + +**返回值描述:** + +- 返回以 `226` 打头的字符串,表示上传文件成功(如 `226 Transfer complete`),否则表示上传文件失败。 + +**示例:** + +```python +path = 'usr/' # 模组用户分区的根目录为'usr' +filename = 'ftp_file.txt' + +# 判断文件是否存在 +if filename in uos.listdir('usr/'): + print('文件存在') + with open(path + filename, 'rb') as fp: + # cmd应为STOR 命令。 + res = ftp.storlines('STOR ' + filename, fp) + msg = 'Upload %s to FTP Server %s.' + if res.startswith('226 Transfer complete'): + print(msg % (filename, 'success')) + return True + else: + print(msg % (filename, 'falied')) + return False +else: + print('文件路径不存在') +``` + +## FTP客户端命令介绍 + +以下是常用的 FTP 客户端命令: + +- CONNECT:建立与 FTP 服务器的连接。 +- USER:指定登录用户名。 +- PASS:指定登录密码。 +- LIST:列出服务器上当前目录的文件和子目录。 +- CWD:改变当前工作目录。 +- PWD:显示当前工作目录的路径。 +- RETR:从服务器下载文件到本地计算机。 +- STOR:将本地文件上传到服务器。 +- DELE:删除服务器上的文件。 +- MKD:在服务器上创建新的目录。 +- RMD:删除服务器上的目录。 +- RNFR:指定要重命名的文件或目录。 +- RNTO:指定重命名后的文件或目录名。 +- PASV:进入被动模式,用于数据传输。 +- TYPE:指定数据传输的类型,如 ASCII 或二进制。 +- SIZE:获取服务器上文件的大小信息。 +- SYST:获取服务器的操作系统类型。 +- NOOP:空操作,用于保持控制连接的活动状态。 +- QUIT:断开与服务器的连接。 \ No newline at end of file diff --git a/docs/API_reference/zh/networklib/ntptime.md b/docs/API_reference/zh/networklib/ntptime.md new file mode 100644 index 0000000000000000000000000000000000000000..220e29d4cec5ce4190072db7388e06cfdbefe1e2 --- /dev/null +++ b/docs/API_reference/zh/networklib/ntptime.md @@ -0,0 +1,101 @@ +# ntptime - 网络时间同步 + +该模块用于网络时间同步。 + +> BC25PA平台电信卡开卡时需要说明SIM卡须支持此类业务,移动联通一般不限制(开卡时需要和运营商确认)。 + + + +## 获取ntp服务器 + +### `ntptime.host` + +```python +ntptime.host +``` +**返回值描述:** + +* 返回当前的ntp服务器,默认为"ntp.aliyun.com"。 + + + +## 设置ntp服务器 + + +### `ntptime.sethost` + +```python +ntptime.sethost(host) +``` + +**参数描述:** + +* `host` - ntp服务器地址,字符串类型 + +**返回值描述:** + +* 成功返回整型值0,失败返回整型值-1。 + + + +## 同步ntp时间 + + +### `ntptime.settime` + +```python +ntptime.settime(timezone=0, use_rhost=1, timeout=10) +``` + +**参数描述:** + +* `timezone` - int类型,可选参数,时区设置,默认为0, 范围 (-12~12)。(-数为西时区,正数为东时区) + +* `use_rhost` - int类型,可选参数,ntptime.host 对时失败时,是否使用备用服务器继续尝试对时,默认为1,使用备用服务器,设为0时,仅使用ntptime.host对时。 + +* `timeout` - int类型,可选参数,socket网络请求超时时间(单位为秒),默认为10,范围:>0。 + + + +**返回值描述:** + +* 成功返回整型值`0`,失败返回整型值`-1`。 + + + +**示例: ** + +```python +import ntptime +import log +import utime +import checkNet + + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_NTP_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +ntp_log = log.getLogger("NtpTime") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + ntp_log.info('Network connection successful!') + + # 查看默认ntp服务 + ntp_log.info(ntptime.host) + # 设置ntp服务 + ntptime.sethost('pool.ntp.org') + + # 同步ntp服务时间 + ntptime.settime() + else: + ntp_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) +``` \ No newline at end of file diff --git a/docs/API_reference/zh/networklib/request.md b/docs/API_reference/zh/networklib/request.md new file mode 100644 index 0000000000000000000000000000000000000000..36d5ee2f4f7b0b161f020318d9abeb0062b2188b --- /dev/null +++ b/docs/API_reference/zh/networklib/request.md @@ -0,0 +1,283 @@ +# request - HTTP客户端 + +`request`模块用于向服务器发起 HTTP 请求,它可以被用于从一个服务器获取数据,或者将数据提交到服务器上,支持多种请求方法(如 GET、POST、PUT等)。 + +## HTTP请求 + +### `request.get` + +```python +response = request.get(url) +``` + +发送GET请求。 + +**参数描述:** + +- `url`- 必填参数,请求的远端地址(自动识别http/https请求,https主动使能ssl)。 +- `data`-可选参数,请求中需要携带参数,JSON格式。 +- `headers`-可选参数,请求头信息,字典类型。 +- `decode`-可选参数,将请求成功后的响应结果解码(UTF8),默认为True,输入False则返回bytes,仅配合response.content使用。 +- `timeout`-可选参数,socket网络请求超时时间(单位为秒),默认为20,范围:>0。 +- `ipvtype`-可选参数,默认为:0 发送ipv4请求,设置为:1 发送ipv6请求。 +- `username`-可选参数,用户身份验证的用户名,字符串类型。 +- `password`-可选参数,用户身份验证的密码,字符串类型。 +- `sizeof`-可选参数,读取缓冲区的数据块大小,默认2048 个字节,建议255-4096,数值越大读取的速度越快。 +- `ssl_params`-可选参数,url为https请求时,如果SSL认证时需传入密钥,密钥格式为{"cert": certificate_content, "key": private_content},内容为字符串类型。 + +**返回值描述:** + +- 返回响应对象,对象包含了服务器返回的所有信息,例如响应状态码、响应头、响应体等。 + +**示例:** + +```python +import request +import utime + +url = "http://www.example.com" +response = request.get(url) + +for i in response.text: + print(i);utime.sleep_ms(10) + +url = "https://www.example.com" +response = request.get(url) + +for i in response.text: + print(i);utime.sleep_ms(10) + +``` + +### `request.post` + +```python +response = request.post(url,data) +``` + +发送POST请求。 + +**参数描述:** + +- `url`- 必填参数,请求的远端地址(自动识别http/https请求,https主动使能ssl)。 +- `data`-可选参数,请求中需要携带的参数,JSON格式。 +- `headers`-可选参数,请求头信息,字典类型。 +- `decode`-可选参数,将请求成功后的响应结果解码(UTF8),默认为True,输入False则返回bytes,仅配合response.content使用。 +- `timeout`-可选参数,socket网络请求超时时间(单位为秒),默认为20,范围:>0。 +- `ipvtype`-可选参数,默认为:0 发送ipv4请求,设置为:1 发送ipv6请求。 +- `username`-可选参数,用户身份验证的用户名,字符串类型。 +- `password`-可选参数,用户身份验证的密码,字符串类型。 +- `sizeof`-可选参数,读取缓冲区的数据块大小,默认2048 个字节,建议255-4096,数值越大读取的速度越快。 +- `ssl_params`-可选参数,url为https请求时,如果SSL认证时需传入密钥,密钥格式为{"cert": certificate_content, "key": private_content},内容为字符串类型。 + +**返回值描述:** + +- 返回响应对象,对象包含了服务器返回的所有信息,例如响应状态码、响应头、响应体等。 + +**Content-Type介绍:** + +当使用POST方法提交数据时,对于提交的数据主要有如下四种形式: + +- application/x-www-form-urlencoded:form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)。 +- multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式。 +- application/json: JSON数据格式。 +- application/octet-stream : 二进制流数据(如常见的文件下载)。 + +**示例:** + +```python +import request + +url = "http://httpbin.org/post" +data = {"key1": "value1", "key2": "value2", "key3": "value3"} +header = {'key1': 'value1', "key2": "value2", "key3": "value3"} +response = request.post(url, data=ujson.dumps(data), header) + +for i in response.text: + print(i) + +``` + + +### `request.put` + +```python +response = request.put(url) +``` + +发送PUT请求。 + +**参数描述:** + +- `url`- 必填参数,请求的远端地址(自动识别http/https请求,https主动使能ssl)。 +- `data`-可选参数,请求中需要携带的参数,JSON格式。 +- `headers`-可选参数,请求头信息,字典类型。 +- `decode`-可选参数,将请求成功后的响应结果解码(UTF8),默认为True,输入False则返回bytes,仅配合response.content使用。 +- `timeout`-可选参数,socket网络请求超时时间(单位为秒),默认为20,范围:>0。 +- `ipvtype`-可选参数,默认为:0 发送ipv4请求,设置为:1 发送ipv6请求。 +- `username`-可选参数,用户身份验证的用户名,字符串类型。 +- `password`-可选参数,用户身份验证的密码,字符串类型。 +- `sizeof`-可选参数,读取缓冲区的数据块大小,默认2048 个字节,建议255-4096,数值越大读取的速度越快。 +- `ssl_params`-可选参数,url为https请求时,如果SSL认证时需传入密钥,密钥格式为{"cert": certificate_content, "key": private_content},内容为字符串类型。 + +**返回值描述:** + +- 返回响应对象,对象包含了服务器返回的所有信息,例如响应状态码、响应头、响应体等。 + +### `request.head` + +```python +response = request.head(url) +``` + +发送HEAD请求。 + +**参数描述:** + +- `url`- 必填参数,请求的远端地址(自动识别http/https请求,https主动使能ssl)。 +- `data`-可选参数,请求中需要携带的参数,JSON格式。 +- `headers`-可选参数,请求头信息,字典类型。 +- `decode`-可选参数,将请求成功后的响应结果解码(UTF8),默认为True,输入False则返回bytes,仅配合response.content使用。 +- `timeout`-可选参数,socket网络请求超时时间(单位为秒),默认为20,范围:>0。 +- `ipvtype`-可选参数,默认为:0 发送ipv4请求,设置为:1 发送ipv6请求。 +- `username`-可选参数,用户身份验证的用户名,字符串类型。 +- `password`-可选参数,用户身份验证的密码,字符串类型。 +- `sizeof`-可选参数,读取缓冲区的数据块大小,默认2048 个字节,建议255-4096,数值越大读取的速度越快。 +- `ssl_params`-可选参数,url为https请求时,如果SSL认证时需传入密钥,密钥格式为{"cert": certificate_content, "key": private_content},内容为字符串类型。 + +**返回值描述:** + +- 返回响应对象,对象包含了服务器返回的所有信息,例如响应状态码、响应头、响应体等。 + +## 获取响应 + +`request` 库发送请求后,会返回一个响应对象。响应对象包含了服务器返回的所有信息,例如响应状态码、响应头、响应体等。 + +### `response.status_code` + +使用 `response.status_code` 属性获取请求状态码。 + +```python +response.status_code +``` + +**返回值描述:** + +- int类型,响应状态码 + +**示例:** + +```python +import request + +response = request.get("http://httpbin.org/get") +print(response.status_code) +``` + +### `response.headers` + +使用 `response.headers` 属性获取请求头信息。 + +```python +response.headers +``` + +**返回值描述:** + +- dict类型,响应头信息 + +**示例:** + +```python +import request + +response = request.get("http://httpbin.org/get") +print(response.headers) +``` + +### `response.text` + +使用 `response.text` 属性获取响应体数据,可以不读取数据使用`response.close`直接释放资源。 + +```python +response.text +``` + +**返回值描述:** + +- 生成器对象,通过for遍历读取全部返回的文本数据。 + +**示例:** + +```python +import request + +response = request.get("http://httpbin.org/get") +if True: + for i in response.text: + print(i) +else: + response.close() +``` + +### `response.content` + +使用 `response.content` 属性获取响应体数据。 + +```python +response.content +``` + +**返回值描述:** + +- 生成器对象,通过for遍历读取全部返回的响应体数据 + +**示例:** + +```python +import request + +response = request.get("http://httpbin.org/get") +for i in response.content: + print(i) +``` + +### `response.json` + +使用 `response.json` 属性获取JSON类型的响应体数据。 + +```python +response.json() +``` + +**返回值描述:** + +- 字典类型的响应体数据 + +**示例:** + +```python +import request + +response = request.get("http://httpbin.org/get") +data = response.json() +print(data) +``` +### `respnse.close` + +使用 `response.close`不读取服务器的数据主动关闭http,释放资源。 + +```python +response.close() +``` +**返回值描述:** + +- 无返回值 + +**示例:** +```python +import request + +response = request.get("http://httpbin.org/get") +response.close() +``` diff --git a/docs/API_reference/zh/networklib/umqtt.md b/docs/API_reference/zh/networklib/umqtt.md new file mode 100644 index 0000000000000000000000000000000000000000..9f324c84e3412bc6c5a66eb169d6939fa06d1611 --- /dev/null +++ b/docs/API_reference/zh/networklib/umqtt.md @@ -0,0 +1,577 @@ +# umqtt - MQTT客户端 + +模块功能:提供创建MQTT客户端发布订阅功能。 + +> umqtt 是python源码实现,如对应固件版本未默认支持。用户可使用源码 [umqtt.py](https://github.com/QuecPython/umqtt),放默认目录/usr下,使用时,将from umqtt import MQTTClient 改为from usr.umqtt import MQTTClient. + +``` +QoS级别说明 +在MQTT协议中,定义了三个级别的QoS,分别是: +QoS0 – 最多一次,是最低级别;发送者发送完消息之后,并不关心消息是否已经到达接收方; +QoS1 – 至少一次,是中间级别;发送者保证消息至少送达到接收方一次; +QoS2 – 有且仅有一次,是最高级别;保证消息送达且仅送达一次。 +``` + +## 构造函数 + +### `umqtt.MQTTClient` + +```python +class umqtt.MQTTClient(client_id, server, port=0, user=None, password=None, keepalive=60, ssl=False, ssl_params={},reconn=True,version=4) +``` + +构建mqtt连接对象。 + +**参数描述:** + +* `client_id` - 客户端 ID,字符串类型,具有唯一性。 + +* `server` - 服务端地址,字符串类型,可以是 IP 或者域名。 + +* `port` - 服务器端口(可选),整数类型,默认为1883,请注意,MQTT over SSL/TLS的默认端口是8883。 + +* `user` - (可选) 在服务器上注册的用户名,字符串类型。 + +* `password` - (可选) 在服务器上注册的密码,字符串类型。 + +* `keepalive` - (可选)客户端的keepalive超时值,整数类型,默认为60。 + +* `ssl` - (可选)是否使能 SSL/TLS 支持,布尔值类型。 + +* `ssl_params` - (可选)SSL/TLS 参数,如果SSL认证时需传入密钥,密钥格式为{"cert": certificate_content, "key": private_content},内容为字符串类型。 + +* `reconn` - (可选)控制是否使用内部重连的标志,布尔值类型,默认开启为True。 + +* `version` - (可选)选择使用mqtt版本,整数类型,version=3开启MQTTv3.1,默认version=4开启MQTTv3.1.1。 + + + +## 设置相关功能和回调 + +### `MQTTClient.set_callback` + +```python +MQTTClient.set_callback(callback) +``` + +设置回调函数,收到消息时会被调用。 + +>回调函数不建议处理阻塞API,会影响mqtt消息接收。 + + +**参数描述:** + +* `callback` - 设置异常回调函数,function(topic, data)类型 + +**示例:** + +```python +from umqtt import MQTTClient + +def data_cb(topic, data): + try: + print("umqtt recv topic[%s] data:%s:"%(topic, data)) + except Exception as e: + print("Handle error:%s"%str(e)) + +c = MQTTClient("umqtt_client", "mq.tongxinmao.com", 18830) +c.set_callback(data_cb) +``` + +### `MQTTClient.error_register_cb` + +```python +MQTTClient.error_register_cb(callback) +``` + +设置异常回调函数,使用内部重连的情况下umqtt内部线程异常时通过回调返回error信息。 + +**参数描述:** + +* `callback` - 设置异常回调函数,function(error)类型 + +**示例:** +```python +from umqtt import MQTTClient + +def err_cb(err): + print("thread err:%s"%err) + if err == "reconnect_start": + print("start reconnect") + elif err == "reconnect_success": + print("success reconnect") + else: + print("reconnect FAIL") + +c = MQTTClient("umqtt_client", "mq.tongxinmao.com", 18830) +c.error_register_cb(err_cb) +``` + +### `MQTTClient.set_last_will` + +```python +MQTTClient.set_last_will(topic,msg,retain=False,qos=0) +``` + +设置要发送给服务器的遗嘱,客户端没有调用disconnect()异常断开,则发送通知到其他客户端。 + +**参数描述:** + +* `topic` - mqtt遗嘱主题,字符串类型。 + +* `msg` - 遗嘱的内容,字符串类型。 + +* `retain` - retain = True boker会一直保留消息,默认False,布尔值类型。 + +* `qos` - 整数类型,消息服务质量(0~1)。 + + +## MQTT连接相关功能 + +### `MQTTClient.connect` + +```python +MQTTClient.connect(clean_session=True) +``` + +与服务器建立连接,连接失败会导致MQTTException异常。 + +>mqtt相关操作要在确认connect成功后执行。 + +**参数描述:** + +* `clean_session` - 布尔值类型,可选参数,一个决定客户端类型的布尔值。 如果为True,那么代理将在其断开连接时删除有关此客户端的所有信息。 如果为False,则客户端是持久客户端,当客户端断开连接时,订阅信息和排队消息将被保留。默认为True。 + +**返回值描述:** + +成功返回0,失败则抛出异常。 + + +### `MQTTClient.disconnect` + +```python +MQTTClient.disconnect() +``` + +与服务器断开连接,释放相关资源。 + + +### `MQTTClient.close` + +```python +MQTTClient.close() +``` + +释放socket资源,(注意区别disconnect方法,close只释放socket资源,disconnect包含线程等资源)。 + +>该方法仅用于在自己实现重连时使用,具体请参照mqtt重连示例代码,正常关闭mqtt连接请使用disconnect。 + + +### `MQTTClient.ping` + +```python +MQTTClient.ping() +``` + +当keepalive不为0且在时限内没有通讯活动,会主动向服务器发送ping包, 检测保持连通性,keepalive为0则不开启。 + + +## 发布订阅相关功能 + +### `MQTTClient.publish` + +```python +MQTTClient.publish(topic, msg, retain=False, qos=0) +``` + +发布消息到对应topic。 + +**参数描述:** + +* `topic` - mqtt 消息主题,字符串类型 + +* `msg` - 需要发送的数据,字符串类型 + +* `retain` - 布尔值类型,默认为False, 发布消息时把retain设置为true,即为保留信息。
MQTT服务器会将最近收到的一条RETAIN标志位为True的消息保存在服务器端, 每当MQTT客户端连接到MQTT服务器并订阅了某个topic,如果该topic下有Retained消息,那么MQTT服务器会立即向客户端推送该条Retained消息
特别注意:MQTT服务器只会为每一个Topic保存最近收到的一条RETAIN标志位为True的消息!也就是说,如果MQTT服务器上已经为某个Topic保存了一条Retained消息,当客户端再次发布一条新的Retained消息,那么服务器上原来的那条消息会被覆盖! | + +* `qos` - 整数类型, MQTT消息服务质量(默认0,可选择0或1)0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker + +**返回值描述:** + +成功返回布尔型True,失败返回布尔型False。 + + +### `MQTTClient.subscribe` + +```python +MQTTClient.subscribe(topic,qos) +``` + +订阅mqtt主题。 + +**参数描述:** + +* `topic` - mqtt topic主题,字符串类型。 + +* `qos` - MQTT消息服务质量(默认0,可选择0或1),整数类型
0:发送者只发送一次消息,不进行重试 1:发送者最少发送一次消息,确保消息到达Broker。 + + +### `MQTTClient.wait_msg` + +```python +MQTTClient.wait_msg() +``` + +阻塞等待服务器消息响应。 + +>该方法如果在线程中调用时,需保证创建线程栈空间>=16K,具体请参照mqtt重连示例代码. + +### `MQTTClient.get_mqttsta` + +```python +MQTTClient.get_mqttsta() +``` + +获取mqtt连接状态。 + +注意:BG95平台不支持该API。 + +>如果用户调用了 disconnect() 方法之后,再调用 MQTTClient.get_mqttsta() 会返回-1,因为此时创建的对象资源等都已经被释放。 + + +**返回值描述:** + +0:连接成功。 + +1:连接中。 + +2:服务端连接关闭。 + +-1:连接异常。 + + +**示例:** + +```python +''' +@Author: Baron +@Date: 2020-04-24 +@LastEditTime: 2020-04-24 17:06:08 +@Description: example for module umqtt +@FilePath: example_mqtt_file.py +''' +from umqtt import MQTTClient +import utime +import log +import checkNet + + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_MQTT_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +mqtt_log = log.getLogger("MQTT") + + +state = 0 + +def sub_cb(topic, msg): + global state + mqtt_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + state = 1 + + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + mqtt_log.info('Network connection successful!') + + # 创建一个mqtt实例 + c = MQTTClient("umqtt_client", "mq.tongxinmao.com", 18830) + # 设置消息回调 + c.set_callback(sub_cb) + #建立连接 + c.connect() + # 订阅主题 + c.subscribe(b"/public/TEST/quecpython") + mqtt_log.info("Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic" ) + # 发布消息 + c.publish(b"/public/TEST/quecpython", b"my name is Quecpython!") + mqtt_log.info("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython") + + while True: + c.wait_msg() # 阻塞函数,监听消息 + if state == 1: + break + # 关闭连接 + c.disconnect() + else: + mqtt_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +``` + +**MQTT断网异常重连示例** + +特别说明: + +1.下面示例代码中mqtt的reconn参数用于控制使用或关闭umqtt内部的重连机制,默认为True,使用内部重连机制。 + +2.如需测试或使用外部重连机制可参考此示例代码,测试前需将reconn=False,否则默认会使用内部重连机制! + +```python +''' +@Author: Baron +@Date: 2020-04-24 +@LastEditTime: 2021-05-25 17:06:08 +@Description: example for module umqtt +@FilePath: example_mqtt_file.py +''' +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值, +在执行用户代码前,会先打印这两个变量的值。 +''' +import utime +import log +import net +import _thread +import checkNet +import dataCall +import uos +from umqtt import MQTTClient + +PROJECT_NAME = "QuecPython_MQTT_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 调用disconnect后会通过该状态回收线程资源 +TaskEnable = True +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +mqtt_log = log.getLogger("MQTT") + + +# 封装mqtt,使其可以支持更多自定义逻辑 +class MqttClient(): + ''' + mqtt init + ''' + + # 说明:reconn该参数用于控制使用或关闭umqtt内部的重连机制,默认为True,使用内部重连机制。 + # 如需测试或使用外部重连机制可参考此示例代码,测试前需将reconn=False,否则默认会使用内部重连机制! + def __init__(self, clientid, server, port, user=None, password=None, keepalive=0, ssl=False, ssl_params={}, + reconn=True): + self.__clientid = clientid + self.__pw = password + self.__server = server + self.__port = port + self.__uasename = user + self.__keepalive = keepalive + self.__ssl = ssl + self.__ssl_params = ssl_params + self.topic = None + self.qos = None + # 网络状态标志 + self.__nw_flag = True + # 创建互斥锁 + self.mp_lock = _thread.allocate_lock() + # 创建类的时候初始化出mqtt对象 + self.client = MQTTClient(self.__clientid, self.__server, self.__port, self.__uasename, self.__pw, + keepalive=self.__keepalive, ssl=self.__ssl, ssl_params=self.__ssl_params, + reconn=reconn) + + def connect(self): + ''' + 连接mqtt Server + ''' + self.client.connect() + # 注册网络回调函数,网络状态发生变化时触发 + flag = dataCall.setCallback(self.nw_cb) + if flag != 0: + # 回调注册失败 + raise Exception("Network callback registration failed") + + def set_callback(self, sub_cb): + ''' + 设置mqtt回调消息函数 + ''' + self.client.set_callback(sub_cb) + + def error_register_cb(self, func): + ''' + 注册一个接收umqtt内线程异常的回调函数 + ''' + self.client.error_register_cb(func) + + def subscribe(self, topic, qos=0): + ''' + 订阅Topic + ''' + self.topic = topic # 保存topic ,多个topic可使用list保存 + self.qos = qos # 保存qos + self.client.subscribe(topic, qos) + + def publish(self, topic, msg, qos=0): + ''' + 发布消息 + ''' + self.client.publish(topic, msg, qos) + + def disconnect(self): + ''' + 关闭连接 + ''' + global TaskEnable + # 关闭wait_msg的监听线程 + TaskEnable = False + # 关闭之前的连接,释放资源 + self.client.disconnect() + + def reconnect(self): + ''' + mqtt 重连机制(该示例仅提供mqtt重连参考,根据实际情况调整) + PS:1.如有其他业务需要在mqtt重连后重新开启,请先考虑是否需要释放之前业务上的资源再进行业务重启 + 2.该部分需要自己根据实际业务逻辑添加,此示例只包含mqtt重连后重新订阅Topic + ''' + # 判断锁是否已经被获取 + if self.mp_lock.locked(): + return + self.mp_lock.acquire() + # 重新连接前关闭之前的连接,释放资源(注意区别disconnect方法,close只释放socket资源,disconnect包含mqtt线程等资源) + self.client.close() + # 重新建立mqtt连接 + while True: + net_sta = net.getState() # 获取网络注册信息 + if net_sta != -1 and net_sta[1][0] == 1: + call_state = dataCall.getInfo(1, 0) # 获取拨号信息 + if (call_state != -1) and (call_state[2][0] == 1): + try: + # 网络正常,重新连接mqtt + self.connect() + except Exception as e: + # 重连mqtt失败, 5s继续尝试下一次 + self.client.close() + utime.sleep(5) + continue + else: + # 网络未恢复,等待恢复 + utime.sleep(10) + continue + # 重新连接mqtt成功,订阅Topic + try: + # 多个topic采用list保存,遍历list重新订阅 + if self.topic is not None: + self.client.subscribe(self.topic, self.qos) + self.mp_lock.release() + except: + # 订阅失败,重新执行重连逻辑 + self.client.close() + utime.sleep(5) + continue + else: + utime.sleep(5) + continue + break # 结束循环 + # 退出重连 + return True + + def nw_cb(self, args): + ''' + dataCall 网络回调 + ''' + nw_sta = args[1] + if nw_sta == 1: + # 网络连接 + mqtt_log.info("*** network connected! ***") + self.__nw_flag = True + else: + # 网络断线 + mqtt_log.info("*** network not connected! ***") + self.__nw_flag = False + + def __listen(self): + while True: + try: + if not TaskEnable: + break + self.client.wait_msg() + except OSError as e: + # 判断网络是否断线 + if not self.__nw_flag: + # 网络断线等待恢复进行重连 + self.reconnect() + # 在socket状态异常情况下进行重连 + elif self.client.get_mqttsta() != 0 and TaskEnable: + self.reconnect() + else: + # 这里可选择使用raise主动抛出异常或者返回-1 + return -1 + + def loop_forever(self): + task_stacksize =_thread.stack_size() + name,platform = uos.uname()[1].split("=",1) + if platform == "EC600E" or platform == "EC800E": + _thread.stack_size(8 * 1024) + elif platform == "FCM362K": + _thread.stack_size(3 * 1024) + else: + _thread.stack_size(16 * 1024) + # 创建线程之前,按照平台,修改线程栈空间。 + _thread.start_new_thread(self.__listen, ()) + # 线程创建成功后,恢复平台线程栈默认大小。 + _thread.stack_size(task_stacksize) + +if __name__ == '__main__': + ''' + 手动运行本例程时,可以去掉该延时,如果将例程文件名改为main.py,希望开机自动运行时,需要加上该延时, + 否则无法从CDC口看到下面的 poweron_print_once() 中打印的信息 + ''' + utime.sleep(5) + checknet.poweron_print_once() + ''' + 如果用户程序包含网络相关代码,必须执行 wait_network_connected() 等待网络就绪(拨号成功); + 如果是网络无关代码,可以屏蔽 wait_network_connected() + 【本例程必须保留下面这一行!】 + ''' + checknet.wait_network_connected() + + def sub_cb(topic, msg): + # global state + mqtt_log.info("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + + c = MqttClient("umqtt_client_753", "mq.tongxinmao.com", 18830, reconn=False) + + def err_cb(error): + ''' + 接收umqtt线程内异常的回调函数 + ''' + mqtt_log.info(error) + c.reconnect() # 可根据异常进行重连 + + # c = MqttClient("umqtt_client_753", "mq.tongxinmao.com", 18830, reconn=False) + # 设置消息回调 + c.set_callback(sub_cb) + # 设置异常回调 + c.error_register_cb(err_cb) + # 建立连接 + c.connect() + # 订阅主题 + c.subscribe(b"/public/TEST/quecpython758") + mqtt_log.info("Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic") + # 发布消息 + c.publish(b"/public/TEST/quecpython758", b"my name is Quecpython!") + mqtt_log.info("Publish topic: /public/TEST/quecpython758, msg: my name is Quecpython") + # 监听mqtt消息 + c.loop_forever() + # 等待5s接收消息 + # PS:如果需要测试重连,包括服务器断开连接等情况,请注释掉c.disconnect()和utime.sleep(5) + # utime.sleep(5) + # 关闭连接 + # c.disconnect() +``` \ No newline at end of file diff --git a/docs/API_reference/zh/networklib/uping.md b/docs/API_reference/zh/networklib/uping.md new file mode 100644 index 0000000000000000000000000000000000000000..eb624e24449c9e1e7ccc8c6a2eb61d34ba4f4e27 --- /dev/null +++ b/docs/API_reference/zh/networklib/uping.md @@ -0,0 +1,52 @@ +# uping - 发送ping包 + +该模块实现了 IPv4 ping 请求功能。 + +>1.可能会存在host地址无法建立socket连接异常。 +>2.通过初始化参数中的`COUNT`和`INTERVAL`来确认发Ping包周期。 + +**示例:** + +```python +# 方式一 +# 打印输出方式 +import uping +uping.ping('www.baidu.com') + +# 以下是uping的输出, 无返回值 +#72 bytes from 49.49.48.46: icmp_seq=1, ttl=53, time=1169.909000 ms +#72 bytes from 49.49.48.46: icmp_seq=2, ttl=53, time=92.060000 ms +#72 bytes from 49.49.48.46: icmp_seq=3, ttl=53, time=94.818000 ms +#72 bytes from 49.49.48.46: icmp_seq=4, ttl=53, time=114.879000 ms +#4 packets transmitted, 4 packets received, 0 packet loss +#round-trip min/avg/max = 92.06000000000001/367.916/1169.909 ms + + +# 方式二 +# 设置quiet会得到输出结果 +import uping +result = uping.ping('baidu.com', quiet=True) +# result可以拿到对应数据 +# result(tx=4, rx=4, losses=0, min=76.93899999999999, avg=131.348, max=226.697) +``` + +## 发送 ping 请求 + +### `uping.ping` + +```python +uping.ping(HOST, SOURCE=None, COUNT=4, INTERVAL=1000, SIZE=64, TIMEOUT=5000, quiet=False) +``` + +周期性发送Ping包。 + +**参数描述:** + +- `HOST` - 主机名,字符串类型,所要ping的域名地址, 例如"baidu.com"。 +- `SOURCE` - 源地址,字符串类型,用于绑定, 一般情况下不需要传。 +- `COUNT` - 默认请求次数,整型,默认是4次,发送4次ping包。 +- `INTERVAL` - 间隔时间,整型,用于绑定, 一般情况下不需要传。 +- `SIZE` - 每次读取的包大小,整型,默认64, 无需修改。 +- `TIMEOUT` - 超时时间,整型,单位:ms, 默认5000ms。 +- `quiet` - 打印是否直接输出,布尔类型,默认:False,打印直接输出。若设为True, 默认打印的值会被转换成对象返回。 + diff --git a/docs/API_reference/zh/networklib/ussl.md b/docs/API_reference/zh/networklib/ussl.md new file mode 100644 index 0000000000000000000000000000000000000000..9e15c30c3621e94b8819c065fc31c1de0e960917 --- /dev/null +++ b/docs/API_reference/zh/networklib/ussl.md @@ -0,0 +1,178 @@ +# ussl - SSL加密通信 + +ussl模块实现了TLS/SSL加密通信功能, 主要用于单向和双向认证使用。 + + + +## 创建SSL连接通道 + +### `ussl.wrap_socket` + +```python +ussl.wrap_socket(sock,server_hostname=None,cert=None,key=None) +``` + +**参数描述:** + +- `sock` - usocket.socket对象, 必须参数,要包装的套接字(usocket.socket)对象 + +- `server_hostname` - 字符串类型, 可选参数, 服务器IP地址 + +- `cert` - 字符串类型, 可选参数, 数字证书数据 + +- `key` - 字符串类型, 可选参数, 私钥数据 + +**返回值描述:** + +返回一个被包装的`usocket.socket`对象 + + + +**示例:** + +```python +# 导入ussl模块 +# -*- coding: UTF-8 -*- +import ussl +import usocket +import log +import utime +import checkNet + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_Socket_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +socket_log = log.getLogger("SOCKET") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + socket_log.info('Network connection successful!') + # 1. 单向认证说明 + # 创建一个socket实例 + sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) + # 解析域名 + sockaddr=usocket.getaddrinfo('myssl.com', 443)[0][-1] + # 建立连接 + sock.connect(sockaddr) + # SSL连接. 前提需要服务器支持 + sock = ussl.wrap_socket(sock, server_hostname="myssl.com") + # 向服务端发送消息 + ret = sock.write('GET / HTTP/1.0\r\nHost: myssl.com\r\nAccept-Encoding: deflate\r\n\r\n') + socket_log.info('write %d bytes' % ret) + #接收服务端消息 + data=sock.read(256) + socket_log.info('read %s bytes:' % len(data)) + socket_log.info(data.decode()) + + # 关闭连接 + sock.close() + socket_log.info('--------------------Socket Ussl End-------------------') + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +# 2. 双向认证说明 +cert = "数据证书" +key = "私钥" +sock = ussl.wrap_socket(sock, server_hostname="myssl.com", cert=cert, key=key) + +``` + + + +## ssl加密算法套件支持 + +``` +ssl版本说明: +ussl 支持 SSL 3.0 至 TLS 1.2 和 DTLS通信。 +``` + +| 算法套件 | +| ------------------------------------------------------ | +| TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca9) | +| TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xccaa) | +| TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8) | +| TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c) | +| TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030) | +| TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x009f) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CCM (0xc0ad) | +| TLS_DHE_RSA_WITH_AES_256_CCM (0xc09f) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 (0xc024) | +| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (0xc028) | +| TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 (0x006b) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a) | +| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014) | +| TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039) | +| TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 (0xc0af) | +| TLS_DHE_RSA_WITH_AES_256_CCM_8 (0xc0a3) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc087) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc08b) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc07d) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc073) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc077) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 (0x00c4) | +| TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA (0x0088) | +| TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b) | +| TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f) | +| TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x009e) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CCM (0xc0ac) | +| TLS_DHE_RSA_WITH_AES_128_CCM (0xc09e) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (0xc023) | +| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (0xc027) | +| TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 (0x0067) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009) | +| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013) | +| TLS_DHE_RSA_WITH_AES_128_CBC_SHA (0x0033) | +| TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (0xc0ae) | +| TLS_DHE_RSA_WITH_AES_128_CCM_8 (0xc0a2) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc086) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc08a) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc07c) | +| TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc072) | +| TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc076) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0x00be) | +| TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA (0x0045) | +| TLS_RSA_WITH_AES_256_GCM_SHA384 (0x009d) | +| TLS_RSA_WITH_AES_256_CCM (0xc09d) | +| TLS_RSA_WITH_AES_256_CBC_SHA256 (0x003d) | +| TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) | +| TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 (0xc032) | +| TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 (0xc02a) | +| TLS_ECDH_RSA_WITH_AES_256_CBC_SHA (0xc00f) | +| TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02e) | +| TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 (0xc026) | +| TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA (0xc005) | +| TLS_RSA_WITH_AES_256_CCM_8 (0xc0a1) | +| TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc07b) | +| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 (0x00c0) | +| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA (0x0084) | +| TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc08d) | +| TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc079) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 (0xc089) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 (0xc075) | +| TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) | +| TLS_RSA_WITH_AES_128_CCM (0xc09c) | +| TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003c) | +| TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) | +| TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 (0xc031) | +| TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 (0xc029) | +| TLS_ECDH_RSA_WITH_AES_128_CBC_SHA (0xc00e) | +| TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02d) | +| TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 (0xc025) | +| TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA (0xc004) | +| TLS_RSA_WITH_AES_128_CCM_8 (0xc0a0) | +| TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc07a) | +| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0x00ba) | +| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA (0x0041) | +| TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc08c) | +| TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc078) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 (0xc088) | +| TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 (0xc074) | +| TLS_EMPTY_RENEGOTIATION_INFO_SCSV (0x00ff) | \ No newline at end of file diff --git a/docs/API_reference/zh/networklib/uwebsocket.md b/docs/API_reference/zh/networklib/uwebsocket.md new file mode 100644 index 0000000000000000000000000000000000000000..533cc713ac92f77015387004ae20dadde454970b --- /dev/null +++ b/docs/API_reference/zh/networklib/uwebsocket.md @@ -0,0 +1,86 @@ +# uwebsocket - websocket客户端 + +提供用于websocket连接使用 + + + +## 客户端连接 + +### uwebsocket.Client.connect + +```python +ws_client = uwebsocket.Client.connect(url, headers=None, debug=False) +``` + +**参数描述:**: + +* `url` - str类型, websocket的连接地址, 一般以"ws://xxx/"或"wss://xxx/"形式存在 +* `headers` - dict类型, 额外需要添加的headers, 用于除了标准连接头之外, 允许用户自己传额外的头部 +* `debug` - bool类型, 默认False, 当为True的情况下, 会输出日志 + + + +## send发送数据 + +### ws_client.send + +```python +ws_client.send(msg) +``` + +**参数描述:** +* `msg` - str/byte类型, 需要发送的数据 + + + +## recv接收数据 + +### ws_client.recv + +```python +ws_client.recv() +``` + +**返回值描述:** +* `result `- str/byte类型, recv接受返回的结果, 当接受空值或None的时候, 为连接被关闭 + + + +## 关闭连接 + +### ws_client.close + +```python +ws_client.close() +``` + + + +**示例:**: + +```python +import uwebsocket +import _thread + + +def recv(cli): + while True: + # 死循环接收数据 + recv_data = cli.recv() + print("recv_data = {}".format(recv_data)) + if not recv_data: + # 服务器关闭连接或客户端关闭连接 + print("cli close") + client.close() + break + + +# 创建客户端, debug=True输出日志, ip和端口需要自己填写, 或者是域名 +client = uwebsocket.Client.connect('ws://xxx/', debug=True) + +# 线程接收数据 +_thread.start_new_thread(recv, (client,)) + +# 发送数据 +client.send("this is a test msg") +``` \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/README.md b/docs/API_reference/zh/peripherals/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee6d104423e4315ea8610734db9c1ebfa110ef43 --- /dev/null +++ b/docs/API_reference/zh/peripherals/README.md @@ -0,0 +1,11 @@ +# QuecPython 外设接口 + +> QuecPython 外设接口库包括GPIO、UART等硬件接口相关的功能组件 + +本文描述了 QuecPython 外设接口库中的模块。 + +## QuecPython 外设接口库列表 + +- [machine - 硬件相关功能](./machine.md) +- [misc - 其他](./misc.md) +- [ethernet - 以太网相关功能](./ethernet.md) \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/ethernet.CH395.md b/docs/API_reference/zh/peripherals/ethernet.CH395.md new file mode 100644 index 0000000000000000000000000000000000000000..c7993ca4f4df2a6c40ff16447358b3ca9615bdbf --- /dev/null +++ b/docs/API_reference/zh/peripherals/ethernet.CH395.md @@ -0,0 +1,180 @@ +# class CH395 - CH395以太网卡控制 + +该类用于控制`CH395`型号以太网网卡设备。 + +> 当前仅支持EC600U系列 + +## 构造函数 + +### `ethernet.CH395` + +```python +class ethernet.CH395(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +加载CH395驱动,初始化CH395以太网卡,并返回CH395网卡对象。 + +**参数描述:** + +- `mac` - 字节流,6字节长度的 `mac` 地址。 +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 +- `spi_port` - 连接`CH395`的[SPI端口](./machine.SPI.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为了 `SPI1` 端口。 +- `spi_cs_pin` - 连接`CH395`的 `SPI` 片选[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为了 `Pin.GPIO4`。 +- `extint_pin` - 连接`CH395`的外部中断[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示上次配置的值,程序中默认配置为 `Pin.GPIO24`。 +- `reset_pin` - 连接`CH395`的重置[GPIO管脚](./machine.Pin.md), 表示上次配置的值,程序中默认配置为 `Pin.GPIO30`。 +- `work_mode` - 以太网工作模式配置,默认为终端模式,`0`/`1` 分别表示终端模式/网关模式。终端模式表示该模块作为终端设备连接供网设备上网。网关模式表示该模块作为网关,为外部设备提供网络访问,通过`4G`上网。 + +## 方法 + +### `CH395.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +网卡静态ip地址配置。 + +**参数描述:** + +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `CH395.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +网卡dns服务器配置。 + +**参数描述:** + +- `primary_dns` - `DNS`服务器主地址。 +- `secondary_dns` - `DNS`服务器辅地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `CH395.set_up` + +```python +nic.set_up() +``` + +网卡启动,启动后网卡正常处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `CH395.set_down` + +```python +nic.set_down() +``` + +网卡禁用,禁用后网卡不再处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `CH395.dhcp` + +```python +nic.dhcp() +``` + +动态ip获取,此方法是作为终端模式下使用,从而自动获取ip信息。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `CH395.ipconfig` + +```python +nic.ipconfig() +``` + +获取网卡网络信息,通过该方法获取到mac地址、主机名、IP地址类型、IP地址、子网掩码、网关地址和DNS服务器地址。 + +**返回值描述:** + +返回list类型。 + +格式如下: +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)] + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `mac` | `str` | `mac`地址,格式为`'XX-XX-XX-XX-XX-XX'` | +| `hostname`| `str` | 网卡名称 | +| `iptype` | `str` | `ip`类型,`4`表示`ipv4`,`6`表示`ipv6`,目前仅支持`ip4` | +| `ip` | `str` | `ip`地址 | +| `subnet` | `str` | 子网掩码 | +| `gateway`| `str` | 网关 | +| `primary_dns`| `str` | DNS服务器主地址 | +| `secondary_dns`| `str` | DNS服务器辅地址 | + +### `CH395.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +默认网卡配置。 + +**参数描述:** + +- `ip` - 默认网卡ip地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_default_NIC('192.168.1.100') +``` + +### `CH395.status` + +```python +nic.status() +``` + +获取网卡当前状态。 + +**返回值描述:** + +返回tuble类型。 + +格式内容如下: +(dev, active, link) + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `dev` | `bool` | 表示网卡设备是否连接正常,`True`/`False`表示有连接/未连接 | +| `active`| `bool` | 表示网卡是否激活使用,`True`/`False`表示启用/禁用,与`set_up`/`set_down`对应 | +| `link` | `bool` | 表示网卡网线是否连接,`True`/`False`表示已连接/未连接 | \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/ethernet.DM9051.md b/docs/API_reference/zh/peripherals/ethernet.DM9051.md new file mode 100644 index 0000000000000000000000000000000000000000..189f90dc09c499271c45b4563429e971ed1d975f --- /dev/null +++ b/docs/API_reference/zh/peripherals/ethernet.DM9051.md @@ -0,0 +1,139 @@ +# class DM9051 - DM9051以太网卡控制 + +该类用于控制`DM9051`型号以太网网卡设备。 + +> 当前仅支持EC600N/EG912N/EG915N系列及EC800MCN_LE + +## 构造函数 + +### `ethernet.DM9051` + +```python +class ethernet.DM9051(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +加载DM9051驱动,初始化DM9051以太网卡,并返回DM9051网卡对象。 + +**参数描述:** + +- `mac` - 字节流,6字节长度的 `mac` 地址。 +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 +- `spi_port` - 连接`DM9051`的[SPI端口](./machine.SPI.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为了 `SPI1` 端口。 +- `spi_cs_pin` - 连接`DM9051`的 `SPI` 片选[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为了 `Pin.GPIO13`。 +- `extint_pin` - 连接`DM9051`的外部中断[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示上次配置的值,程序中默认配置为 `Pin.GPIO19`。 +- `reset_pin` - 连接`DM9051`的重置[GPIO管脚](./machine.Pin.md),默认值为`-1`, 表示上次配置的值,程序中默认配置为 `Pin.GPIO17`。 +- `work_mode` - 以太网工作模式配置,默认为终端模式,`0`/`1` 分别表示终端模式/网关模式。终端模式表示该模块作为终端设备连接供网设备上网。网关模式表示该模块作为网关,为外部设备提供网络访问,通过`4G`上网。 + +> 默认值各个平台有差异,建议定义可用GPIO使用。 + +## 方法 + +### `DM9051.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +网卡静态ip地址配置。 + +**参数描述:** + +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `DM9051.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +网卡dns服务器配置。 + +**参数描述:** + +- `primary_dns` - `DNS`服务器主地址。 +- `secondary_dns` - `DNS`服务器辅地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `DM9051.set_up` + +```python +nic.set_up() +``` + +网卡启动,启动后网卡正常处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `DM9051.set_down` + +```python +nic.set_down() +``` + +网卡禁用,禁用后网卡不再处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `DM9051.dhcp` + +```python +nic.dhcp() +``` + +动态ip获取,此方法是作为终端模式下使用,从而自动获取ip信息。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `DM9051.ipconfig` + +```python +nic.ipconfig() +``` + +获取网卡网络信息,通过该方法获取到mac地址、主机名、IP地址类型、IP地址、子网掩码、网关地址和DNS服务器地址。 + +**返回值描述:** + +返回list类型。 + +格式如下: +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)] + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `mac` | `str` | `mac`地址,格式为`'XX-XX-XX-XX-XX-XX'` | +| `hostname`| `str` | 网卡名称 | +| `iptype` | `str` | `ip`类型,`4`表示`ipv4`,`6`表示`ipv6`,目前仅支持`ip4` | +| `ip` | `str` | `ip`地址 | +| `subnet` | `str` | 子网掩码 | +| `gateway`| `str` | 网关 | +| `primary_dns`| `str` | DNS服务器主地址 | +| `secondary_dns`| `str` | DNS服务器辅地址 | diff --git a/docs/API_reference/zh/peripherals/ethernet.W5500.md b/docs/API_reference/zh/peripherals/ethernet.W5500.md new file mode 100644 index 0000000000000000000000000000000000000000..62a335512a34d0df5e6a4c723b2578f1e5b609ff --- /dev/null +++ b/docs/API_reference/zh/peripherals/ethernet.W5500.md @@ -0,0 +1,162 @@ +# class W5500 - W5500以太网卡控制 + +该类用于控制`W5500`型号以太网网卡设备。 + +> 当前仅支持EC600N/EC600U/EC600M/EC800M/EG912N/EG915N/EC200U/EG915U系列 + + +## 构造函数 + +### `ethernet.W5500` + +```python +class ethernet.W5500(mac, ip='', subnet='', gateway='', spi_port=-1, spi_cs_pin=-1, extint_pin=-1, reset_pin=-1, work_mode=0) +``` + +加载W5500驱动,初始化W5500以太网卡,并返回W5500网卡对象。 + +**参数描述:** + +- `mac` - 字节流,6字节长度的 `mac` 地址。 +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 +- `spi_port` - 连接`W5500`的[SPI端口](./machine.SPI.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为 `SPI1` 端口。 +- `spi_cs_pin` - 连接`W5500`的 `SPI` 片选[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示使用上次配置的值,程序中默认配置为 `Pin.GPIO34`。 +- `extint_pin` - 连接`W5500`的外部中断[GPIO管脚](./machine.Pin.md),默认值为`-1`,表示上次配置的值,程序中默认配置为 `Pin.GPIO19`。 +- `reset_pin` - 连接`W5500`的重置[GPIO管脚](./machine.Pin.md),默认值为`-1`, 表示上次配置的值,程序中默认配置为 `Pin.GPIO17`。 +- `work_mode` - 以太网工作模式配置,默认为终端模式,`0`/`1` 分别表示终端模式/网关模式。终端模式表示该模块作为终端设备连接供网设备上网。网关模式表示该模块作为网关,为外部设备提供网络访问,通过`4G`上网。 + +> 注意:请勿使用spi_port的硬件CS脚,另选一个GPIO作为CS脚 + +## 方法 + +### `W5500.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +网卡静态ip地址配置。 + +**参数描述:** + +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `W5500.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +网卡dns服务器配置。 + +**参数描述:** + +- `primary_dns` - `DNS`服务器主地址。 +- `secondary_dns` - `DNS`服务器辅地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `W5500.set_up` + +```python +nic.set_up() +``` + +网卡启动,启动后网卡正常处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `W5500.set_down` + +```python +nic.set_down() +``` + +网卡禁用,禁用后网卡不再处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `W5500.dhcp` + +```python +nic.dhcp() +``` + +动态ip获取,此方法是作为终端模式下使用,从而自动获取ip信息。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `W5500.ipconfig` + +```python +nic.ipconfig() +``` + +获取网卡网络信息,通过该方法获取到mac地址、主机名、IP地址类型、IP地址、子网掩码、网关地址和DNS服务器地址。 + +**返回值描述:** + +返回list类型。 + +格式如下: +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)] + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `mac` | `str` | `mac`地址,格式为`'XX-XX-XX-XX-XX-XX'` | +| `hostname`| `str` | 网卡名称 | +| `iptype` | `str` | `ip`类型,`4`表示`ipv4`,`6`表示`ipv6`,目前仅支持`ip4` | +| `ip` | `str` | `ip`地址 | +| `subnet` | `str` | 子网掩码 | +| `gateway`| `str` | 网关 | +| `primary_dns`| `str` | DNS服务器主地址 | +| `secondary_dns`| `str` | DNS服务器辅地址 | + +### `W5500.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +默认网卡配置。 + +**参数描述:** + +- `ip` - 默认网卡ip地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_default_NIC('192.168.1.100') +``` diff --git a/docs/API_reference/zh/peripherals/ethernet.YT8512H.md b/docs/API_reference/zh/peripherals/ethernet.YT8512H.md new file mode 100644 index 0000000000000000000000000000000000000000..9a251617592c9cfb40c82009be5c7d4359145b7b --- /dev/null +++ b/docs/API_reference/zh/peripherals/ethernet.YT8512H.md @@ -0,0 +1,216 @@ +# class YT8512H - YT8512H PHY控制 + +该类用于控制`YT8512H/SZ18201`型号以太网网卡设备。 + +> 当前仅支持EC200A系列 + +## 构造函数 + +### `ethernet.YT8512H` + +```python +class ethernet.YT8512H(mac, ip='', subnet='', gateway='') +``` + +加载YT8512H驱动,初始化YT8512H phy设备,并返回YT8512H网卡对象。 + +**参数描述:** + +- `mac` - 字节流,6字节长度的 `mac` 地址。 +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 + +## 方法 + +### `YT8512H.set_addr` +```python +nic.set_addr(ip, subnet, gateway) +``` + +网卡静态ip地址配置。 + +**参数描述:** + +- `ip` - 以太网卡的 `ip` 地址,若值为空字符串'',表示使用默认值`192.168.1.100`。 +- `subnet` - 以太网卡的子网掩码地址,若值为空字符串'',表示使用默认值`255.255.255.0`。 +- `gateway` - 以太网卡的网关地址,若值为空字符串'',表示将 `ip` 地址的最后一位替换成`1`作为网关。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_addr('192.168.1.100', '', '') +``` + +### `YT8512H.set_dns` + +```python +nic.set_dns(primary_dns, secondary_dns) +``` + +网卡dns服务器配置。 + +**参数描述:** + +- `primary_dns` - `DNS`服务器主地址。 +- `secondary_dns` - `DNS`服务器辅地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_dns('8.8.8.8', '114.114.114.114') +``` + +### `YT8512H.set_up` + +```python +nic.set_up() +``` + +网卡启动,启动后网卡正常处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `YT8512H.set_down` + +```python +nic.set_down() +``` + +网卡禁用,禁用后网卡不再处理网口网络报文。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `YT8512H.dhcp` + +```python +nic.dhcp() +``` + +动态ip获取,此方法是作为终端模式下使用,从而自动获取ip信息。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +### `YT8512H.ipconfig` + +```python +nic.ipconfig() +``` + +获取网卡网络信息,通过该方法获取到mac地址、主机名、IP地址类型、IP地址、子网掩码、网关地址和DNS服务器地址。 + +**返回值描述:** + +返回list类型。 + +格式如下: +[(mac, hostname), (iptype, ip, subnet, gateway, primary_dns,secondary_dns)] + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `mac` | `str` | `mac`地址,格式为`'XX-XX-XX-XX-XX-XX'` | +| `hostname`| `str` | 网卡名称 | +| `iptype` | `str` | `ip`类型,`4`表示`ipv4`,`6`表示`ipv6`,目前仅支持`ip4` | +| `ip` | `str` | `ip`地址 | +| `subnet` | `str` | 子网掩码 | +| `gateway`| `str` | 网关 | +| `primary_dns`| `str` | DNS服务器主地址 | +| `secondary_dns`| `str` | DNS服务器辅地址 | + +### `YT8512H.set_default_NIC` + +```python +nic.set_default_NIC(ip) +``` + +默认网卡配置。 + +**参数描述:** + +- `ip` - 默认网卡ip地址。 + +**返回值描述:** + +成功返回整型值0,失败返回整型值-1。 + +**示例:** + +```python +nic.set_default_NIC('192.168.1.100') +``` + +### `YT8512H.status` + +```python +nic.status() +``` + +获取网卡当前状态。 + +**返回值描述:** + +返回tuble类型。 + +格式内容如下: +(dev, active, link) + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `dev` | `bool` | 表示网卡设备是否连接正常,`True`/`False`表示有连接/未连接 | +| `active`| `bool` | 表示网卡是否激活使用,`True`/`False`表示启用/禁用,与`set_up`/`set_down`对应 | +| `link` | `bool` | 表示网卡网线是否连接,`True`/`False`表示已连接/未连接 | + +### `YT8512H.speed` + +```python +nic.speed() +``` + +获取网卡当前上下行速率。 + +**返回值描述:** + +返回tuble类型。 + +格式内容如下: +(tx, rx) + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `tx` | `int` | 表示网卡当前发送数据速率,单位bps | +| `rx` | `int` | 表示网卡当前接收数据速率,单位bps | + +### `YT8512H.node` + +```python +nic.node() +``` + +获取网卡当前已连接终端列表。 + +**返回值描述:** + +返回list类型。 + +格式内容如下: +[(mac, ip, time),] + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `mac` | `byte` | 终端`mac`地址 | +| `ip`| `str` | 终端`ip`地址 | +| `time`| `int` | 终端已连接时长,单位秒 | \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/ethernet.md b/docs/API_reference/zh/peripherals/ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..5066a89b9c63df0f16db85686d1c14f6d9fe21b8 --- /dev/null +++ b/docs/API_reference/zh/peripherals/ethernet.md @@ -0,0 +1,86 @@ +# ethernet - 以太网相关功能 +`ethernet`模块包含以太网控制及网络配置功能,主要是针对不同类型以太网卡提供统一的管理方式。 + +**示例:** + +根据不同应用场景,分别以终端模式、网关模式、静态ip配置介绍网卡初始化过程。 + + +> 1. 以下示例只是针对模组侧的网卡应用配置,也需要对端进行对应操作方可正常使用。 +> 2. 以下示例部分网卡未完全实现,请根据不同网卡驱动对应说明进行使用。 + + +终端模式: + +```python +# 作为终端工作模式时,模块通过以太网网口连接外网。如W5500网口连接路由器,通过dhcp获取ip信息,从而模组可以通过该网口连接外部网络。 + +import ethernet + +# 加载对应的网卡驱动,并初始化网卡相关配置,driver替换成实际对应的网卡驱动。 +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# 获取动态IP地址。 +nic.dhcp() +print(nic.ipconfig()) + +# 此时可以启动其他网络服务,并通过以太网进行网络访问。 +... + +``` + +网关模式: + +```python +# 作为网关使用配置时,使用4G连接外网。如W5500网口连接电脑,电脑需要配置静态ip与W5500以太网卡同一网段,网关与W5500网卡地址一致,从而电脑能够通过4G网卡连接网络。 +import ethernet +import dataCall + +# 加载对应的网卡驱动,并初始化网卡相关配置,driver替换成实际对应的网卡驱动。 +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# 获取当前4G拨号ip信息。 +lte=dataCall.getInfo(1, 0) +print(lte) +if lte[2][0] == 1: + # 设置默认网卡,将4G作为默认网卡。 + nic.set_default_NIC(lte[2][2]) + +#启动网卡。 +nic.set_up() + +# 此时其他设备可以通过网线连接模组,实现4G上网。 +... + +``` + +静态IP配置: + +```python +# 静态ip配置,根据当前已有环境,自定义网络信息。 +import ethernet + +# 加载对应的网卡驱动,并初始化网卡相关配置,driver替换成实际对应的网卡驱动。 +nic = ethernet.diver(...) +print(nic.ipconfig()) + +# 配置静态ip地址192.168.1.100,子网掩码255.255.255.0,网关地址192.168.1.1。 +nic.set_addr('192.168.1.100','255.255.255.0','192.168.1.1') +print(nic.ipconfig()) + +# 启动网卡。 +nic.set_up() + +# 1. 终端模式下,此时可以启动其他网络服务,并通过以太网进行网络访问。 +# 2. 网关模式下,此时按照上例网关使用说明,配置默认网卡及对端静态ip,即可使用该模块提供网络服务。 +... + +``` + +## Classes +- [class W5500 – W5500驱动](./ethernet.W5500.md) +- [class DM9051 – DM9051驱动](./ethernet.DM9051.md) +- [class CH395 – CH395驱动](./ethernet.CH395.md) +- [class YT8512H – YT8512H驱动](./ethernet.YT8512H.md) diff --git a/docs/API_reference/zh/peripherals/machine.ExtInt.md b/docs/API_reference/zh/peripherals/machine.ExtInt.md new file mode 100644 index 0000000000000000000000000000000000000000..29f93270ce44f3bcd45799c5af574cf01a4d5ba7 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.ExtInt.md @@ -0,0 +1,128 @@ +# class ExtInt - 外部中断 + +该类用于配置I/O引脚在发生外部事件时中断。 + +## 构造函数 + +### `machine.ExtInt` + +```python +class machine.ExtInt(GPIOn, mode, pull, callback, [filter_time]) +``` + +**参数描述:** + +- `GPIOn` - 需要控制的GPIO引脚号,int类型,参照[Pin模块](./machine.Pin.md)的引脚定义(除BG95M3外),点此查看BG95M3平台引脚对应关系 + +- `mode` - 触发方式,int类型,说明如下:
`IRQ_RISING` – 上升沿触发
`IRQ_FALLING` – 下降沿触发
`IRQ_RISING_FALLING` – 上升和下降沿触发(EC600E/EC800E不支持) + +- `pull` - 上下拉模式,int类型,说明如下:
`PULL_PU` – 上拉模式
`PULL_PD` – 下拉模式
`PULL_DISABLE` – 浮空模式 + +- `callback` - 中断触发回调函数,int类型,说明如下:
返回参数为长度为2的元组
args[0]: gpio号
args[1]: 触发沿(0:上升沿 1:下降沿) + +- `[filter_time]` - 滤波时间,int类型,单位ms,缺省为0即不滤波,不为0时按设置的滤波时间进行滤波,支持设置的非零值为10的倍数。 + + > `[filter_time]`目前 EG912N/EG915N/EC600M/EC800M/EG810M/EC600K/EC800K/EG800P/EC200A/UC200A/EC600E/EC800E/EC800Z支持。 + +
+ BG95M3,BG95M8平台引脚对应关系
+GPIO2 – 引脚号5
GPIO3 – 引脚号6
GPIO6 – 引脚号19
GPIO7 – 引脚号22
GPIO8 – 引脚号23
GPIO9 – 引脚号25
GPIO11 – 引脚号27
GPIO12 – 引脚号28
GPIO14 – 引脚号41
GPIO16 – 引脚号65
GPIO17 – 引脚号66
GPIO18 – 引脚号85
GPIO19 – 引脚号86
GPIO22 – 引脚号20
GPIO23 – 引脚号21
GPIO24 – 引脚号30
GPIO25 – 引脚号34
GPIO26 – 引脚号35
GPIO29 – 引脚号38
GPIO30 – 引脚号39 +
+ + +**示例:** + +```python +# 创建ExtInt对象 +from machine import ExtInt +def fun(args): + print('### interrupt {} ###'.format(args)) # args[0]:gpio号 args[1]:上升沿或下降沿 +extint = ExtInt(ExtInt.GPIO1, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, fun) +extint = ExtInt(ExtInt.GPIO1, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, fun,filter_time=50)#使能滤波,滤波时间为50ms +``` + +## 方法 + +### `extint.enable` + +``` +extint.enable() +``` + +该方法用于使能中断,使能extint对象外部中断,当中断引脚收到上升沿或者下降沿信号时,会调用callback执行。 + +**返回值描述:** + +使能成功返回整型值`0`,使能失败返回整型值`-1`。 + +### `extint.disable` + +``` +extint.disable() +``` + +该方法用于关闭中断,禁用与extint对象关联的中断 。 + +**返回值描述:** + +使能成功返回整型值`0`,使能失败返回整型值`-1`。 + +### `extint.line` + +``` +extint.line() +``` + +该方法用于读取引脚映射行号。 + +**返回值描述:** + +返回引脚映射的行号。 + +**示例:** + +```python +>>> extint = ExtInt(ExtInt.GPIO1, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, fun) +>>> extint.line() +1 +``` + +### `extint.read_count` + +``` +extint.read_count(is_reset) +``` + +该方法用于返回触发中断的次数。 + +**参数描述:** + +- `is_reset` - 读取后是否重置计数,int类型,`0`表示不重置,`1`表示重置。 + +**返回值描述:** + +返回列表 `[rising_count, falling_count]`
`rising_count`:上升沿触发中断的次数
`falling_count`:下降沿触发中断的次数 + +### `extint.count_reset` + +``` +extint.count_reset() +``` + +该方法用于清空触发中断的次数。 + +**返回值描述:** + +返回`0`表示成功,返回其他表示失败。 + +### `extint.read_level` + +``` +extint.read_level() +``` + +该方法用于读取当前引脚电平。 + +**返回值描述:** + +返回引脚电平,`0`表示获取到的引脚电平为低电平,`1` 表示获取到的引脚电平为高电平。 \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/machine.I2C.md b/docs/API_reference/zh/peripherals/machine.I2C.md new file mode 100644 index 0000000000000000000000000000000000000000..094ffe62af97a84215abd76ac2ceff195bd73432 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.I2C.md @@ -0,0 +1,1582 @@ +# class I2C – I2C通信 + +该类用于设备之间通信的双线协议。 + + +## 构造函数 + +### `machine.I2C` + +
+
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2
    I2C3 : 3 - 通道3

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
  • 注: +
    1.模块的Pin57与PIN11、Pin56 与Pin12 内部是同一个管脚。 +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
  • 注: +
    1.模块的Pin67与Pin57、Pin66 与Pin58 内部是同一个管脚。 +
    2.EC800ECN_LE&LQ&CG 的57/58引脚不可用。 +
  • +
+
+ + +
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式
    ENHANCED_FAST_MODE2 - 快速模式增强

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE, [group])
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
  • [group] - 选择在不同管脚使用IIC,缺省值为0

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE, [group])
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
  • [group] - 选择在不同管脚使用IIC,缺省值为0

    +
  • +
+
+ +
+
class machine.I2C(I2Cn, MODE)
+
+

参数描述:

+
    +
  • I2Cn - I2C 通路索引号,int类型,说明如下:
    I2C0 : 0 - 通道0
    I2C1 : 1 - 通道1
    I2C2 : 2 - 通道2
    I2C3 : 3 - 通道3

    +
  • +
  • MODE - I2C 的工作模式,int类型,说明如下:
    STANDARD_MODE : 0 - 标准模式
    FAST_MODE1 - 快速模式

    +
  • +
+
+ +
+ +
+
+

示例:

+
>>> from machine import I2C
+>>> # 创建I2C对象
+>>> i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE)  # 返回I2C对象
+
+
+ +
+

示例:

+
>>> from machine import I2C
+>>> # 创建I2C对象
+>>> i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE,0)  # 返回I2C对象
+
+
+
+ +**I2C引脚对应关系:** + +
+ + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚11引脚12
I2C1引脚57引56
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚41引脚42
I2C1引脚141引142
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚41引脚42
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚41引脚42
I2C1引脚143引脚144
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚41引脚42
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚23引脚22
I2C1引脚20引脚21
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚18引脚19
I2C1引脚40引脚41
I2C2引脚26引脚25
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚9引脚64
I2C1引脚57引脚56
I2C2引脚67引脚65
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚103引脚114
I2C1引脚40引脚41
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C1引脚75引脚74
I2C2引脚68引脚69
I2C3引脚57引脚58
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C1引脚75引脚74
I2C2引脚68引脚69
I2C3引脚57引脚58
+ + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C1引脚40引脚41
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C1引脚57(11)引脚56(12)
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67(57)引脚66(58)
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚57引脚56
I2C1引脚11引脚12
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C1引脚57引脚58
I2C2引脚68引脚69
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C1引脚40引脚41
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C1引脚57引脚56
I2C3引脚11引脚12
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C2引脚68引脚69
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C2引脚68引脚69
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C2引脚68引脚69
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚29引脚23
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚30引脚29
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚81(group=0)引脚80(group=0)
I2C0引脚67(group=1)引脚66(group=1)
I2C1引脚57引脚58
+ + + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚12引脚26
I2C1引脚43引脚44
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚12引脚26
I2C2引脚43引脚44
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C1引脚40引脚41
+ + + + + + + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚67引脚66
I2C1引脚57引脚58
+ + + + + + + + + + + + + + + + +
I2C编号SCL引脚SDA引脚
I2C0引脚40引脚41
+ +
+ + + + +## 方法 + +### `I2C.read` + +```python +I2C.read(slaveaddress, addr,addr_len, r_data, datalen, delay) +``` + +该方法用于从 I2C 总线中读取数据。 + +**参数描述:** + +- `slaveaddress` - I2C 设备地址,int类型,传入七位设备地址即可,低位自动补1。 +- `addr` - I2C 寄存器地址,bytearray类型。 +- `addr_len` - 寄存器地址长度,int类型。 +- `r_data` - 接收数据的字节数组,bytearray类型。 +- `datalen` - 字节数组的长度,int类型。 +- `delay` - 延时,数据转换缓冲时间(单位ms),int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `I2C.write` + +```python +I2C.write(slaveaddress, addr, addr_len, data, datalen) +``` + +该方法用于从 I2C 总线中写入数据。 + +**参数描述:** + +- `slaveaddress` - I2C 设备地址,int类型,传入七位设备地址即可,低位自动补0。 +- `addr` - I2C 寄存器地址,bytearray类型。 +- `addr_len` - 寄存器地址长度,int类型。 +- `data` - 写入的数据,bytearray类型。 +- `datalen` - 写入数据的长度,int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +**使用示例:** + +> 需要连接设备使用。 + +```python +import log +from machine import I2C +import utime + +''' +I2C使用示例 +''' + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +i2c_log = log.getLogger("I2C") + + +if __name__ == '__main__': + I2C_SLAVE_ADDR = 0x1B # I2C 设备地址 + WHO_AM_I = bytearray([0x02, 0]) # I2C 寄存器地址,以buff的方式传入,取第一个值,计算一个值的长度 + + data = bytearray([0x12, 0]) # 输入对应指令 + i2c_obj = I2C(I2C.I2C0, I2C.STANDARD_MODE) # 返回I2C对象 + i2c_obj.write(I2C_SLAVE_ADDR, WHO_AM_I, 1, data, 2) # 写入data + + r_data = bytearray(2) # 创建长度为2的字节数组接收 + i2c_obj.read(I2C_SLAVE_ADDR, WHO_AM_I, 1, r_data, 2, 0) # read + i2c_log.info(r_data[0]) + i2c_log.info(r_data[1]) + +``` + +## 常量 + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C1I2C通路索引号: 1
I2C.I2C3I2C通路索引号: 3
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.I2C3I2C通路索引号: 3
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.I2C3I2C通路索引号: 3
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.I2C2I2C通路索引号: 2
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.I2C1I2C通路索引号: 1
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
I2C.ENHANCED_FAST_MODE快速模式增强
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
I2C.I2C0I2C通路索引号: 0
I2C.STANDARD_MODE标准模式
I2C.FAST_MODE快速模式
+ + +
\ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/machine.I2C_simulation.md b/docs/API_reference/zh/peripherals/machine.I2C_simulation.md new file mode 100644 index 0000000000000000000000000000000000000000..4eb2d6fcdfcdbca39216f88c157469029e8fdb2c --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.I2C_simulation.md @@ -0,0 +1,182 @@ +# class I2C_simulation - 模拟I2C通信 + +该类用于gpio模拟标准I2C协议,除了创建对象外,其它的操作(读写)均与I2C通信一致。 + +## 构造函数 + +### `machine.I2C_simulation` + +```python +class machin.I2C_simulation(GPIO_clk, GPIO_sda, CLK) +``` + +**参数描述:** + +- `GPIO_clk` - I2C 的CLK引脚(需要控制的GPIO引脚号,参照[Pin模块](machine.Pin.md)的定义),int类型。 +- `GPIO_sda` - I2C 的SDA引脚(需要控制的GPIO引脚号,参照[Pin模块](machine.Pin.md)的定义),int类型。 +- `CLK` - I2C 的频率,范围:(0,1000000Hz],int类型。 + +**示例:** + +```python +>>> from machine import I2C_simulation +>>> # 创建I2C_simulation对象 +>>> i2c_obj = I2C_simulation(I2C_simulation.GPIO10, I2C_simulation.GPIO11, 300) # 返回I2C对象 +``` + +## 方法 + +### `I2C_simulation.read` + +```python +I2C_simulation.read(slaveaddress, addr,addr_len, r_data, datalen, delay) +``` + +该方法用于从 I2C 总线中读取数据。 + +**参数描述:** + +- `slaveaddress` - I2C 设备地址,int类型,传入七位设备地址即可,低位自动补1。 +- `addr` - I2C 寄存器地址,bytearray类型。 +- `addr_len` - 寄存器地址长度,int类型。 +- `r_data` - 接收数据的字节数组,bytearray类型。 +- `datalen` - 字节数组的长度,int类型。 +- `delay` - 延时,数据转换缓冲时间(单位ms),int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `I2C_simulation.write` + +```python +I2C_simulation.write(slaveaddress, addr, addr_len, data, datalen) +``` + +该方法用于从 I2C 总线中写入数据。 + +**参数描述:** + +- `slaveaddress` - I2C 设备地址,int类型,传入七位设备地址即可,低位自动补0。 +- `addr` - I2C 寄存器地址,bytearray类型。 +- `addr_len` - 寄存器地址长度,int类型。 +- `data` - 写入的数据,bytearray类型。 +- `datalen` - 写入数据的长度,int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +**使用示例:** + +```python +import log +#from machine import I2C +from machine import I2C_simulation +import utime as time +""" +1. calibration +2. Trigger measurement +3. read data +""" +# API 手册 +# https://python.quectel.com/doc/API_reference/zh/peripherals/machine.I2C_simulation.html + +# AHT10 说明书 +# https://server4.eca.ir/eshop/AHT10/Aosong_AHT10_en_draft_0c.pdf +# 该示例是驱动AHT10获取温湿度数据 + +class aht10class(): + i2c_log = None + i2c_dev = None + i2c_addre = None + + # Initialization command + AHT10_CALIBRATION_CMD = 0xE1 + # Trigger measurement + AHT10_START_MEASURMENT_CMD = 0xAC + # reset + AHT10_RESET_CMD = 0xBA + + def write_data(self, data): + self.i2c_dev.write(self.i2c_addre, + bytearray(0x00), 0, + bytearray(data), len(data)) + pass + + def read_data(self, length): + print("read_data start") + r_data = [0x00 for i in range(length)] + r_data = bytearray(r_data) + print("read_data start1") + ret = self.i2c_dev.read(self.i2c_addre, + bytearray(0x00), 0, + r_data, length, + 0) + print("read_data start2") + print('ret',ret) + print('r_data:',r_data) + return list(r_data) + + def aht10_init(self, addre=0x38, Alise="Ath10"): + self.i2c_log = log.getLogger(Alise) + self.i2c_dev = I2C_simulation(I2C_simulation.GPIO10, I2C_simulation.GPIO11, 300) + self.i2c_addre = addre + self.sensor_init() + pass + + def aht10_transformation_temperature(self, data): + r_data = data + # 根据数据手册的描述来转化温度 + humidity = (r_data[0] << 12) | ( + r_data[1] << 4) | ((r_data[2] & 0xF0) >> 4) + humidity = (humidity/(1 << 20)) * 100.0 + print("current humidity is {0}%".format(humidity)) + temperature = ((r_data[2] & 0xf) << 16) | ( + r_data[3] << 8) | r_data[4] + temperature = (temperature * 200.0 / (1 << 20)) - 50 + print("current temperature is {0}°C".format(temperature)) + + + def sensor_init(self): + # calibration + self.write_data([self.AHT10_CALIBRATION_CMD, 0x08, 0x00]) + time.sleep_ms(300) # at last 300ms + pass + + + def ath10_reset(self): + self.write_data([self.AHT10_RESET_CMD]) + time.sleep_ms(20) # at last 20ms + + def Trigger_measurement(self): + # Trigger data conversion + self.write_data([self.AHT10_START_MEASURMENT_CMD, 0x33, 0x00]) + time.sleep_ms(200) # at last delay 75ms + # check has success + r_data = self.read_data(6) + # check bit7 + if (r_data[0] >> 7) != 0x0: + print("Conversion has error") + else: + self.aht10_transformation_temperature(r_data[1:6]) + +ath_dev = None + +def i2c_aht10_test(): + global ath_dev + ath_dev = aht10class() + ath_dev.aht10_init() + + # 测试十次 + for i in range(5): + ath_dev.Trigger_measurement() + time.sleep(1) + + +if __name__ == "__main__": + print('start') + i2c_aht10_test() + + +``` diff --git a/docs/API_reference/zh/peripherals/machine.KeyPad.md b/docs/API_reference/zh/peripherals/machine.KeyPad.md new file mode 100644 index 0000000000000000000000000000000000000000..d0be89060dcbc8fda64846575e5b2a9819856218 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.KeyPad.md @@ -0,0 +1,691 @@ +# class KeyPad - 矩阵键盘 + +该类提供矩阵键盘接口。 + + +## 构造函数 + +### `machine.KeyPad` + +```python +class machine.KeyPad(row,col) +``` + +**参数描述:** + +- `row` - 行,int类型,大于0,不超过平台支持最大值。 +- `col` - 列,int类型,大于0,不超过平台支持最大值。 + +> 如果row和col均不设置,默认为4X4。 + +
+ + + + + + + + + + + + + +
最大行最大列
44
+ + + + + + + + + + + + + + +
最大行最大列
6(EC200UXXAA系列只支持4行,见管脚说明)4
+ + + + + + + + + + + + + + +
最大行最大列
66
+ + + + + + + + + + + + + + +
最大行最大列
55
+ + + + + + + + + + + + + + +
最大行最大列
55
+ + + + + + + + + + + + + + +
最大行最大列
5(EG810MEU只支持3行)5(EG810MEU只支持3行)
+ + + + + + + + + + + + + + +
最大行最大列
33
+ + + + + + + + + + + + + + +
最大行最大列
44
+ + + + + + + + + + + + + + +
最大行最大列
33
+ + + + + + + + + + + + + + +
最大行最大列
55
+ + + + + + + + + + + + + + +
最大行最大列
44
+ +
+ +**KeyPad引脚对应关系:** + +> 当不使用全部引脚时,接线按行列号从小到大顺序接线,比如EC600M使用2x2矩阵键盘时,硬件使用49、51和48、50引脚。 + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号49列号0引脚号48
行号1引脚号51列号1引脚号50
行号2引脚号53列号2引脚号52
行号3引脚号55列号3引脚号54
行号4引脚号56列号4引脚号57
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号86列号0引脚号87
行号1引脚号76列号1引脚号77
行号2引脚号85列号2引脚号84
行号3引脚号82列号3引脚号83
行号4引脚号74列号4引脚号75
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号86(EG810MEU不支持)列号0引脚号87(EG810MEU不支持)
行号1引脚号76列号1引脚号77
行号2引脚号85(EG810MEU不支持)列号2引脚号84(EG810MEU不支持)
行号3引脚号82列号3引脚号83
行号4引脚号74列号4引脚号75
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号1引脚号20列号2引脚号105
行号2引脚号16列号3引脚号21
行号3引脚号116列号4引脚号1
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号83列号0引脚号115
行号1引脚号84列号1引脚号78
行号2引脚号113列号2引脚号79
行号3引脚号114列号3引脚号80
行号4引脚号81(EC200UXXAA系列不支持)列号4/
行号5引脚号82(EC200UXXAA系列不支持)列号5/
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号105列号0引脚号55
行号1引脚号106列号1引脚号129
行号2引脚号107列号2引脚号128
行号3引脚号108列号3引脚号127
行号4引脚号104列号4引脚号126
行号5引脚号103列号5引脚号125
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号39列号0引脚号83
行号1引脚号20列号2引脚号28
行号2引脚号27列号3引脚号25
行号3引脚号26列号4引脚号1
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号53列号0引脚号52
行号1引脚号49列号1引脚号54
行号2引脚号55列号2引脚号50
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号74列号0引脚号75
行号1引脚号76列号1引脚号77
行号2引脚号86列号2引脚号87
行号3引脚号82列号3引脚号81
行号4引脚号29列号4引脚号28
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
行号行号引脚列号列号引脚
行号0引脚号74列号0引脚号75
行号1引脚号76列号1引脚号77
行号2引脚号86列号2引脚号87
行号3引脚号82列号3引脚号81
+ +
+ +**示例:** + +```python +>>> # 创建keypad对象 +>>> import machine +>>> keypad=machine.KeyPad(2,3) # 设置为2行3列矩阵键盘 +>>> keypad=machine.KeyPad() # 参数缺省,默认设置为4行4列矩阵键盘 +>>> keypad=machine.KeyPad(2) # 行值设置为2,列值缺省,列值默认为4,初始化为2行4列矩阵键盘 +``` + +## 方法 + +### `keypad.init` + +```python +keypad.init() +``` + +该方法用于初始化keypad设置。 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1` 。 + +### `keypad.set_callback` + +```python +keypad.set_callback(usrFun) +``` + +该方法用于设置回调函数,外接按键接入模组后,当外接键盘按键按放时会触发此回调函数。 + +**参数描述:** + +- `usrFun` - 矩阵键盘回调函数,回调函数原型: + + ```python + usrFun(result_list) + ``` + + 回调函数参数描述: + + - `result_list[0]`:按键状态(1表示按下,0表示抬起) + + - `result_list[1]`:行号 + + - `result_list[2]`:列号 + +> 以EC600M为例,假设按键连接的管脚为49,52脚,按下后产生的回调的参数为[1,0,2],松开后产生的回调的参数为[0,0,2]。 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1` 。 + +### `keypad.deinit` + +```python +keypad.deinit() +``` + +该方法用于解除初始化,释放初始化的资源和回调函数设置。 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1` 。 + +**使用示例:** + +```python +import machine +import utime +is_loop = 1 +keypad=machine.KeyPad() +keypad.init() +def userfun(l_list): + global is_loop + if l_list[0] != 1 : + is_loop = 0 + print('will exit') + print(l_list) +keypad.set_callback(userfun) +loop_num = 0 +while is_loop == 1 and loop_num < 10: + utime.sleep(5) + loop_num = loop_num +1 + print(" running..... ",is_loop,loop_num) +keypad.deinit() +print('exit!') +``` diff --git a/docs/API_reference/zh/peripherals/machine.LCD.md b/docs/API_reference/zh/peripherals/machine.LCD.md new file mode 100644 index 0000000000000000000000000000000000000000..66fad7f5612b57e4e93d6b3c2b1fc80945c4b6b3 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.LCD.md @@ -0,0 +1,517 @@ +# class LCD - LCD显示屏 + +该类提供对LCD显示屏的控制。 + +> 支持的平台和模块型号: +> +> EC200U系列、EC600U系列、EC600N系列、EC800N系列 +> +> EC600M-CNLA、EC600M-CNLE +> +> EC800M-CNLA、EC800M-CNLE、EC800M-CNGA、EC800G-CNGA、EG810M-CNGA +> +> EG912N-ENAA、EG912U-GLAA +> +> EG915N-EUAG、EG915U-EUAB + +## 构造函数 + +### `machine.LCD` + +```python +class machine.lcd = LCD() +``` + +**示例:** + +```python +>>> from machine import LCD +>>> lcd = LCD() # 创建lcd对象 +``` + +## 方法 + +### `lcd.lcd_init` + +该方法用于初始化LCD。 + +#### **接口1:设备接模块LCM接口** + +```python +lcd.lcd_init(lcd_init_data, lcd_width, lcd_hight, lcd_clk, data_line, line_num, lcd_type, lcd_invalid, lcd_display_on, lcd_display_off, lcd_set_brightness) +``` + +**参数描述:** + +| 参数 | 类型 | 说明 | +| ------------------ | --------- | ------------------------------------------------------------ | +| lcd_init_data | bytearray | LCD 初始化的配置命令 | +| lcd_width | int | LCD 屏幕的宽度,宽度不超过 500像素 | +| lcd_hight | int | LCD 屏幕的高度,高度不超过 500像素 | +| lcd_clk | int | LCD SPI 时钟频率:
6500: 6.5MHz
13000:13MHz
26000:26MHz
52000:52MHz | +| data_line | int | 数据线数,参数值为 1 和 2 | +| line_num | int | 线的数量,参数值为 3 和 4 | +| lcd_type | int | 屏幕类型,0 - rgb;1 - fstn | +| lcd_invalid | bytearray | LCD 区域设置的配置命令 | +| lcd_display_on | bytearray | LCD 屏亮的配置命令 | +| lcd_display_off | bytearray | LCD 屏灭的配置命令 | +| lcd_set_brightness | bytearray | LCD屏亮度的配置命令:
设置为 None表示由 LCD_BL_K 控制亮度 | + +**返回值描述:** + +`0` 表示成功。 + +`-1` 表示已经初始化。 + +`-2` 表示参数错误,为空或过大(大于 1000 像素点)。 + +`-3` 表示缓存申请失败。 + +`-5` 表示配置参数错误。 + +#### **接口2:设备接模块SPI接口** + +```python +lcd.lcd_init(lcd_init_data, lcd_width, lcd_hight, lcd_clk, data_line, line_num, lcd_type, lcd_invalid, lcd_display_on, lcd_display_off, lcd_set_brightness, lcd_interface, spi_port, spi_mode, cs_pin, dc_pin, rst_pin) +``` + +**参数描述:** + +| 参数 | 类型 | 说明 | +| ------------------ | --------- | ------------------------------------------------------------ | +| lcd_init_data | bytearray | LCD 初始化的配置命令 | +| lcd_width | int | LCD 屏幕的宽度,宽度不超过 500像素 | +| lcd_hight | int | LCD 屏幕的高度,高度不超过 500像素 | +| lcd_clk | int | SPI 时钟,见machine.SPI 创建SPI对象参数说明clk | +| data_line | int | 数据线数,参数值为 1 和 2 | +| line_num | int | 线的数量,参数值为 3 和 4 | +| lcd_type | int | 屏幕类型,0 - rgb;1 - fstn | +| lcd_invalid | bytearray | LCD 区域设置的配置命令 | +| lcd_display_on | bytearray | LCD 屏亮的配置命令 | +| lcd_display_off | bytearray | LCD 屏灭的配置命令 | +| lcd_set_brightness | bytearray | LCD屏亮度的配置命令:
设置为 None表示由 LCD_BL_K 控制亮度 | +| lcd_interface | int | LCD接口类型,0 - LCM接口;1 - SPI接口 | +| spi_port | int | 通道选择[0,1],参照SPI部分 | +| spi_mode | int | SPI 的工作模式(通常使用工作模式0):
时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
0 : CPOL=0, CPHA=0
1 : CPOL=0, CPHA=1
2 : CPOL=1, CPHA=0
3 : CPOL=1, CPHA=1 | +| cs_pin | int | CS引脚,见[machine.Pin](machine.Pin.md)中GPIO引脚编号说明 | +| dc_pin | int | DC引脚,见[machine.Pin](machine.Pin.md)中GPIO引脚编号说明 | +| rst_pin | int | RST引脚,见[machine.Pin](machine.Pin.md)中GPIO引脚编号说明 | + +**返回值描述:** + +`0` 表示成功。 + +`-1` 表示屏幕已经初始化。 + +`-2` 表示参数错误,为空或过大(大于 1000 像素点)。 + +`-3` 表示缓存申请失败。 + +`-5` 表示配置参数错误。 + + +### `lcd.mipi_init` + +```python +lcd.mipi_init(initbuf, **kwargs) +``` + +该方法用于初始化MIPI,按键值对传参,请根据屏厂提供的初始化参数填写。 + +> 1.仅支持EC200U系列和EC600U系列。 +> +> 2.参数列表中,initbuf为必传参数;后面参数与缺省值不同时传入。 + +**参数描述:** + +| 参数 | 类型 | 说明 | +| ----------- | --------- | ------------------------------------------------------------ | +| initbuf | bytearray | 必传,传入 MIPI 的配置命令 | +| width | int | 缺省值:480,屏幕的宽度,单位像素,示例:width=400 | +| hight | int | 缺省值:854,屏幕的高度,单位像素,示例:hight=800 | +| bpp | int | 缺省值:16,像素深度 | +| DataLane | int | 缺省值:2,数据通道 | +| MipiMode | int | 缺省值:0
模式:
0:DSI_VIDEO_MODE
1:DSI_CMD_MODE | +| PixelFormat | int | 缺省值:0
像素格式:
0:RGB_PIX_FMT_RGB565
16:RGB_PIX_FMT_RGB888
32:RGB_PIX_FMT_XRGB888
48:RGB_PIX_FMT_RGBX888 | +| DsiFormat | int | 缺省值:0
DSI格式:
0:DSI_FMT_RGB565
1:DSI_FMT_RGB666
2:DSI_FMT_RGB666L
3:DSI_FMT_RGB888 | +| TransMode | int | 缺省值:3
转换模式:
0:DSI_CMD
1:DSI_PULSE
2:DSI_EVENT
3:DSI_BURST | +| RgbOrder | int | 缺省值:8
RGB顺序:
0:RGB
8:BGR | +| BllpEnable | bool | 缺省值:true,blank low power 模式使能 | +| HSync | int | 缺省值:10,水平同步 | +| HBP | int | 缺省值:10,水平后肩 | +| HFP | int | 缺省值:10,水平前肩 | +| VSync | int | 缺省值:4,垂直同步 | +| VBP | int | 缺省值:10,垂直后肩 | +| VFP | int | 缺省值:14,垂直前肩 | +| FrameRate | int | 缺省值:60,帧率 | +| TESel | bool | 缺省值:false,TE选择 | +| RstPolarity | int | 缺省值:1,reset极性 | + +**返回值描述:** + + +成功则返回`0`, 失败则报错。 + +**mipi屏引脚说明:** + +| 引脚名 | EC600U系列 | EC200U系列 | +| ------ | ---------- | ---------- | +| CKN | PIN61 | PIN27 | +| CKP | PIN58 | PIN26 | +| D1N | PIN59 | PIN24 | +| D1P | PIN60 | PIN25 | +| D0N | PIN69 | PIN13 | +| D0P | PIN70 | PIN135 | +| FMARK | PIN62 | PIN119 | +| RESET | PIN64 | PIN120 | + +**使用示例:** + +```python +init_480X854 = ( +0x11,0,0, +0xFF,120,5,0x77,0x01,0x00,0x00,0x10, +0xC0,0,2,0xE9,0x03, +0xC1,0,2,0x11,0x02, +0xC2,0,2,0x31,0x08, +0xCC,0,1,0x10, +0xB0,0,16,0x00,0x0D,0x14,0x0D,0x10,0x05,0x02,0x08,0x08,0x1E,0x05,0x13,0x11,0xA3,0x29,0x18, +0xB1,0,16,0x00,0x0C,0x14,0x0C,0x10,0x05,0x03,0x08,0x07,0x20,0x05,0x13,0x11,0xA4,0x29,0x18, +0xFF,0,5,0x77,0x01,0x00,0x00,0x11, +0xB0,0,1,0x6C, +0xB1,0,1,0x43, +0xB2,0,1,0x07, +0xB3,0,1,0x80, +0xB5,0,1,0x47, +0xB7,0,1,0x85, +0xB8,0,1,0x20, +0xB9,0,1,0x10, +0xC1,0,1,0x78, +0xC2,0,1,0x78, +0xD0,0,1,0x88, +0xE0,100,3,0x00,0x00,0x02, +0xE1,0,11,0x08,0x00,0x0A,0x00,0x07,0x00,0x09,0x00,0x00,0x33,0x33, +0xE2,0,13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0xE3,0,4,0x00,0x00,0x33,0x33, +0xE4,0,2,0x44,0x44, +0xE5,0,16,0x0E,0x60,0xA0,0xA0,0x10,0x60,0xA0,0xA0,0x0A,0x60,0xA0,0xA0,0x0C,0x60,0xA0,0xA0, +0xE6,0,4,0x00,0x00,0x33,0x33, +0xE7,0,2,0x44,0x44, +0xE8,0,16,0x0D,0x60,0xA0,0xA0,0x0F,0x60,0xA0,0xA0,0x09,0x60,0xA0,0xA0,0x0B,0x60,0xA0,0xA0, +0xEB,0,7,0x02,0x01,0xE4,0xE4,0x44,0x00,0x40, +0xEC,0,2,0x02,0x01, +0xED,0,16,0xAB,0x89,0x76,0x54,0x01,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x10,0x45,0x67,0x98,0xBA, +0xFF,0,5,0x77,0x01,0x00,0x00,0x00, +0x3A,0,1,0x77, +0x36,0,1,0x00, +0x35,0,1,0x00, +0x29,0,0 +) +from machine import LCD +mipilcd = LCD() +mipilcd.mipi_init(initbuf=bytearray(init_480X854), TransMode=1) +``` + +### `lcd.lcd_clear` + +``` +lcd.lcd_clear(color) +``` + +该方法用于清除屏幕。 + +**参数描述:** + +- `color` - 需要刷屏的颜色值,16进制。 + +**返回值描述:** + +成功返回`0`,失败返回`-1`。 + +### `lcd.lcd_write` + +``` +lcd.lcd_write(color_buffer,start_x,start_y,end_x,end_y) +``` + +该方法用于区域写屏。 + +**参数描述:** + +- `color_buffer` - 屏幕的颜色值缓存,bytearray类型。 +- `start_x` - 起始 x 坐标,int类型。 +- `start_y` - 起始 y 坐标,int类型。 +- `end_x` - 结束 x 坐标,int类型。 +- `end_y` - 结束 y 坐标,int类型。 + +**返回值描述:** + +`0` 表示成功。 + +`-1` 表示屏幕未初始化。 + +`-2` 表示宽度和高度设置错误。 + +`-3 ` 表示数据缓存为空。 + +### `lcd.lcd_brightness` + +``` +lcd.lcd_brightness(level) +``` + +该方法用于设置屏幕亮度等级。 + +**参数描述:** + +- `level` - 亮度等级,int类型 ,说明如下:
此处会调用 lcd.lcd_init()中的 lcd_set_brightness回调。若该参数为 None,亮度调节则由背光亮度调节引脚来控制,范围[0,5]。 + +**返回值描述:** + +成功返回`0`, 失败返回`-1`。 + +### `lcd.lcd_display_on` + +``` +lcd.lcd_display_on() +``` + +此接口用于向LCD发送lcd_display_on指令来打开屏幕显示,请确保lcd初始化的时候传入了正确的lcd_display_on指令。 + +**返回值描述:** + +成功返回`0`, 失败返回`-1`。 + +### `lcd.lcd_display_off` + +```python +lcd.lcd_display_off() +``` + +此接口用于向LCD发送lcd_display_off 指令来关闭屏幕显示,请确保lcd初始化的时候传入了正确的lcd_display_off 指令。 + +**返回值描述:** + +成功返回`0`, 失败返回`-1`。 + +### `lcd.lcd_write_cmd` + +``` +lcd.lcd_write_cmd(cmd_value, cmd_value_len) +``` + +该方法用于写入命令。 + +**参数描述:** + +- `cmd_value` - 命令值 ,16进制 。 +- `cmd_value_len` - 命令值长度,int类型。 + +**返回值描述:** + +成功返回`0`, 失败返回其他值。 + +### `lcd.lcd_write_data` + +```python +lcd.lcd_write_data(data_value, data_value_len) +``` + +该方法用于写入数据。 + +**参数描述:** + +- `data_value` - 数据值,16进制。 +- `data_value_len` - 数据值长度,int类型。 + +**返回值描述:** + +成功返回`0`, 失败返回其他值。 + +### `lcd.lcd_show` + +支持此方法的模块:EC600K/EC800K/EG800P 系列模块。 + +``` +lcd.lcd_show(file_name, start_x,start_y,width,hight) +``` + +该方法采用读文件方式,显示图片。 + +> 该文件是由Image2Lcd工具生成的bin文件,若勾选包含图像头文件,则width和hight无需填写。 + +**参数描述:** + +- `file_name ` - 需要显示的图片名,str类型。 +- `start_x` - 起始x坐标,int类型。 +- `start_y` - 起始y坐标,int类型。 +- `width` - 图片宽度(若图片文件包含头信息,则该处不填),int类型。 +- `hight` - 图片高度(若图片文件包含头信息,则该处不填),int类型。 + +**返回值描述:** + +成功返回`0`, 失败返回其他值。 + +### `lcd.lcd_show_jpg` + +支持此方法的模块:EC600K/EC800K/EG800P 系列模块。 + + +```python +lcd.lcd_show_jpg( file_name, start_x,start_y) +``` + +该方法采用读文件方式,显示jpeg图片。 + +**参数描述:** + +- `file_name ` - 需要显示的图片名,str类型。 +- `start_x` - 起始x坐标,int类型。 +- `start_y` - 起始y坐标,int类型。 + +**返回值描述:** + +成功返回`0`, 失败返回其他值。 + +**使用示例:** + +> 需要配合LCD屏使用,如下代码以st7789为例。 + +```python +from machine import LCD + +# 根据LCD商家给出的相应的初始化示例来填写 +# 第一行:2, 0, 120, 2表示sleep命令,中间恒为0,120表示sleep的毫秒数。收到此行数据,LCD将sleep 120ms +# 第二行:0, 0, 0x11, 0表示写入寄存器地址命令,中间数字表示后续需要写入的DATA长度,0表示没有要写入的数据,0x11是寄存器地址 +# 第三行:0, 1, 0x36, 0表示写入寄存器地址命令,中间数字表示后续需要写入的DATA长度,1表示要写入一字节数据,0x36是寄存器地址 +# 第四行:1, 1, 0x00, 1表示写入数据命令,中间数字表示写入的数据长度,0x00是数据 +# 后面按照前四行的格式将初始化示例填入即可 +init_data = (2, 0, 120, + 0, 0, 0x11, + 0, 1, 0x36, + 1, 1, 0x00, + 0, 1, 0x3A, + 1, 1, 0x05, + 0, 0, 0x21, + 0, 5, 0xB2, + 1, 1, 0x05, + 1, 1, 0x05, + 1, 1, 0x00, + 1, 1, 0x33, + 1, 1, 0x33, + 0, 1, 0xB7, + 1, 1, 0x23, + 0, 1, 0xBB, + 1, 1, 0x22, + 0, 1, 0xC0, + 1, 1, 0x2C, + 0, 1, 0xC2, + 1, 1, 0x01, + 0, 1, 0xC3, + 1, 1, 0x13, + 0, 1, 0xC4, + 1, 1, 0x20, + 0, 1, 0xC6, + 1, 1, 0x0F, + 0, 2, 0xD0, + 1, 1, 0xA4, + 1, 1, 0xA1, + 0, 1, 0xD6, + 1, 1, 0xA1, + 0, 14, 0xE0, + 1, 1, 0x70, + 1, 1, 0x06, + 1, 1, 0x0C, + 1, 1, 0x08, + 1, 1, 0x09, + 1, 1, 0x27, + 1, 1, 0x2E, + 1, 1, 0x34, + 1, 1, 0x46, + 1, 1, 0x37, + 1, 1, 0x13, + 1, 1, 0x13, + 1, 1, 0x25, + 1, 1, 0x2A, + 0, 14, 0xE1, + 1, 1, 0x70, + 1, 1, 0x04, + 1, 1, 0x08, + 1, 1, 0x09, + 1, 1, 0x07, + 1, 1, 0x03, + 1, 1, 0x2C, + 1, 1, 0x42, + 1, 1, 0x42, + 1, 1, 0x38, + 1, 1, 0x14, + 1, 1, 0x14, + 1, 1, 0x27, + 1, 1, 0x2C, + 0, 0, 0x29, + 0, 1, 0x36, + 1, 1, 0x00, + 0, 4, 0x2a, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0xef, + 0, 4, 0x2b, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0x00, + 1, 1, 0xef, + 0, 0, 0x2c,) + +display_on_data = ( + 0, 0, 0x11, + 2, 0, 20, + 0, 0, 0x29, +) +display_off_data = ( + 0, 0, 0x28, + 2, 0, 120, + 0, 0, 0x10, +) +# 设置区域参数 +XSTART_H = 0xf0 +XSTART_L = 0xf1 +YSTART_H = 0xf2 +YSTART_L = 0xf3 +XEND_H = 0xE0 +XEND_L = 0xE1 +YEND_H = 0xE2 +YEND_L = 0xE3 +invalid_data = ( + 0, 4, 0x2a, + 1, 1, XSTART_H, + 1, 1, XSTART_L, + 1, 1, XEND_H, + 1, 1, XEND_L, + 0, 4, 0x2b, + 1, 1, YSTART_H, + 1, 1, YSTART_L, + 1, 1, YEND_H, + 1, 1, YEND_L, + 0, 0, 0x2c, +) + +lcd = LCD() +init_list = bytearray(init_data) +display_on_list = bytearray(display_on_data) +display_off_list = bytearray(display_off_data) +invalid_list = bytearray(invalid_data) + + +lcd.lcd_init(init_list, 240,240,13000,1,4,0,invalid_list,display_on_list,display_off_list,None) + +Color_buffer =(0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f, 0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00,0x1f,0x00, 0x1f) + +Color_buffer = bytearray(Color_buffer) + +lcd.lcd_write(Color_buffer,10,10,20,20) +lcd.lcd_clear(0xf800) # 红色 + +lcd.lcd_show("lcd_test.bin",0,0) #该lcd_test.bin 中包含图像头数据 +lcd.lcd_show("lcd_test1.bin",0,0,126,220) #该lcd_test1.bin 中没有包含图像头数据 +``` diff --git a/docs/API_reference/zh/peripherals/machine.OneWire.md b/docs/API_reference/zh/peripherals/machine.OneWire.md new file mode 100644 index 0000000000000000000000000000000000000000..0246fcb3e0c800fc9abd9af21438372498ee65e8 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.OneWire.md @@ -0,0 +1,87 @@ +# class OneWire – 单总线 + +该类提供单总线通信功能。该功能目前仅EC200U/EC600U/EG912U/EG915U系列支持。 + +## 构造函数 + +### `machine.OneWire` + +```python +class machine.OneWire(GPIO) +``` + +**参数描述:** + +- `GPIO` - 使用的gpio,int类型。 + + +**示例:** + +```python +from machine import OneWire +obj=OneWire(OneWire.GPIO19)# 创建单总线对象,使用GPIO19 +``` + +## 方法 + +### `OneWire.reset` + +```python +OneWire.reset() +``` + +该方法用于复位总线并检测设备是否响应,使用时需要先调用该接口,再调用读写接口。 + +**返回值描述:** + +返回整型值`0`表示正确响应,返回整型值`-1`表示没有响应。 + +### `OneWire.read` + +```python +OneWire.read(len) +``` + +该方法用于读取数据。 + +**参数描述:** + +- `len` - 读取数据的长度,int类型。 + +**返回值描述:** + +返回读取到的bytes对象。 + +### `OneWire.write` + +```python +OneWire.write(data) +``` + +该方法用于写入数据。 + +**参数描述:** + +- `data` - 写入的数据,bytes类型。 + +**返回值描述:** + +返回整型值`0`。 + +**使用示例:**读取DS18B20数据 + +> 需要配合DS18B20使用! + +```python +from machine import OneWire + +obj=OneWire(OneWire.GPIO19) +data1=bytearray([0xcc,0x44]) +data2=bytearray([0xcc,0xbe]) + +obj.reset()#先进行总线复位、检测从设备是否响应,再进行读写 +obj.write(data1) +obj.reset() +obj.write(data2) +obj.read(2)#读取的为DS18B20原始数据,需按照DS18B20的数据格式换算成实际温度 +``` diff --git a/docs/API_reference/zh/peripherals/machine.Pin.md b/docs/API_reference/zh/peripherals/machine.Pin.md new file mode 100644 index 0000000000000000000000000000000000000000..e486ea9dc164c08b138abf39ce5f7aa9f5f7b167 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.Pin.md @@ -0,0 +1,8443 @@ +# class Pin - 控制I/O引脚 + +该类提供GPIO读写操作。引脚是控制I/O的基本对象,它有设置引脚的模式(输入,输出等)、获取和设置数字逻辑电平的方法。 + +**示例:** + +```python +from machine import Pin + +# 创建gpio对象 +gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 1) + +# 获取引脚电平 +gpio1.read() + +# 设置引脚电平 +gpio1.write(0) +gpio1.write(1) + +# 设置输入输出模式 +gpio1.set_dir(Pin.IN) +gpio1.set_dir(Pin.OUT) + +# 获取输入输出模式 +gpio1.get_dir() +``` + +## 构造函数 + +### `machine.Pin` + +```python +class machine.Pin(GPIOn, direction, pullMode, level) +``` + +**参数描述:** + +- `GPIOn` - GPIO号,int类型,点此查看 GPIO引脚编号与物理引脚的映射关系。 +- `direction` - 输入输出模式,int类型,`IN` - 输入模式,`OUT` - 输出模式。 +- `pullMode` - 上下拉模式,int类型,说明如下:
PULL_DISABLE - 浮空模式
PULL_PU - 上拉模式
PULL_PD - 下拉模式 +- `level` - 引脚电平,int类型,`0` - 设置引脚为低电平, `1`- 设置引脚为高电平。 + +**示例:** + +```python +>>> # 创建gpio对象 +>>> from machine import Pin +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +``` + +**GPIO引脚编号与物理引脚的映射关系:** + +> GPIO对应引脚号说明:文档中提供的GPIO引脚号对应的为模块外部的引脚编号,例如EC600MCN下GPIO1对应引脚号10,这里的引脚号10为模块外部的引脚编号。可参考提供的硬件资料查看模块外部的引脚编号。 + +**平台引脚对应关系:** +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号10
GPIO2引脚号11
GPIO3引脚号12
GPIO4引脚号13
GPIO5引脚号14
GPIO6引脚号15
GPIO7引脚号16
GPIO8引脚号39
GPIO9引脚号40
GPIO10引脚号48
GPIO11引脚号58
GPIO12引脚号59
GPIO13引脚号60
GPIO14引脚号61
GPIO15引脚号62
GPIO16引脚号63
GPIO17引脚号69
GPIO18引脚号70
GPIO19引脚号1
GPIO20引脚号3
GPIO21引脚号49
GPIO22引脚号50
GPIO23引脚号51
GPIO24引脚号52
GPIO25引脚号53
GPIO26引脚号54
GPIO27引脚号55
GPIO28引脚号56
GPIO29引脚号57
GPIO30引脚号2
GPIO31引脚号66
GPIO32引脚号65
GPIO33引脚号67
GPIO34引脚号64
GPIO35引脚号4
GPIO36引脚号31
GPIO37引脚号32
GPIO38引脚号33
GPIO39引脚号34
GPIO40引脚号71
GPIO41引脚号72
GPIO42引脚号109
GPIO43引脚号110
GPIO44引脚号112
GPIO45引脚号111
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4
GPIO2引脚号5
GPIO3引脚号6
GPIO4引脚号7
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号25
GPIO8引脚号26
GPIO9引脚号42
GPIO10引脚号1
GPIO11引脚号40
GPIO12引脚号41
GPIO13引脚号64
GPIO14引脚号65
GPIO15引脚号66
GPIO16引脚号86
GPIO17引脚号20
GPIO18引脚号21
GPIO19引脚号34
GPIO20引脚号35
GPIO21引脚号36
GPIO22引脚号37
GPIO23引脚号38
GPIO24引脚号39
GPIO25引脚号98
GPIO26引脚号85
GPIO27引脚号87
GPIO28引脚号88
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号61(不可与GPIO31同时为gpio)
GPIO2引脚号58(不可与GPIO32同时为gpio)
GPIO3引脚号34(不可与GPIO41同时为gpio)
GPIO4引脚号60(不可与GPIO34同时为gpio)
GPIO5引脚号69(不可与GPIO35同时为gpio)
GPIO6引脚号70(不可与GPIO36同时为gpio)
GPIO7引脚号123(不可与GPIO43同时为gpio)
GPIO8引脚号118
GPIO9引脚号9(不可与GPIO47同时为gpio)
GPIO10引脚号1(不可与GPIO37同时为gpio)
GPIO11引脚号4(不可与GPIO38同时为gpio)
GPIO12引脚号3(不可与GPIO39同时为gpio)
GPIO13引脚号2(不可与GPIO40同时为gpio)
GPIO14引脚号54
GPIO15引脚号57
GPIO16引脚号56
GPIO17引脚号12
GPIO18引脚号33(不可与GPIO42同时为gpio)
GPIO19引脚号124(不可与GPIO44同时为gpio)
GPIO20引脚号122(不可与GPIO45同时为gpio)
GPIO21引脚号121(不可与GPIO46同时为gpio)
GPIO22引脚号48
GPIO23引脚号39
GPIO24引脚号40
GPIO25引脚号49
GPIO26引脚号50
GPIO27引脚号53
GPIO28引脚号52
GPIO29引脚号51
GPIO30引脚号59(不可与GPIO33同时为gpio)
GPIO31引脚号66(不可与GPIO1同时为gpio)
GPIO32引脚号63(不可与GPIO2同时为gpio)
GPIO33引脚号67(不可与GPIO30同时为gpio)
GPIO34引脚号65(不可与GPIO4同时为gpio)
GPIO35引脚号137(不可与GPIO5同时为gpio)
GPIO36引脚号62(不可与GPIO6同时为gpio)
GPIO37引脚号98(不可与GPIO10同时为gpio)
GPIO38引脚号95(不可与GPIO11同时为gpio)
GPIO39引脚号119(不可与GPIO12同时为gpio)
GPIO40引脚号100(不可与GPIO13同时为gpio)
GPIO41引脚号120(不可与GPIO3同时为gpio)
GPIO42引脚号16(不可与GPIO18同时为gpio)
GPIO43引脚号10(不可与GPIO7同时为gpio)
GPIO44引脚号14(不可与GPIO19同时为gpio)
GPIO45引脚号15(不可与GPIO20同时为gpio)
GPIO46引脚号13(不可与GPIO21同时为gpio)
GPIO47引脚号99(不可与GPIO9同时为gpio)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号27(不可与GPIO31同时为gpio)
GPIO2引脚号26(不可与GPIO32同时为gpio)
GPIO3引脚号24(不可与GPIO33同时为gpio)
GPIO4引脚号25(不可与GPIO34同时为gpio)
GPIO5引脚号13(不可与GPIO17同时为gpio)
GPIO6引脚号135(不可与GPIO36同时为gpio)
GPIO7引脚号136(不可与GPIO44同时为gpio)
GPIO8引脚号133
GPIO9引脚号3(不可与GPIO37同时为gpio)
GPIO10引脚号40(不可与GPIO38同时为gpio)
GPIO11引脚号37(不可与GPIO39同时为gpio)
GPIO12引脚号38(不可与GPIO40同时为gpio)
GPIO13引脚号39(不可与GPIO41同时为gpio)
GPIO14引脚号5
GPIO15引脚号141
GPIO16引脚号142
GPIO17引脚号121(不可与GPIO5同时为gpio)
GPIO18引脚号65(不可与GPIO42同时为gpio)
GPIO19引脚号64(不可与GPIO43同时为gpio)
GPIO20引脚号139(不可与GPIO45同时为gpio)
GPIO21引脚号126(不可与GPIO46同时为gpio)
GPIO22引脚号127(不可与GPIO47同时为gpio)
GPIO23引脚号33
GPIO24引脚号31
GPIO25引脚号30
GPIO26引脚号29
GPIO27引脚号28
GPIO28引脚号1
GPIO29引脚号2
GPIO30引脚号4
GPIO31引脚号125(不可与GPIO1同时为gpio)
GPIO32引脚号124(不可与GPIO2同时为gpio)
GPIO33引脚号123(不可与GPIO3同时为gpio)
GPIO34引脚号122(不可与GPIO4同时为gpio)
GPIO35引脚号42
GPIO36引脚号119(不可与GPIO6同时为gpio)
GPIO37引脚号134(不可与GPIO9同时为gpio)
GPIO38引脚号132(不可与GPIO10同时为gpio)
GPIO39引脚号131(不可与GPIO11同时为gpio)
GPIO40引脚号130(不可与GPIO12同时为gpio)
GPIO41引脚号129(不可与GPIO13同时为gpio)
GPIO42引脚号61(不可与GPIO18同时为gpio)
GPIO43引脚号62(不可与GPIO19同时为gpio)
GPIO44引脚号63(不可与GPIO7同时为gpio)
GPIO45引脚号66(不可与GPIO20同时为gpio)
GPIO46引脚号6(不可与GPIO21同时为gpio)
GPIO47引脚号23(不可与GPIO22同时为gpio)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号27
GPIO2引脚号26
GPIO3引脚号24
GPIO4引脚号25
GPIO5引脚号5
GPIO6引脚号135
GPIO7引脚号136
GPIO8引脚号68
GPIO9引脚号3
GPIO10引脚号40
GPIO11引脚号37
GPIO12引脚号38
GPIO13引脚号39
GPIO14引脚号67
GPIO15引脚号13
GPIO18引脚号65
GPIO19引脚号64
GPIO20引脚号139
GPIO22引脚号127
GPIO27引脚号28
GPIO28引脚号1
GPIO29引脚号2
GPIO30引脚号4
GPIO35引脚号42
GPIO36引脚号119
GPIO43引脚号62
GPIO44引脚号63(EC200ACN_LA不支持)
GPIO45引脚号66
GPIO46引脚号6
GPIO47引脚号23
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号27
GPIO2引脚号26
GPIO3引脚号24
GPIO4引脚号25
GPIO5引脚号5
GPIO6引脚号135
GPIO7引脚号136
GPIO8引脚号68
GPIO9引脚号3
GPIO10引脚号40
GPIO11引脚号37
GPIO12引脚号38
GPIO13引脚号39
GPIO14引脚号67
GPIO15引脚号13
GPIO18引脚号65
GPIO19引脚号64
GPIO20引脚号139
GPIO22引脚号127
GPIO27引脚号28
GPIO28引脚号1
GPIO29引脚号2
GPIO30引脚号4
GPIO35引脚号42
GPIO43引脚号62
GPIO44引脚号63
GPIO45引脚号66
GPIO46引脚号6
GPIO47引脚号23
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号56
GPIO13引脚号57
GPIO14引脚号58
GPIO15引脚号80
GPIO16引脚号81
GPIO17引脚号76
GPIO18引脚号77
GPIO19引脚号82
GPIO20引脚号83
GPIO21引脚号86
GPIO22引脚号87
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO27引脚号19
GPIO28引脚号20
GPIO29引脚号21
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO36引脚号16
GPIO37引脚号78
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号3
GPIO2引脚号4
GPIO3引脚号5
GPIO4引脚号6
GPIO5引脚号16
GPIO6引脚号20
GPIO7引脚号21
GPIO8引脚号22
GPIO9引脚号23
GPIO10引脚号25
GPIO11引脚号28
GPIO12引脚号29
GPIO13引脚号30
GPIO14引脚号31
GPIO15引脚号32
GPIO16引脚号33
GPIO17引脚号2
GPIO18引脚号8
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4
GPIO2引脚号5
GPIO3引脚号6
GPIO4引脚号7
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号22
GPIO8引脚号23
GPIO9引脚号25
GPIO10引脚号26
GPIO11引脚号27
GPIO12引脚号28
GPIO13引脚号40
GPIO14引脚号41
GPIO15引脚号64
GPIO16引脚号65
GPIO17引脚号66
GPIO18引脚号85
GPIO19引脚号86
GPIO20引脚号87
GPIO21引脚号88
GPIO22引脚号20
GPIO23引脚号21
GPIO24引脚号30
GPIO25引脚号34
GPIO26引脚号35
GPIO27引脚号36
GPIO28引脚号37
GPIO29引脚号38
GPIO30引脚号39
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4(不可与GPIO41同时为gpio)
GPIO2引脚号5(不可与GPIO36同时为gpio)
GPIO3引脚号6(不可与GPIO35同时为gpio)
GPIO4引脚号7(不可与GPIO24同时为gpio)
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号1(不可与GPIO37同时为gpio)
GPIO8引脚号38
GPIO9引脚号25
GPIO10引脚号26
GPIO11引脚号27(不可与GPIO32同时为gpio)
GPIO12引脚号28(不可与GPIO31同时为gpio)
GPIO13引脚号40
GPIO14引脚号41
GPIO15引脚号64
GPIO16引脚号20(不可与GPIO30同时为gpio)
GPIO17引脚号21
GPIO18引脚号85(使用双卡单待功能是不可复用)
GPIO19引脚号86(使用双卡单待功能是不可复用)
GPIO20引脚号30
GPIO21引脚号88
GPIO22引脚号36(不可与GPIO40同时为gpio)
GPIO23引脚号37(不可与GPIO38同时为gpio)
GPIO24引脚号16(不可与GPIO4同时为gpio)
GPIO25引脚号39
GPIO26引脚号42(不可与GPIO27同时为gpio)
GPIO27引脚号78(不可与GPIO26同时为gpio)
GPIO28引脚号83(不可与GPIO33同时为gpio)
GPIO29引脚号84(使用双卡单待功能时不可复用)
GPIO30引脚号92(不可与GPIO16同时为gpio)
GPIO31引脚号95(不可与GPIO12同时为gpio)
GPIO32引脚号97(不可与GPIO11同时为gpio)
GPIO33引脚号98(不可与GPIO28同时为gpio)
GPIO34引脚号104
GPIO35引脚号105(不可与GPIO3同时为gpio)
GPIO36引脚号106(不可与GPIO2同时为gpio)
GPIO37引脚号108(不可与GPIO4同时为gpio)
GPIO38引脚号111(不可与GPIO23同时为gpio)
GPIO39引脚号114
GPIO40引脚号115(不可与GPIO22同时为gpio)
GPIO41引脚号116(不可与GPIO1同时为gpio)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号56
GPIO13引脚号57
GPIO14引脚号58
GPIO15引脚号80
GPIO16引脚号81
GPIO17引脚号76
GPIO18引脚号77
GPIO19引脚号82
GPIO20引脚号83
GPIO21引脚号86(EG810M_EU不支持)
GPIO22引脚号87(EG810M_EU不支持)
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO27引脚号19
GPIO28引脚号20
GPIO29引脚号21
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO34引脚号38
GPIO35引脚号39
GPIO36引脚号16
GPIO37引脚号78
GPIO38引脚号68
GPIO39引脚号69
GPIO40引脚号74
GPIO41引脚号75
GPIO42引脚号84(EG810M_EU不支持)
GPIO43引脚号85(EG810M_EU不支持)
GPIO44引脚号25
GPIO47引脚号79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4
GPIO2引脚号5
GPIO3引脚号6
GPIO4引脚号7
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号1
GPIO8引脚号16
GPIO9引脚号25
GPIO10引脚号26
GPIO11引脚号27
GPIO12引脚号28
GPIO13引脚号40
GPIO14引脚号41
GPIO15引脚号64
GPIO16引脚号20
GPIO17引脚号21
GPIO18引脚号30
GPIO19引脚号34
GPIO20引脚号35
GPIO21引脚号36
GPIO22引脚号37
GPIO23引脚号38
GPIO24引脚号39
GPIO25引脚号42
GPIO26引脚号78
GPIO27引脚号83
GPIO28引脚号92
GPIO29引脚号95
GPIO30引脚号96
GPIO31引脚号97
GPIO32引脚号98
GPIO33引脚号103
GPIO34引脚号104
GPIO35引脚号105
GPIO36引脚号106
GPIO37引脚号107
GPIO38引脚号114
GPIO39引脚号115
GPIO40引脚号116
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号10(I&PU)
GPIO2引脚号11(57)(I&PU)(不可与GPIO41同时为gpio)
GPIO3引脚号12(56)(I&PU)(不可与GPIO40同时为gpio)
GPIO4引脚号13(I&PU)
GPIO5引脚号14(I&PU)
GPIO6引脚号15(I&PU)
GPIO7引脚号16(I&PU)
GPIO8引脚号39(I&PD)
GPIO9引脚号40(I&PU)
GPIO10引脚号48(I&PD)
GPIO11引脚号58(I&PD)
GPIO12引脚号59(I&PD)
GPIO13引脚号60(I&PD)(不可与GPIO36同时为gpio)
GPIO14引脚号61(I&PD)
GPIO15引脚号62(I&PU)(EC600ECN_LE&LQ不可用)
GPIO16引脚号63(I&PD)(EC600ECN_LE&LQ不可用)
GPIO17引脚号69(I&PU)(EC600ECN_LE&LQ不可用)
GPIO18引脚号70(I&PU)(EC600ECN_LE&LQ不可用)
GPIO22引脚号50(I&PD)
GPIO23引脚号51(I&PD)
GPIO24引脚号52(I&PD)
GPIO25引脚号53(I&PD)
GPIO26引脚号54(I&PD)
GPIO31引脚号66(I&PU)(EC600ECN_LE&LQ不可用)
GPIO32引脚号65(I&PU)(EC600ECN_LE&LQ不可用)
GPIO33引脚号67(I&PU)(EC600ECN_LE&LQ不可用)
GPIO34引脚号64(I&PU)(EC600ECN_LE&LQ不可用)
GPIO36引脚号31(I&PU)(不可与GPIO13同时为gpio)
GPIO37引脚号32(I&PU)
GPIO38引脚号33(I&PU)
GPIO39引脚号34(I&PU)
GPIO40引脚号71(I&PU)(不可与GPIO3同时为gpio)
GPIO41引脚号72(I&PU)(不可与GPIO2同时为gpio)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30(I&PD)
GPIO2引脚号31(I&PD)
GPIO3引脚号32(I&PD)
GPIO4引脚号33(I&PD)(不可与GPIO25同时为gpio)
GPIO5引脚号49(I&PD)(EC800ECN_LE&LQ&CG不可用)
GPIO6引脚号50(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO7引脚号51(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO8引脚号52(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO9引脚号53(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO10引脚号54(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO11引脚号55(I&PU)(EC800ECN_LE&LQ&CG不可用,不可与64脚同时使用)
GPIO12引脚号56(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO13引脚号57(67)(I&PU)(EC800ECN_LE&LQ&CG引脚号57无法使用)(不可与GPIO34同时为gpio)
GPIO14引脚号58(66)(I&PU)(EC800ECN_LE&LQ&CG引脚号58无法使用)(不可与GPIO35同时为gpio)
GPIO15引脚号80(I&PU)(EC800ECN_LE&LQ&CG不可用,不可与63脚同时使用)
GPIO16引脚号81(I&PU)(EC800ECN_LE&LQ&CG不可用,不可与62脚同时使用)
GPIO17引脚号25(I&PD)
GPIO25引脚号17(I&PU)(不可与GPIO4同时为gpio)
GPIO26引脚号18(I&PU)
GPIO27引脚号19(I&PD)
GPIO28引脚号20(I&PU)
GPIO29引脚号21(I&PD)
GPIO30引脚号22(I&PU)
GPIO31引脚号23(I&PU)
GPIO32引脚号28(I&PU)
GPIO33引脚号29(I&PU)
GPIO34引脚号38(I&PU)(不可与GPIO13同时为gpio)
GPIO35引脚号39(I&PU)(不可与GPIO14同时为gpio)
GPIO36引脚号16(I&PD)
GPIO37引脚号78(I&PU)(EC800ECN_LE&LQ&CG不可用)
GPIO38引脚号85(I&PD)(EC800ECN_LE&LQ&LC&CG不可用)
GPIO39引脚号108(I&PD)(EC800ECN_LE&LQ&LC&CG不可用)
GPIO40引脚号109(I&PD)(EC800ECN_LE&LQ&LC&CG不可用)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号56
GPIO13引脚号57
GPIO14引脚号58
GPIO15引脚号80
GPIO16引脚号81
GPIO17引脚号25(AGPIO)
GPIO23引脚号66(不可与GPIO26同时为gpio)
GPIO24引脚号67(不可与GPIO25同时为gpio)
GPIO25引脚号17(不可与GPIO24同时为gpio)
GPIO26引脚号18(不可与GPIO23同时为gpio)
GPIO27引脚号19(AGPIO,驱动能力较弱,建议仅作输入引脚使用)
GPIO28引脚号20(AGPIO)
GPIO29引脚号21(AGPIO)
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO34引脚号38
GPIO35引脚号39
GPIO36引脚号16(AGPIO)
GPIO37引脚号78
GPIO38引脚号85(AGPIO)
GPIO39引脚号108(AGPIO,驱动能力较弱,建议仅作输入引脚使用)
GPIO40引脚号109(AGPIO,驱动能力较弱,建议仅作输入引脚使用)
GPIO41引脚号101
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号61(不可与GPIO24同时为gpio)
GPIO2引脚号58(不可与GPIO25同时为gpio)
GPIO3引脚号34
GPIO4引脚号60
GPIO5引脚号69(不可与GPIO10同时为gpio)
GPIO6引脚号70(不可与GPIO11同时为gpio)
GPIO7引脚号123
GPIO8引脚号132
GPIO9引脚号9
GPIO10引脚号1(不可与GPIO5同时为gpio)
GPIO11引脚号4(不可与GPIO6同时为gpio)
GPIO12引脚号3
GPIO13引脚号2
GPIO14引脚号54
GPIO15引脚号57
GPIO16引脚号56
GPIO17引脚号12
GPIO18引脚号33
GPIO19引脚号124(不可与GPIO37同时为gpio)
GPIO20引脚号104
GPIO21引脚号103
GPIO22引脚号48
GPIO23引脚号39(不可与GPIO46同时为gpio)
GPIO24引脚号40(不可与GPIO1同时为gpio)
GPIO25引脚号49(不可与GPIO2同时为gpio)
GPIO26引脚号50(不可与GPIO30同时为gpio)
GPIO27引脚号53
GPIO28引脚号52
GPIO29引脚号51
GPIO30引脚号59(不可与GPIO26同时为gpio)
GPIO31引脚号66
GPIO32引脚号63
GPIO33引脚号67
GPIO34引脚号65
GPIO35引脚号137
GPIO36引脚号62
GPIO37引脚号105(不可与GPIO19同时为gpio)
GPIO38引脚号106
GPIO39引脚号107
GPIO40引脚号126
GPIO41引脚号120
GPIO42引脚号16
GPIO43引脚号10
GPIO44引脚号14
GPIO45引脚号64
GPIO46引脚号13(不可与GPIO23同时为gpio)
GPIO47引脚号116
GPIO48引脚号31
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30(不可与GPIO45同时为gpio)
GPIO2引脚号31(不可与GPIO46同时为gpio)
GPIO3引脚号32(不可与GPIO47同时为gpio)
GPIO4引脚号33(不可与GPIO48同时为gpio)
GPIO5引脚号49
GPIO6引脚号50(不可与GPIO50同时为gpio)
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号25
GPIO13引脚号57(不可与GPIO49同时为gpio)
GPIO14引脚号58(不可与GPIO20同时为gpio)
GPIO15引脚号84
GPIO16引脚号81
GPIO17引脚号76(不可与GPIO35同时为gpio)
GPIO18引脚号77
GPIO19引脚号82
GPIO20引脚号83(不可与GPIO14同时为gpio)
GPIO21引脚号86(不可与GPIO34同时为gpio)
GPIO22引脚号87
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO27引脚号19
GPIO28引脚号20
GPIO29引脚号21
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO34引脚号38(不可与GPIO21同时为gpio)
GPIO35引脚号39(不可与GPIO17同时为gpio)
GPIO36引脚号16
GPIO37引脚号78
GPIO38引脚号85
GPIO39引脚号68
GPIO40引脚号69
GPIO41引脚号80(不可与GPIO44同时为gpio)
GPIO42引脚号107
GPIO43引脚号103
GPIO44引脚号101(不可与GPIO41同时为gpio)
GPIO45引脚号79(不可与GPIO1同时为gpio)
GPIO46引脚号100(不可与GPIO2同时为gpio)
GPIO47引脚号108(不可与GPIO3同时为gpio)
GPIO48引脚号109(不可与GPIO4同时为gpio)
GPIO49引脚号75(不可与GPIO13同时为gpio)
GPIO50引脚号74(不可与GPIO6同时为gpio)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4(不可与GPIO40同时为GPIO)
GPIO2引脚号5(不可与GPIO36同时为GPIO)
GPIO3引脚号6(不可与GPIO35同时为GPIO)
GPIO4引脚号7(不可与GPIO8同时为GPIO)
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号1(不可与GPIO19同时为GPIO)
GPIO8引脚号16(不可与GPIO4同时为GPIO)
GPIO10引脚号26(EG912UGLAA不支持)
GPIO11引脚号27(不可与GPIO31同时为GPIO)
GPIO12引脚号28(不可与GPIO29同时为GPIO)
GPIO13引脚号40
GPIO14引脚号41
GPIO15引脚号64(EG912UGLAA不支持)
GPIO16引脚号20(不可与GPIO28同时为GPIO)
GPIO17引脚号21
GPIO18引脚号30
GPIO19引脚号108(不可与GPIO7同时为GPIO)
GPIO20引脚号88(EG912UGLAA不支持)
GPIO21引脚号36(不可与GPIO39同时为GPIO)
GPIO22引脚号37(不可与GPIO30同时为GPIO)
GPIO23引脚号38
GPIO24引脚号39
GPIO25引脚号42(不可与GPIO26同时为GPIO)
GPIO26引脚号78(不可与GPIO25同时为GPIO)
GPIO27引脚号83(不可与GPIO32同时为GPIO)
GPIO28引脚号92(不可与GPIO16同时为GPIO)
GPIO29引脚号95(不可与GPIO12同时为GPIO)
GPIO30引脚号111(不可与GPIO22同时为GPIO)
GPIO31引脚号97(不可与GPIO11同时为GPIO)
GPIO32引脚号98(不可与GPIO27同时为GPIO)
GPIO34引脚号104
GPIO35引脚号105(不可与GPIO3同时为GPIO)
GPIO36引脚号106(不可与GPIO2同时为GPIO)
GPIO38引脚号114
GPIO39引脚号115(不可与GPIO21同时为GPIO)
GPIO40引脚号116(不可与GPIO1同时为GPIO)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号10
GPIO2引脚号11
GPIO3引脚号12
GPIO4引脚号13
GPIO5引脚号14
GPIO6引脚号15
GPIO7引脚号16
GPIO8引脚号39
GPIO9引脚号40
GPIO10引脚号48
GPIO11引脚号58
GPIO12引脚号59
GPIO13引脚号60
GPIO14引脚号61
GPIO15引脚号62
GPIO16引脚号63
GPIO17引脚号69
GPIO18引脚号70
GPIO19引脚号1
GPIO20引脚号3
GPIO21引脚号49
GPIO22引脚号50
GPIO23引脚号51
GPIO24引脚号52
GPIO25引脚号53
GPIO26引脚号54
GPIO27引脚号55(boot脚,内部有上拉)
GPIO28引脚号56
GPIO29引脚号57
GPIO30引脚号2
GPIO31引脚号66
GPIO32引脚号65
GPIO33引脚号67
GPIO34引脚号64
GPIO35引脚号4
GPIO36引脚号31
GPIO37引脚号32
GPIO38引脚号33
GPIO39引脚号34
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54(EG800KCN不可用)
GPIO11引脚号55(EG800KCN不可用)
GPIO12引脚号56(EG800KCN不可用)
GPIO13引脚号57(EG800KCN不可用)
GPIO14引脚号58(EG800KCN不可用)
GPIO15引脚号80(EG800KCN不可用)
GPIO16引脚号81
GPIO17引脚号76
GPIO18引脚号77
GPIO19引脚号82
GPIO20引脚号83
GPIO21引脚号86
GPIO22引脚号87
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO27引脚号19
GPIO28引脚号20
GPIO29引脚号21
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28(EG800KCN不可用)
GPIO33引脚号29(EG800KCN不可用)
GPIO36引脚号16
GPIO37引脚号78
GPIO38引脚号68
GPIO39引脚号69
GPIO40引脚号74
GPIO41引脚号75
GPIO44引脚号25
GPIO47引脚号79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号20
GPIO13引脚号19
GPIO14引脚号21
GPIO15引脚号80
GPIO16引脚号81
GPIO17引脚号76
GPIO18引脚号77
GPIO19引脚号82
GPIO20引脚号83
GPIO21引脚号86
GPIO22引脚号87
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO36引脚号16
GPIO37引脚号78
GPIO38引脚号68
GPIO39引脚号69
GPIO40引脚号74
GPIO41引脚号75
GPIO44引脚号25
GPIO47引脚号79
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号30
GPIO2引脚号31
GPIO3引脚号32
GPIO4引脚号33
GPIO5引脚号49
GPIO6引脚号50
GPIO7引脚号51
GPIO8引脚号52
GPIO9引脚号53
GPIO10引脚号54
GPIO11引脚号55
GPIO12引脚号56
GPIO15引脚号80
GPIO16引脚号81
GPIO17引脚号25(AGPIO的状态不受睡眠模式的影响)
GPIO23引脚号66
GPIO24引脚号67
GPIO25引脚号17
GPIO26引脚号18
GPIO27引脚号19
GPIO28引脚号20(AGPIO的状态不受睡眠模式的影响)
GPIO30引脚号22
GPIO31引脚号23
GPIO32引脚号28
GPIO33引脚号29
GPIO34引脚号38
GPIO35引脚号39
GPIO36引脚号16(AGPIO的状态不受睡眠模式的影响)
GPIO37引脚号78
GPIO38引脚号6(AGPIOWU可作为WAKEUP和AGPIO类型)
GPIO39引脚号5(AGPIOWU可作为WAKEUP和AGPIO类型)
GPIO40引脚号100(AGPIO的状态不受睡眠模式的影响)
GPIO41引脚号101(AGPIO的状态不受睡眠模式的影响)
GPIO42引脚号26
GPIO43引脚号64
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
引脚号
引脚号6
引脚号7
引脚号8
引脚号9
引脚号10
引脚号12
引脚号13
引脚号14
引脚号15
引脚号16
引脚号19
引脚号20
引脚号21
引脚号22
引脚号23
引脚号29
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
引脚号
引脚号6
引脚号7
引脚号8
引脚号9
引脚号14
引脚号15
引脚号16
引脚号27
引脚号28
引脚号29
引脚号30
引脚号31
引脚号34
引脚号35
引脚号37
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号12
GPIO2引脚号13
GPIO3引脚号41
GPIO4引脚号42
GPIO5引脚号21
GPIO6引脚号22
GPIO7引脚号23
GPIO8引脚号24
GPIO9引脚号26
GPIO10引脚号43
GPIO11引脚号44
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号12
GPIO2引脚号13
GPIO3引脚号41
GPIO4引脚号42
GPIO5引脚号21
GPIO6引脚号22
GPIO7引脚号23
GPIO8引脚号24
GPIO9引脚号26
GPIO10引脚号43
GPIO11引脚号44
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO号引脚号
GPIO1引脚号4
GPIO2引脚号5
GPIO3引脚号6
GPIO4引脚号7
GPIO5引脚号18
GPIO6引脚号19
GPIO7引脚号1
GPIO8引脚号38
GPIO9引脚号25
GPIO10引脚号26
GPIO11引脚号27
GPIO12引脚号28
GPIO13引脚号40
GPIO14引脚号41
GPIO15引脚号64
GPIO16引脚号20
GPIO17引脚号21
GPIO18引脚号34
GPIO19引脚号35
GPIO20引脚号30
GPIO21引脚号22
GPIO22引脚号36
GPIO23引脚号37
GPIO24引脚号16
GPIO25引脚号39
GPIO26引脚号23
GPIO27引脚号78
GPIO28引脚号83
GPIO29引脚号107
GPIO30引脚号92
GPIO31引脚号95
GPIO32引脚号97
GPIO33引脚号98
GPIO34引脚号104
GPIO35引脚号105
GPIO36引脚号106
GPIO37引脚号103
GPIO38引脚号96
GPIO39引脚号114
GPIO40引脚号115
GPIO41引脚号116
+
+ +
+
+
+
+

注:

+

1.I&PU:输入模式下,仅支持浮空和上拉模式

+

2.I&PD:输入模式下,仅支持浮空和下拉模式

+

3.EC600E的ExtInt功能不支持上升和下降沿同时触发中断

+
+
+ +
+
+

注:

+

1.I&PU:输入模式下,仅支持浮空和上拉模式

+

2.I&PD:输入模式下,仅支持浮空和下拉模式

+

3.EC800ECN_LE&LQ&CG不可用:指该型号模块的引脚内部悬空,所以无法使用

+

4.模组的Pin67、Pin66 和Pin57、Pin58 共用内部同一路IO,即改变GPIO13的电平,Pin57和Pin67会同时变化

+

5.在EC800ECN_LE&LQ&CG型号的模组上,Pin57、Pin58内部悬空,所以仅可使用Pin67、Pin66作为GPIO13、14

+

6.EC800E的ExtInt功能不支持上升和下降沿同时触发中断

+

7.Pin55、80、81分别不可与Pin64、63、62(SIM2管脚)同时使用

+
+
+ +
+
+

注:

+

1.AGPIO在睡眠模式状态下,电平状态保持不变,普通GPIO在睡眠状态下电平不能保持

+

2.GPIO27、GPIO39、GPIO40驱动能力较弱,建议仅做输入引脚使用

+
+
+ +
+
+

注:

+

1.AGPIO在睡眠模式状态下,电平状态保持不变,普通GPIO在睡眠状态下电平不能保持

+

2.GPIO38、GPIO49驱动能力较弱,建议仅做输入引脚使用

+
+
+ +
+
+

注:

+

1.Pin37-GPIO11,Pin38-GPIO12,Pin39-GPIO13,支持GNSS的模块不会启用此引脚的复用功能,因此该引脚需要保持处于断开状态。

+

2.Pin1、Pin2、Pin4在使用(U)SIM2功能时,不能再作为GPIO使用。

+
+
+ +
+
+

注:

+

1.GPIO27-Pin53、GPIO28-Pin52、GPIO29-Pin51与Pin145~Pin147有硬件冲突。如使用(U)SIM2接口的Pin145~Pin147引脚,则引脚Pin51~Pin53不能用作GPIO。

+
+
+ +
+ +## 方法 + +### `Pin.read` + +```python +Pin.read() +``` + +该方法用于读取PIN脚电平。 + +**返回值描述:** + +返回引脚电平,`0`表示获取到的引脚电平为低电平,`1` 表示获取到的引脚电平为高电平。 + +### `Pin.write` + +``` +Pin.write(value) +``` + +该方法用于设置PIN脚电平。 + +> 设置高低电平前需要保证引脚为输出模式。 + +**参数描述:** + +- `value` - 引脚电平,int类型,`0`表示设置当前PIN脚输出低电平,`1`表示设置当前PIN脚输出高电平。 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1`。 + +**示例:** + +```python +>>> from machine import Pin +#GPIO输出模式 设置引脚电平 +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +>>> gpio1.write(1) +0 +#GPIO输入模式 读取引脚电平 +>>> gpio1 = Pin(Pin.GPIO1, Pin.IN, Pin.PULL_DISABLE, 0) +>>> gpio1.read() +0 +``` + +### `Pin.set_dir` + +```python +Pin.set_dir(value) +``` + +该方法用于设置PIN脚GPIO的输入输出模式。 + +**参数描述:** + +- `value` - 引脚电平,int类型,说明如下:
Pin.IN : `0` - 输入模式
Pin.OUT : `1` - 输出模式 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1`。 + +### `Pin.get_dir` + +```python +Pin.get_dir() +``` + +该方法用于获取PIN脚GPIO的输入输出模式。 + +**返回值描述:** + +返回PIN脚输入输出模式,`0`表示输入模式,`1` 表示输出模式。 + +**示例:** + +```python +>>> from machine import Pin +>>> gpio1 = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) +>>> gpio1.get_dir() +1 +>>> gpio1.set_dir(Pin.IN) +0 +>>> gpio1.get_dir() +0 +``` + +## 常量 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO22GPIO22
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO22GPIO22
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO35GPIO35
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.GPIO48GPIO48
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.GPIO44GPIO44
Pin.GPIO45GPIO45
Pin.GPIO46GPIO46
Pin.GPIO47GPIO47
Pin.GPIO48GPIO48
Pin.GPIO49GPIO49
Pin.GPIO50GPIO50
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO44GPIO44
Pin.GPIO47GPIO47
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.GPIO42GPIO42
Pin.GPIO43GPIO43
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
Pin.GPIO1GPIO1
Pin.GPIO2GPIO2
Pin.GPIO3GPIO3
Pin.GPIO4GPIO4
Pin.GPIO5GPIO5
Pin.GPIO6GPIO6
Pin.GPIO7GPIO7
Pin.GPIO8GPIO8
Pin.GPIO9GPIO9
Pin.GPIO10GPIO10
Pin.GPIO11GPIO11
Pin.GPIO12GPIO12
Pin.GPIO13GPIO13
Pin.GPIO14GPIO14
Pin.GPIO15GPIO15
Pin.GPIO16GPIO16
Pin.GPIO17GPIO17
Pin.GPIO18GPIO18
Pin.GPIO19GPIO19
Pin.GPIO20GPIO20
Pin.GPIO21GPIO21
Pin.GPIO22GPIO22
Pin.GPIO23GPIO23
Pin.GPIO24GPIO24
Pin.GPIO25GPIO25
Pin.GPIO26GPIO26
Pin.GPIO27GPIO27
Pin.GPIO28GPIO28
Pin.GPIO29GPIO29
Pin.GPIO30GPIO30
Pin.GPIO31GPIO31
Pin.GPIO32GPIO32
Pin.GPIO33GPIO33
Pin.GPIO34GPIO34
Pin.GPIO35GPIO35
Pin.GPIO36GPIO36
Pin.GPIO37GPIO37
Pin.GPIO38GPIO38
Pin.GPIO39GPIO39
Pin.GPIO40GPIO40
Pin.GPIO41GPIO41
Pin.IN输入模式
Pin.OUT输出模式
Pin.PULL_DISABLE浮空模式
Pin.PULL_PU上拉模式
Pin.PULL_PD下拉模式
+
+ diff --git a/docs/API_reference/zh/peripherals/machine.RTC.md b/docs/API_reference/zh/peripherals/machine.RTC.md new file mode 100644 index 0000000000000000000000000000000000000000..fe7a235418a9b27c973d196e21a36641411d9c54 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.RTC.md @@ -0,0 +1,147 @@ +# class RTC – 实时时钟 + +该类提供获取设置rtc时间方法,对于BC25PA平台起到从深休眠或者软件关机状态唤醒模组的功能。 + +## 构造函数 + +### `machine.RTC` + +```python +class machine.RTC() +``` + +**示例:** + +```python +>>> # 创建RTC对象 +>>> from machine import RTC +>>> rtc = RTC() +``` + +## 方法 + +### `rtc.datetime` + +```python +rtc.datetime([year, month, day, week, hour, minute, second, microsecond]) +``` + +该方法用于设置或获取RTC时间。不带参数时,用于获取时间,带参数则是设置时间;设置时间时,参数week不参与设置,microsecond参数保留,暂未使用,默认是0。 + +**参数描述:** + +- `year` - 年,int类型。 +- `month` - 月,int类型,范围[1 ~ 12]。 +- `day` - 日,int类型,范围[1 ~ 31]。 +- `week` - 星期,int类型,范围[0 ~ 6],其中0表示周日,[1 ~ 6]分别表示周一到周六;设置时间时,该参数不起作用,保留;获取时间时该参数有效。 +- `hour` - 时,int类型,范围[0 ~ 23]。 +- `minute` - 分,int类型,范围[0 ~ 59]。 +- `second` - 秒,int类型,范围[0 ~ 59]。 +- `microsecond` - 微秒,int类型,保留参数,暂未使用,设置时间时该参数写0即可。 + +**返回值描述:** + +获取时间时,返回一个元组,包含日期时间,格式如下:
`[year, month, day, week, hour, minute, second, microsecond]` + +设置时间时,设置成功返回整型值`0`,设置失败返回整型值`-1` 。 + +**示例:** + +```python +>>> from machine import RTC +>>> rtc = RTC() +>>> rtc.datetime() +(2020, 9, 11, 5, 15, 43, 23, 0) +>>> rtc.datetime([2020, 3, 12, 1, 12, 12, 12, 0]) +0 +>>> rtc.datetime() +(2020, 3, 12, 4, 12, 12, 14, 0) + +``` + +### `rtc.set_alarm` + +```python +rtc.set_alarm(data_e) +``` + +该方法用于设置RTC到期时间,时间到期就会调用注册的回调函数。 + +**参数描述:** + +- `year` - 年,int类型。 +- `month` - 月,int类型,范围[1 ~ 12]。 +- `day` - 日,int类型,范围[1 ~ 31]。 +- `week` - 星期,int类型,范围[0 ~ 6],其中0表示周日,[1 ~ 6]分别表示周一到周六;设置时间时,该参数不起作用,保留;获取时间时该参数有效。 +- `hour` - 时,int类型,范围[0 ~ 23]。 +- `minute` - 分,int类型,范围[0 ~ 59]。 +- `second` - 秒,int类型,范围[0 ~ 59]。 +- `microsecond` - 微秒,int类型,保留参数,暂未使用,设置时间时该参数写0即可。 + +**返回值描述:** + +设置成功返回整型值`0`,设置失败返回整型值`-1` 。 + +> 该方法支持平台EC600U/EC200U/EC600N/EC800N/BC25。 + +**示例:** + +```python +>>> data_e=rtc.datetime() +>>> data_l=list(data_e) +>>> data_l[6] +=30 +>>> data_e=tuple(data_l) +>>> rtc.set_alarm(data_e) +0 +``` + +### `rtc.register_callback` + +```python +rtc.register_callback(callback) +``` + +该方法用于注册RTC alarm回调处理函数。 + +**参数描述:** + +- `callback` - RTC alarm回调处理函数,function类型,原型为callback(arg),`arg`未实际使用,可直接传入`None`。 + +**返回值描述:** + +注册成功返回整型值`0`,注册失败返回整型值`-1` 。 + +> 该方法支持平台EC600U/EC200U/EC600N/EC800N/BC25。 + +### `rtc.enable_alarm` + +```python +rtc.enable_alarm(on_off) +``` + +该方法用于打开/关闭RTC alarm功能。 + +**参数描述:** + +- `on_off` - `1`表示打开RTC alarm功能,`0`表示关闭RTC alarm功能,int类型。 + +**返回值描述:** + +打开/关闭成功返回整型值`0`,打开/关闭失败返回整型值`-1` 。 + +> 该方法支持平台EC600U/EC200U/EC600N/EC800N/BC25,BC25PA平台只有设置回调函数,才能启动定时器。 + +**示例:** + +```python +from machine import RTC +rtc = RTC() +def callback(args): + print('RTC alarm') + +rtc.register_callback(callback) +rtc.set_alarm([2021, 7, 9, 5, 12, 30, 0, 0]) +rtc.enable_alarm(1) +``` + +> EC600U/EC200U平台支持自动开机,即设置alarm功能之后将模块关机,alarm时间到了之后可以自动开机。其他平台不支持该特性。 diff --git a/docs/API_reference/zh/peripherals/machine.SPI.md b/docs/API_reference/zh/peripherals/machine.SPI.md new file mode 100644 index 0000000000000000000000000000000000000000..63383ea48f17cacf2421941edde9eb58f6129344 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.SPI.md @@ -0,0 +1,1141 @@ +# class SPI – SPI通信 + +该类提供串行外设接口总线协议功能。 + +## 构造函数 + +### `machine.SPI` + +
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz
    526MHz
    652MHz

    +
  • +

    52MHz时钟频率对硬件要求较高。

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0960kHz
    14.8MHz
    29.6MHz
    316MHz
    419.2MHz
    525MHz
    650MHz

    +
  • +

    50MHz时钟频率对硬件要求较高。

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0100KHz
    1200KHz
    2300KHz
    3400KHz
    4500KHz
    5600KHz
    6700KHz
    7812.5KHz
    81.625MHz
    93.25MHz
    106.5MHz
    1113MHz
    1226MHz
    1352MHz

    +
  • +

    52MHz时钟频率对硬件要求较高。

    +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz

    +
  • +
  • [group] - 选择在不同管脚使用spi,缺省值为0。
    1该组管脚不支持挂载 nor flash

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0812.5kHz
    11.625MHz
    23.25MHz
    36.5MHz
    413MHz

    +
  • +
  • [group] - 选择在不同管脚使用spi,缺省值为0。
    0缺省值
    1不支持挂载 nor flash

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0781.25KHz
    11.5625MHz
    23.125MHz
    35MHz
    46.25MHz
    510MHz
    612.5MHz
    720MHz
    825MHz
    933.33MHz

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0781.25KHz
    XXMHz (X in [1,39])

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    097.656kHz
    1100kHz
    2812.5kHz
    31.3MHz
    41.625MHz
    52MHz
    63.25MHz
    74.333MHz
    86.6MHz
    911.93MHz
    1013MHz
    1113.92MHz
    1216.7MHz
    1320.875MHz
    1427.83MHz

    +
  • +
+
+ +
+
class machine.SPI(spi, mode, clk, [group])
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0500kHz
    11MHz
    25MHz
    310MHz
    420MHz

    +
  • +
+
+ + +
+
class machine.SPI(spi, mode, clk)
+
+

参数描述:

+
    +
  • spi - 通道选择[0,1],int类型。

    +
  • +
  • mode - SPI 的工作模式,int类型,说明如下:
    时钟极性CPOL:即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平)
    0CPOL=0, CPHA=0
    1CPOL=0, CPHA=1
    2CPOL=1, CPHA=0
    3CPOL=1, CPHA=1

    +
  • +
  • clk - 时钟频率,说明如下:
    0500kHz
    1~30(1~30)*1MHz

    +
  • +
+
+ +
+ + +**示例:** + +```python +>>> from machine import SPI +>>> # 创建SPI对象 +>>> spi_obj = SPI(1, 0, 1) +``` + + +**SPI引脚对应关系:** + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚4引脚1引脚3引脚2
spi1引脚58引脚61引脚59引脚60
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚134引脚133引脚132引脚131
spi1引脚26引脚27引脚24引脚25
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚31引脚30引脚32引脚33
spi1引脚52引脚53引脚50引脚51
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚6引脚5引脚4引脚3
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚25引脚26引脚27引脚28
spi1引脚41引脚40引脚64引脚65
spi2引脚19引脚18引脚23引脚22
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0
group0
引脚58引脚61引脚59引脚60
spi0
group1
引脚4引脚1引脚3引脚2
spi1
group0
引脚4引脚1引脚3引脚2
spi1
group1
引脚65引脚67引脚66引脚63
spi2引脚49引脚54引脚53引脚52
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚25引脚26引脚64引脚88
spi1引脚5引脚4引脚6引脚7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0
group0
引脚31引脚30引脚32引脚33
spi0
group1
引脚52引脚53引脚50引脚51
spi1
group0
引脚52引脚53引脚50引脚51
spi1
group1
引脚69引脚68引脚85引脚84
spi2引脚76引脚77引脚78引脚16
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0
group0
引脚31引脚30引脚32引脚33
spi0
group1
引脚52引脚53引脚50引脚51
spi1
group0
引脚52引脚53引脚50引脚51
spi1
group1(EG810M_EU不支持)
引脚69引脚68引脚85引脚84
spi2引脚76引脚77引脚78引脚16
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚25引脚26引脚27引脚28
spi1引脚5引脚4引脚6引脚7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚37引脚40引脚38引脚39
spi1引脚26引脚27引脚25引脚24
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚37引脚40引脚38引脚39
spi1引脚26引脚27引脚25引脚24
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚37引脚40引脚38引脚39
spi1引脚136引脚135引脚127引脚62
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0(EC600ECN_LE&LQ不可用)引脚65引脚67引脚66引脚64
spi1引脚69引脚71引脚70引脚72
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚28引脚39引脚29引脚38
spi1(EC800ECN_LE&LQ&CG不可用)引脚52引脚53引脚50引脚51
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚4引脚1引脚3引脚2
spi1(EC800ECN_LE&LQ&CG不可用)引脚53引脚52引脚54引脚51
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi1引脚79引脚101引脚100引脚108
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0(EG912UGLAA不可用)引脚25引脚26引脚64引脚88
spi1引脚5引脚4引脚6引脚7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi1引脚4引脚1引脚3引脚2
spi2引脚58引脚61引脚59引脚60
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚31引脚30引脚32引脚33
spi1引脚52引脚53引脚50引脚51
spi2引脚74引脚75引脚76引脚77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚31引脚30引脚32引脚33
spi1引脚52引脚53引脚50引脚51
spi2引脚74引脚75引脚76引脚77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚31引脚30引脚32引脚33
spi1引脚52引脚53引脚50引脚51
spi2引脚74引脚75引脚76引脚77
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚66引脚29引脚67引脚28
spi1引脚64引脚49引脚63引脚62
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚21引脚22引脚29引脚23
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚29引脚30引脚37引脚31
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚41引脚42引脚43引脚44
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚41引脚42引脚43引脚44
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚5引脚4引脚6引脚7
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚49引脚29引脚101引脚28
spi1引脚52引脚53引脚50引脚51
+ + + + + + + + + + + + + + + + + + + + +
SPI通道CS引脚CLK引脚MOSI引脚MISO引脚
spi0引脚86引脚85引脚88引脚87
+ + + +
+ +## 方法 + +### `SPI.read` + +```python +SPI.read(recv_data, datalen) +``` + +该方法用于读取数据。 + +**参数描述:** + +- `recv_data` - 接收读取数据的数组,bytearray类型。 +- `datalen` - 读取数据的长度,int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `SPI.write` + +```python +SPI.write(data, datalen) +``` + +该方法用于写入数据。 + +**参数描述:** + +- `data` - 写入的数据,bytes类型。 +- `datalen` - 写入的数据长度,int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `SPI.write_read` + +```python +SPI.write_read(r_data, data, datalen) +``` + +该方法用于写入和读取数据。 + +**参数描述:** + +- `r_data ` - 接收读取数据的数组,bytearray类型。 +- `data` - 发送的数据,bytes类型。 +- `datalen` - 读取数据的长度,int类型。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `SPI.close` + +```python +SPI.close() +``` + +该方法用于关闭spi。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +**使用示例:** + +> 需要配合外设使用! + +```python +import log +from machine import SPI +import utime + +spi_obj = SPI(0, 0, 1) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +spi_log = log.getLogger("SPI") + +if __name__ == '__main__': + r_data = bytearray(5) # 创建接收数据的buff + data = b"world" # 测试数据 + + ret = spi_obj.write_read(r_data, data, 5) # 写入数据并接收 + spi_log.info(r_data) + +``` diff --git a/docs/API_reference/zh/peripherals/machine.SoftSPI.md b/docs/API_reference/zh/peripherals/machine.SoftSPI.md new file mode 100644 index 0000000000000000000000000000000000000000..2ac3e9c8d4311acb5c62a9d6c3b21a0b2eabc85f --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.SoftSPI.md @@ -0,0 +1,135 @@ +# class SoftSPI – 模拟SPI通信 + +该类提供模拟串行外设接口总线协议功能。 + +> EC600E/EC800E系列,FCM362K支持该功能。 + +## 构造函数 + +### `machine.SoftSPI` + +```python +class machine.SoftSPI(gpio_clk, gpio_cs, gpio_mosi, [gpio_miso],[wire_type],[speed],[mode],[cs_active_lvl]) +``` + +**参数描述:** + +- `gpio_clk` - int类型,clk管脚对应的gpio; +- `gpio_cs` - int类型,cs管脚对应的gpio; +- `gpio_mosi` - int类型,mosi管脚对应的gpio; +- `[gpio_miso]` - int类型,miso管脚对应的gpio,三线spi无需传入该参数,收发共用mosi管脚; +- `[wire_type]` - int类型,三线、四线spi设置,`WIRE_3`:三线spi,`WIRE_4`:四线spi,缺省为四线spi; +- `[speed]` - int类型,传输速度,`0`:50kHz,`1`:100kHz,缺省为100kHz; +- `[mode]` - int类型,spi模式,范围:`0`~`3`,缺省为模式`0`,说明如下:
`0` : CPOL=0, CPHA=0
`1` : CPOL=0, CPHA=1
`2`: CPOL=1, CPHA=0
`3`: CPOL=1, CPHA=1 +- `[cs_active_lvl]` - int类型,cs有效电平,`LOW`:低电平有效,`HIGH`:高电平有效,缺省为低电平有效。 + +**返回值描述:** + +成功返回创建的对象,失败直接报错。 + +**示例:** + +```python +from machine import SoftSPI +# 创建四线SPI对象,clk为gpio14,cs为gpio11,mosi为gpio12,miso为gpio13,模式0,速度为100kHz,cs低电平有效 +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,gpio_miso= SoftSPI.GPIO13) +# 创建四线SPI对象,clk为gpio14,cs为gpio11,mosi为gpio12,miso为gpio13,模式1,速度为50kHz,cs高电平有效 +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi=SoftSPI.GPIO12,gpio_miso=SoftSPI.GPIO13, + speed=0,mode=1,cs_active_lvl=SoftSPI.HIGH) +# 创建三线SPI对象,clk为gpio14,cs为gpio11,数据线为gpio12,模式0,速度100kHz,cs低电平有效 +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,wire_type= SoftSPI.WIRE_3) +# 创建三线SPI对象,clk为gpio14,cs为gpio11,数据线为gpio12,模式2,速度50kHz,cs高电平有效 +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi=SoftSPI.GPIO12,wire_type=SoftSPI.WIRE_3, + speed=0,mode=2,cs_active_lvl=SoftSPI.HIGH) +``` + +## 方法 + +### `SoftSPI.read` + +```python +SoftSPI.read(recv_data, datalen) +``` + +该方法用于读取数据。 + +**参数描述:** + +- `recv_data` - 接收读取数据的数组,bytearray类型。 +- `datalen` - 读取数据的长度,int类型。 + +**返回值描述:** + +返回整型值`0`。 + +### `SoftSPI.write` + +```python +SoftSPI.write(data, datalen) +``` + +该方法用于写入数据。 + +**参数描述:** + +- `data` - 写入的数据,bytes类型。 +- `datalen` - 写入的数据长度,int类型。 + +**返回值描述:** + +返回整型值`0`。 + +### `SoftSPI.write_read` + +```python +SoftSPI.write_read(r_data, data, datalen) +``` + +该方法用于写入和读取数据。 + +**参数描述:** + +- `r_data ` - 接收读取数据的数组,bytearray类型。 +- `data` - 发送的数据,bytes类型。 +- `datalen` - 读取数据的长度,int类型。 + +**返回值描述:** + +返回整型值`0`。 + +> 对于三线spi,通信过程:mosi设置为输出,发送data,mosi设置为输入,读取datalen长度的数据。 + +**使用示例:** + +> 需要配合外设使用! + +四线spi示例 + +```python +from machine import SoftSPI + +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,gpio_miso= SoftSPI.GPIO13) + +if __name__ == '__main__': + r_data = bytearray(5) # 创建接收数据的buff + data = b"world" # 测试数据 + spi.write_read(r_data, data, 5) # 写入数据并接收 + spi.read(r_data,5) #接收数据到r_data + spi.write(data,5)#发送数据 +``` + +三线spi示例 + +```python +from machine import SoftSPI + +spi=SoftSPI(gpio_clk=SoftSPI.GPIO14,gpio_cs=SoftSPI.GPIO11,gpio_mosi= SoftSPI.GPIO12,wire_type= SoftSPI.WIRE_3) + +if __name__ == '__main__': + r_data = bytearray(5) # 创建接收数据的buff + data = b"world" # 测试数据 + spi.write_read(r_data, data, 5) # 写入数据并接收 + spi.read(r_data,5) #接收数据到r_data + spi.write(data,5)#发送数据 +``` + diff --git a/docs/API_reference/zh/peripherals/machine.Timer.md b/docs/API_reference/zh/peripherals/machine.Timer.md new file mode 100644 index 0000000000000000000000000000000000000000..81b3fd4b31af442f3ecece9ede342b6e489e75e8 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.Timer.md @@ -0,0 +1,117 @@ +# class Timer - 硬件定时器 + +该类提供硬件定时器功能。 + +> 使用该定时器时需注意定时器0-3,每个在同一时间内只能执行一件任务,且多个对象不可使用同一个定时器。 + +## 构造函数 + +### `machine.Timer` + +```python +class machine.Timer(Timern) +``` + +**参数描述:** + +- `Timern` - 定时器号,int类型,支持定时器Timer0 ~ Timer3。 + +**示例:** + +```python +>>> # 创建Timer对象 +>>> from machine import Timer +>>> timer1 = Timer(Timer.Timer1) +``` + +## 方法 + +### `timer.start` + +```python +timer.start(period, mode, callback) +``` + +该方法用于启动定时器。 + +**参数描述:** + +- `period` - 中断周期,int类型,单位毫秒,大于等于1。 + +- `mode` - 运行模式,int类型,说明如下:
`ONE_SHOT` - 单次模式,定时器只执行一次
`PERIODIC` - 周期模式,循环执行 + +- `callback` - 定时器执行函数,function类型,原型为callback(arg),`arg`未实际使用,可直接传入`None`。callback函数触发后,必须调用stop接口停止该定时器,否则下次调用start接口后,callback不会被执行。 + +**返回值描述:** + +启动成功返回整型值`0`,失败返回整型值`-1`。 + +**示例:** + +```python +>>> def fun(args): + print("###timer callback function###") +>>> timer1.start(period=1000, mode=timer1.PERIODIC, callback=fun) +0 +###timer callback function### +###timer callback function### +###timer callback function### +…… +``` + +### `timer.stop` + +```python +timer.stop() +``` + +该方法用于关闭定时器。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +**使用示例**: + +```python +import log +import utime +from machine import Timer +import checkNet + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +Timer_Log = log.getLogger("Timer") + +num = 0 +state = 1 +# 注:EC100YCN支持定时器Timer0 ~ Timer3 +t = Timer(Timer.Timer1) + +# 创建一个执行函数,并将timer实例传入 +def timer_test(t): + global num + global state + Timer_Log.info('num is %d' % num) + num += 1 + if num > 10: + Timer_Log.info('num > 10, timer exit') + state = 0 + t.stop() # 结束该定时器实例 + + +if __name__ == '__main__': + t.start(period=1000, mode=t.PERIODIC, callback=timer_test) # 启动定时器 +``` + +## 常量 + +| 常量 | 说明 | +| -------------- | -------------------------- | +| Timer.Timer0 | 定时器0 | +| Timer.Timer1 | 定时器1 | +| Timer.Timer2 | 定时器2 | +| Timer.Timer3 | 定时器3 | +| Timer.ONE_SHOT | 单次模式,定时器只执行一次 | +| Timer.PERIODIC | 周期模式,定时器循环执行 | + diff --git a/docs/API_reference/zh/peripherals/machine.UART.md b/docs/API_reference/zh/peripherals/machine.UART.md new file mode 100644 index 0000000000000000000000000000000000000000..4a4cc860ee82b6a16cb72984640f06d88ea7a78d --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.UART.md @@ -0,0 +1,1609 @@ +# class UART - 串口通信 + +该类提供uart串口数据传输功能。 + +## 构造函数 + +### `machine.UART` + +
+
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT
    UART4 - STDOUT PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位仅支持8位,int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT
    UART4 - STDOUT PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[5 ~ 8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位仅支持8位,int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[5 ~ 8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ +
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl, [group])
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[5 ~ 8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • [group] - 选择在不同管脚使用UART,缺省值为0。int类型。

    +
  • +
+
+
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT (不支持BG95M3)

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[5 ~ 8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+
+
class machine.UART(UART.UARTn, baudrate, databits, parity, stopbits, flowctl)
+
+

参数描述:

+
    +
  • UARTn - UART编号,int类型,UARTn说明如下:
    UART0 - DEBUG PORT
    UART1 - BT PORT
    UART2 - MAIN PORT
    UART3 - USB CDC PORT

    +
  • +
  • baudratec - 波特率,int类型,支持常用波特率,如48009600192003840057600115200230400等;

  • +
  • databits - 数据位[5 ~ 8],int类型。

  • +
  • parity - 奇偶校验(0 – NONE,1 – EVEN,2 – ODD),int类型。

  • +
  • stopbits - 停止位[1 ~ 2],int类型。

  • +
  • flowctl - 硬件控制流(0 – FC_NONE, 1 – FC_HW),int类型。

    +
  • +
+
+ + + +
+ +**UART引脚对应关系 :** + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号124引脚号123NULLNULL
uart2引脚号32引脚号31引脚号34引脚号33
uart4引脚号103引脚号104NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号138引脚号137NULLNULL
uart2引脚号67引脚号68引脚号65引脚号64
uart4引脚号82引脚号81NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号12引脚号11NULLNULL
uart1引脚号63引脚号66NULLNULL
uart2引脚号67引脚号68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号12引脚号11NULLNULL
uart1引脚号26引脚号27NULLNULL
uart2引脚号67引脚号68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号12引脚号11NULLNULL
uart1引脚号63引脚号66NULLNULL
uart2引脚号67引脚号68NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1引脚号50引脚号51NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号29引脚号28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号23引脚号22NULLNULL
uart1引脚号27引脚号28NULLNULL
uart2引脚号64引脚号65NULLNULL
uart4引脚号35引脚号34NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号71引脚号72NULLNULL
uart1(flowctl = 0)引脚号3引脚号2NULLNULL
uart1(flowctl = 1)引脚号33引脚号34NULLNULL
uart2引脚号32引脚号31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号27引脚号28NULLNULL
uart2引脚号35引脚号34引脚号37引脚号36
uart4引脚号19引脚号18NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1(flowctl = 0)引脚号50引脚号51NULLNULL
uart1(flowctl = 1)引脚号22引脚号23NULLNULL
uart2引脚号18引脚号17NULLNULL
uart4引脚号29引脚号28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1(flowctl = 0)引脚号50引脚号51NULLNULL
uart1(flowctl = 1)引脚号22引脚号23NULLNULL
uart2引脚号18引脚号17NULLNULL
uart4引脚号29引脚号28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号23引脚号22NULLNULL
uart1(flowctl = 0)引脚号27引脚号28NULLNULL
uart1(flowctl = 1)引脚号36引脚号37NULLNULL
uart2引脚号35引脚号34NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号71引脚号72NULLNULL
uart1引脚号70引脚号69NULLNULL
uart2引脚号32引脚号31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号124引脚号123NULLNULL
uart2引脚号32引脚号31引脚34引脚33
uart4引脚号116引脚号9NULLNULL
uart5引脚号125引脚号126NULLNULL
uart6引脚号106引脚号105NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
uart5引脚号23引脚号22NULLNULL
uart6引脚号86引脚号83NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号27引脚号28NULLNULL
uart2引脚号35引脚号34引脚号37引脚号36
uart4引脚号19引脚号18NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号71引脚号72NULLNULL
uart1(flowctl = 0)引脚号3引脚号2NULLNULL
uart1(flowctl = 1)引脚号33引脚号34NULLNULL
uart2引脚号32引脚号31NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1(group = 0)引脚号50引脚号51NULLNULL
uart1(group = 1)引脚号22引脚号23NULLNULL
uart1(group = 2)引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1(group = 0)引脚号50引脚号51NULLNULL
uart1(group = 1)引脚号22引脚号23NULLNULL
uart1(group = 2)引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1(group = 0)引脚号50引脚号51NULLNULL
uart1(group = 1)引脚号22引脚号23NULLNULL
uart1(group = 2)引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1引脚号22引脚号23NULLNULL
uart2引脚号18引脚号17引脚23引脚22
uart3引脚号29引脚号28NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号27引脚号26NULLNULL
uart1引脚号20引脚号19NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart1引脚号35引脚号34NULLNULL
uart2引脚号28引脚号27NULLNULL
+ + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号21引脚号22NULLNULL
+ + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号22引脚号21NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号23引脚号22NULLNULL
uart1引脚号27引脚号28NULLNULL
uart2引脚号35引脚号34引脚号37引脚号36
uart4引脚号36引脚号37NULLNULL
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart0引脚号39引脚号38NULLNULL
uart1引脚号29引脚号28NULLNULL
uart2引脚号18引脚号17NULLNULL
+ + + + + + + + + + + + + + + + + + + +
uart编号TX引脚RX引脚RTS引脚CTS引脚
uart2引脚号35引脚号34NULLNULL
+ +
+ +
+
+
+

注意:

+

uart0不建议使用

+

EC200ACN_LA,EC200AEU_V1HA,EC200AAU_V1HA,EC200ACN_V1DA 模组uart1引脚号与其他型号不同:

+

TX:引脚号26

+

RX:引脚号27

+
+
+ +
+
+

注意:

+

uart0不建议使用

+
+
+ +
+
+

注意:

+

uart0不建议使用

+
+
+ +
+
+

注意:

+

EC800MCNGA 、CNGB、CNGD模块的uart1 不可用

+
+
+ +
+
+

注意:

+

EG810MCNGA、CNGB模块的uart1 不可用

+
+
+ +
+
+

注意:

+

EG800KCN模块的uart1不可用

+
+
+ +
+
+

注意:

+

EG915NEU_AG模块的uart4不可用

+
+
+ +
+
+

注意:

+

EC200UXXAA模组uart4不可用

+
+
+ +
+
+

注意:

+

EC600ECN_LE&LQ模组uart1不可用

+
+
+ +
+
+

注意:

+

EG912UGL_AA模组uart4不可用

+
+
+
+ +
+
+
+

使用UART4需要先调用modem.main_uart_enable_set(1)使能UART4,重启生效,如下

+
+
    +
    import modem
    +#获取Main_UART使能状态 1-使能,0-不使能
    +modem.main_uart_enable_get()
    +#设置Main_UART使能状态 1-使能,0-不使能,重启生效
    +modem.main_uart_enable_set(1)
    +
    +
+
+ +
+
+

uart1在flowctl = 1时,仅将uart1映射到不同的引脚,未开启流控功能。

+
+
+ + +
+
+

UART2被初始化后交互口将无法使用,需要在代码中执行uart2.close()或者重启模组才可继续使用交互口。

+
+
+ +
+
+

UART1被初始化后交互口将无法使用,需要在代码中执行uart1.close()或者重启模组才可继续使用交互口。

+
+
+
+ +**示例:** + +```python +>>> # 创建uart对象 +>>> from machine import UART +>>> uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0) +``` + +## 方法 + +### `uart.any` + +```python +uart.any() +``` + +该方法用于获取接收缓存未读数据大小。 + +**返回值描述:** + +返回接收缓存器中有多少字节的数据未读。 + +**示例:** + +```python +>>> uart1.any() +20 #表示接收缓冲区中有20字节数据未读 +``` + +### `uart.read` + +```python +uart.read(nbytes) +``` + +该方法用于从串口读取数据。 + +**参数描述:** + +- `nbytes` - 要读取的字节数,int类型。 + +**返回值描述:** + +返回读取的数据。 + +### `uart.write` + +```python +uart.write(data) +``` + +该方法用于发送数据到串口。 + +**参数描述:** + +- `data` - 发送的数据,bytes类型。 + +**返回值描述:** + +返回发送的字节数。 + +### `uart.close` + +```python +uart.close() +``` + +该方法用于关闭串口。 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `uart.control_485` + +
+
+ +
uart.control_485(UART.GPIOn, direction)
+
+

该方法用于控制485通信方向,串口发送数据之前和之后进行拉高拉低指定GPIO,用来指示485通信的方向。

+

参数描述:

+
    +
  • GPIOn - 需要控制的GPIO引脚号,参照Pin模块的引脚定义,int类型。

    +
  • +
  • direction - 引脚电平变化,int类型,说明如下:
    1表示引脚电平变化为:串口发送数据之前由低拉高、发送数据之后再由高拉低
    0表示引脚电平变化为:串口发送数据之前由高拉低、发送数据之后再由低拉高

    +
  • +
+

返回值描述:

+

成功返回整型值0,失败返回整型值-1

+

示例:

+
from machine import UART
+uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0)
+uart1.control_485(UART.GPIO24, 1)
+
+ +
+ +
+

该型号不支持此API

+
+
+ +### `uart.set_callback` + +```python +uart.set_callback(fun) +``` + +该方法用于设置串口数据回调,串口收到数据后,会执行该回调。 + +**参数描述:** + +- `fun` - 串口回调函数,回调函数原型: + + ``` + fun(result_list) + ``` + + 回调函数参数描述: + + - `result_list[0]`:接收是否成功(0:成功,其它:失败) + + - `result_list[1]`:接收端口 + + - `result_list[2]`:返回有多少数据 + +**返回值描述:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +**示例:** + +```python +>>> from machine import UART +>>> uart1 = UART(UART.UART1, 115200, 8, 0, 1, 0) +>>> +>>> def uart_call(para): +>>> print(para) +>>> uart1.set_callback(uart_call) +``` + +**使用示例:** + +```python +""" +运行本例程,需要通过串口线连接开发板的 MAIN 口和PC,在PC上通过串口工具 +打开 MAIN 口,并向该端口发送数据,即可看到 PC 发送过来的消息。 +""" +import _thread +import utime +import log +from machine import UART + +''' + * 参数1:端口 + 注:EC100YCN平台与EC600SCN平台,UARTn作用如下 + UART0 - DEBUG PORT + UART1 – BT PORT + UART2 – MAIN PORT + UART3 – USB CDC PORT + * 参数2:波特率 + * 参数3:data bits (5~8) + * 参数4:Parity (0:NONE 1:EVEN 2:ODD) + * 参数5:stop bits (1~2) + * 参数6:flow control (0: FC_NONE 1:FC_HW) +''' + + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +uart_log = log.getLogger("UART") + +class Example_uart(object): + def __init__(self, no=UART.UART2, bate=115200, data_bits=8, parity=0, stop_bits=1, flow_control=0): + self.uart = UART(no, bate, data_bits, parity, stop_bits, flow_control) + self.uart.set_callback(self.callback) + + + def callback(self, para): + uart_log.info("call para:{}".format(para)) + if(0 == para[0]): + self.uartRead(para[2]) + + + def uartWrite(self, msg): + uart_log.info("write msg:{}".format(msg)) + self.uart.write(msg) + + def uartRead(self, len): + msg = self.uart.read(len) + utf8_msg = msg.decode() + uart_log.info("UartRead msg: {}".format(utf8_msg)) + return utf8_msg + + def uartWrite_test(self): + for i in range(10): + write_msg = "Hello count={}".format(i) + self.uartWrite(write_msg) + utime.sleep(1) + +if __name__ == "__main__": + uart_test = Example_uart() + uart_test.uartWrite_test() + + +# 运行结果示例 +''' +INFO:UART:write msg:Hello count=0 +INFO:UART:write msg:Hello count=1 +INFO:UART:write msg:Hello count=2 +INFO:UART:write msg:Hello count=3 +INFO:UART:write msg:Hello count=4 +INFO:UART:write msg:Hello count=5 +INFO:UART:write msg:Hello count=6 +INFO:UART:write msg:Hello count=7 +INFO:UART:write msg:Hello count=8 +INFO:UART:write msg:Hello count=9 + +INFO:UART:call para:[0, 2, 15] +INFO:UART:UartRead msg: my name is XXX + + +''' + +``` + +## 常量 + +| 常量 | 说明 | +| ---------- | ----- | +| UART.UART0 | UART0 | +| UART.UART1 | UART1 | +| UART.UART2 | UART2 | +| UART.UART3 | UART3 | +| UART.UART4 | UART4 | + diff --git a/docs/API_reference/zh/peripherals/machine.WDT.md b/docs/API_reference/zh/peripherals/machine.WDT.md new file mode 100644 index 0000000000000000000000000000000000000000..1c3663327a982eb5af88c9b41236a8c5dc6af852 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.WDT.md @@ -0,0 +1,71 @@ +# class WDT – 看门狗定时器 + +该类提供APP应用程序发生异常不执行时进行系统重启操作。 + +## 构造函数 + +### `machine.WDT` + +```python +class machine.WDT(period) +``` + +创建软狗对象。 + +**参数描述:** + +- `period` - 设置软狗检测时间,单位(s),int类型。 + +**返回值描述:** + +返回软狗对象。 + +>FCM360W实际超时时间生效值与设置值不一样,具体如下:
+1024s>设置时间>=256s,生效时间为256s
256s>设置时间>=64s,生效时间为64s
64s>设置时间>=16s,生效时间为16s
16s>设置时间>=4.5s,生效时间为4.5s
4.5s>设置时间>=1.5s,生效时间为1.5s
1.5s>设置时间>=1.004s,生效时间为1.004s
1.004s>设置时间>=0.502s,生效时间为0.502s
0.502s>设置时间>=0.252s,生效时间为0.252s
+ +## 方法 + +### `wdt.feed` + +```python +wdt.feed() +``` + +该方法用于喂狗。 + +**返回值描述:** + +成功返回整型值`0`。 + +### `wdt.stop` + +```python +wdt.stop() +``` + +该方法用于关闭软狗功能。 + +**返回值描述:** + +成功返回整型值`0`。 + +**使用示例:** + +```python +from machine import WDT +from machine import Timer + + +timer1 = Timer(Timer.Timer1) + +def feed(t): + wdt.feed() + + +if __name__ == '__main__': + wdt = WDT(20) # 启动看门狗,设置超时时间 + timer1.start(period=15000, mode=timer1.PERIODIC, callback=feed) # 使用定时器喂狗 + + # wdt.stop() + +``` diff --git a/docs/API_reference/zh/peripherals/machine.md b/docs/API_reference/zh/peripherals/machine.md new file mode 100644 index 0000000000000000000000000000000000000000..ebcf9ef9e244e02415878ed22805b0189419a300 --- /dev/null +++ b/docs/API_reference/zh/peripherals/machine.md @@ -0,0 +1,19 @@ +# machine - 硬件相关功能 + +该模块包含与特定电路板上的硬件相关的功能。该模块中的大多数功能允许直接且不受限制地访问和控制系统上的硬件。 + +## Classes + +- [class Pin – 控制I/O引脚](./machine.Pin.md) +- [class UART – 串口通信](./machine.UART.md) +- [class Timer – 硬件定时器](./machine.Timer.md) +- [class ExtInt - 外部中断](./machine.ExtInt.md) +- [class RTC – 实时时钟](./machine.RTC.md) +- [class I2C – I2C通信](./machine.I2C.md) +- [class I2C_simulation - 模拟I2C通信](./machine.I2C_simulation.md) +- [class SPI – SPI通信](./machine.SPI.md) +- [class SoftSPI – 模拟SPI通信](./machine.SoftSPI.md) +- [class LCD - LCD显示屏](./machine.LCD.md) +- [class WDT – 看门狗定时器](./machine.WDT.md) +- [class KeyPad - 矩阵键盘](./machine.KeyPad.md) +- [class OneWire - 单总线](./machine.OneWire.md) diff --git a/docs/API_reference/zh/peripherals/misc.ADC.md b/docs/API_reference/zh/peripherals/misc.ADC.md new file mode 100644 index 0000000000000000000000000000000000000000..5fcbb02a8ec06c7e38652e6c4b941d309f46ada9 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.ADC.md @@ -0,0 +1,1164 @@ +# class ADC - 模数转换 + +用于采集电压信号。 + +## 构造函数 + +### `misc.ADC` + +```python +class misc.ADC() +``` + +**示例:** + +```python +from misc import ADC +adc = ADC() +``` + +## 方法 + +### `ADC.open` + +```python +ADC.open() +``` + +ADC功能初始化。 + +**返回值描述:** + +`0`表示初始化成功,`-1`表示初始化失败。 + +### `ADC.read` + +```python +ADC.read(ADCn) +``` + +读取指定通道的电压值,单位`mV`。 + +**参数描述:** + +- `ADCn`-ADC通道,int类型,点此查看支持的通道与对应引脚 + +**返回值描述:** + +成功返回指定通道电压值,错误返回整型`-1`。 + +**示例:** + +```python +>>>adc.read(ADC.ADC0) #读取ADC通道0电压值 +613 +>>>adc.read(ADC.ADC1) #读取ADC通道1电压值 +605 +``` + +### `ADC.close` + +```python +ADC.close() +``` + +**返回值描述:** + +`0`表示关闭成功,`-1`表示关闭失败。 + +**ADC通道与物理引脚的映射关系:** + +
+ + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号19
ADC1引脚号20
+ + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号19
ADC1引脚号20
ADC2引脚号113
ADC3引脚号114
+ + + + + + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号45
ADC1引脚号44
ADC2引脚号43
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号45
ADC1引脚号44
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号45
ADC1引脚号44
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号45
ADC1引脚号44
+ + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
ADC1引脚号2
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
ADC1引脚号2
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号19
ADC1引脚号20
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号19
ADC1引脚号20
ADC2引脚号113
ADC3引脚号114
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
ADC1引脚号2
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号19
ADC1引脚号20
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号8
ADC1引脚号7
ADC2引脚号6
+ + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号2
+ + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号2
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
ADC1引脚号2
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号9
ADC1引脚号96
+ + + + + + + + + + + + + + + + + + +
ADC编号引脚对应
ADC0引脚号24
ADC1引脚号2
+ +
+ +## 常量 + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
ADC.ADC2ADC通道2
ADC.ADC3ADC通道3
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
ADC.ADC2ADC通道2
+ + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
+ + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
+ + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
ADC.ADC2ADC通道2
+ + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
+ + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ + + + + + + + + + + + + + + + + + +
常量说明
ADC.ADC0ADC通道0
ADC.ADC1ADC通道1
+ +
\ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/misc.PWM.md b/docs/API_reference/zh/peripherals/misc.PWM.md new file mode 100644 index 0000000000000000000000000000000000000000..777fcf5d4c36eef4c8dc62a277a36fd7b1c04cda --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.PWM.md @@ -0,0 +1,212 @@ +# class PWM - 脉宽调制 + +提供脉宽调制输出功能。 + +> BC25系列不支持此模块。 + +## 构造函数 + +### `misc.PWM` + +```python +class misc.PWM(PWM.PWMn,PWM.ABOVE_xx, highTime, cycleTime) +``` + +**参数描述:** + +- `PWM.PWMn`-PWM通道,int类型,点此查看支持的通道与对应引脚; + +- `PWM.ABOVE_xx`-时间取值范围,int类型,说明如下: + + EC200U/EC600U/EG915U/EG912U系列:
PWM.ABOVE_MS ms级取值范围:(0,10]
PWM.ABOVE_1US us级取值范围:(0,10000]
PWM.ABOVE_10US us级取值范围:(1,10000]
PWM.ABOVE_BELOW_US ns级取值范围[100,65535] +
FCM360W:
PWM.ABOVE_MS ms级取值范围:[0,1]
PWM.ABOVE_1US us级取值范围:[0,1638]
PWM.ABOVE_10US us级取值范围:[0,1638]
PWM.ABOVE_BELOW_US ns级取值范围: [2500,65535] + +- `highTime`-高电平时间,int类型,说明如下: + + ms级时,单位为ms
us级时,单位为us
ns级别:需要使用者计算
频率 = 1 / cycleTime
占空比 = highTime/ cycleTime + +- `cycleTime`-周期时间,int类型,说明如下: + + ms级时,单位为ms
us级时,单位为us
ns级别:需要使用者计算
频率 = 1 / cycleTime
占空比 = highTime/ cycleTime + +> 频率支持范围:EC600N/EC800N/EG912N/EC600M/EC800M/EG810M/EC200A/EC200AEUV1/EC600E/EC800E/EC600K/EC800K/EG915N:1Hz-1MHz,EC200U/EC600U/EG915U系列:100Hz-1MHz,BG95系列:293Hz-600kHz。 + +**示例:** + +```python + from misc import PWM + pwm1 = PWM(PWM.PWM1, PWM.ABOVE_MS, 1, 2) +``` + +### `misc.PWM_V2` + +```python +class misc.PWM_V2(PWM_V2.PWMn,frequency, duty) +``` + +**参数描述**: + +- PWM_V2.PWMn-PWM通道,int类型,点此查看支持的通道与对应引脚; +- frequency,频率,float类型,注意要输入浮点数据:100.0表示100Hz; +- duty,占空比,int类型,输入范围0~100,输入50代表占空比50%。 + +> 1、EC600U/EC200U/EG912U/EG915U不支持占空比设置为0。 +> +> 2、FCM360W支持的frequency范围为610Hz至40MHz + +**示例:** + +```python +from misc import PWM_V2 +pwm1 = PWM_V2(PWM_V2.PWM1, 100.0, 50)#频率100Hz,占空比50% +``` + +**PWM通道与物理引脚的映射关系:** + +| 系列 | 对应引脚 | +| ------ | ------------------------------------------------------------ | +| EC600N | PWM0 – 引脚号52
PWM1 – 引脚号53
PWM2 – 引脚号70
PWM3 – 引脚号69 | +| EC800N | PWM0 – 引脚号79
PWM1 – 引脚号78
PWM2 – 引脚号16
PWM3 – 引脚号49 | +| EC200U | PWM0 – 引脚号135 | +| EC600U | PWM0 – 引脚号70 | +| EC600M | PWM0 – 引脚号57
PWM1 – 引脚号56
PWM2 – 引脚号70
PWM3 – 引脚号69 | +| EG915U | PWM0 – 引脚号20 | +| EC800M/EG810M | PWM0 – 引脚号83
PWM1 – 引脚号78
PWM2 – 引脚号16
PWM3 – 引脚号49 | +| EG912N | PWM0 – 引脚号21
PWM1 – 引脚号116
PWM2 – 引脚号107
PWM3 – 引脚号92 | +| EC200A/UC200A | PWM0 – 引脚号1
PWM1 – 引脚号4
PWM2 – 引脚号6 | +| EC200AEUV1 | PWM0 – 引脚号65
PWM1 – 引脚号64
PWM2 – 引脚号6
PWM3 – 引脚号4 | +| EC600E | PWM0 – 引脚号52(不可与PWM6/12同时为PWM)
PWM1 – 引脚号53(不可与PWM7/13同时为PWM)
PWM2 – 引脚号54(不可与PWM8/14同时为PWM)
PWM3 – 引脚号63(不可与PWM9/15/16同时为PWM)(EC600ECN_LE&LQ不可用)
PWM5 – 引脚号48(不可与PWM11同时为PWM)
PWM6 – 引脚号31(不可与PWM0/12同时为PWM)
PWM7 – 引脚号33(不可与PWM1/13同时为PWM)
PWM8 – 引脚号34(不可与PWM2/14同时为PWM)
PWM9 – 引脚号71(不可与PWM3/15/16同时为PWM)
PWM11 – 引脚号72(不可与PWM5同时为PWM)
PWM12 – 引脚号60(不可与PWM0/6同时为PWM)
PWM13 – 引脚号58(不可与PWM1/7同时为PWM)
PWM14 – 引脚号59(不可与PWM2/8同时为PWM)
PWM15 – 引脚号62(不可与PWM3/9/16同时为PWM)(EC600ECN_LE&LQ不可用)
PWM16 – 引脚号61(不可与PWM3/9/15同时为PWM) | +| EC800E | PWM0 – 引脚号25(不可与PWM6/12同时使用)
PWM1 – 引脚号78(不可与PWM7/13同时使用)(EC800ECN_LE&LQ&CG不可用)
PWM2 – 引脚号16(不可与PWM8/14同时使用)
PWM3 – 引脚号49(不可与PWM9/15同时使用)(EC800ECN_LE&LQ&CG不可用)
PWM4 – 引脚号31(不可与PWM10/16同时使用)
PWM6 – 引脚号32(不可与PWM0/12同时使用)
PWM7 – 引脚号30(不可与PWM1/13同时使用)
PWM8 – 引脚号17(不可与PWM2/14同时使用)
PWM9 – 引脚号21(不可与PWM3/15同时使用)
PWM10 – 引脚号85(不可与PWM4/16同时使用)(EC800ECN_LE&LQ&LC&CG不可用)
PWM12 – 引脚号23(不可与PWM0/6同时使用)
PWM13 – 引脚号39(不可与PWM1/7同时使用)
PWM14 – 引脚号33(不可与PWM2/8同时使用)
PWM15 – 引脚号38(不可与PWM3/9同时使用)
PWM16 – 引脚号22(不可与PWM4/10同时使用) | +| BG95 | PWM0 – 引脚号66
PWM1 – 引脚号85 | +| EC600G | PWM0 – 引脚号54
PWM1 – 引脚号9(不可与PWM2/3同时使用)
PWM2 – 引脚号126(不可与PWM1/3同时使用)
PWM3 – 引脚号125(不可与PWM1/2同时使用) | +| EC800G | PWM0 – 引脚号79(不可与PWM20同时使用)
PWM1 – 引脚号25(不可与PWM4/8/17/18同时使用)
PWM2 – 引脚号16
PWM3 – 引脚号21(不可与PWM5同时使用)
PWM4– 引脚号20(不可与PWM1/8/17/18同时使用)
PWM5 – 引脚号22(不可与PWM3同时使用)
PWM6 – 引脚号28(不可与PWM22同时使用)
PWM7 – 引脚号29(不可与PWM23同时使用)
PWM8 – 引脚号54(不可与PWM1/4/17/18同时使用)
PWM9 – 引脚号57(不可与PWM10/27同时使用)
PWM10 – 引脚号58(不可与PWM9/27同时使用)
PWM11 – 引脚号62(不可与PWM15同时使用)
PWM12 – 引脚号63(不可与PWM16/19/21/24/28同时使用)
PWM13 – 引脚号64(不可与PWM14同时使用)
PWM14 – 引脚号66(不可与PWM13同时使用)
PWM15 – 引脚号67(不可与PWM11同时使用)
PWM16 – 引脚号68(不可与PWM12/19/21/24/28同时使用)
PWM17 – 引脚号69(不可与PWM1/4/8/18同时使用)
PWM18 – 引脚号80(不可与PWM1/4/8/17同时使用)
PWM19 – 引脚号81(不可与PWM12/16/21/24/28同时使用)
PWM20 – 引脚号82(不可与PWM0同时使用)
PWM21 – 引脚号83(不可与PWM12/16/19/24/28同时使用)
PWM22 – 引脚号84(不可与PWM6同时使用)
PWM23 – 引脚号85(不可与PWM7同时使用)
PWM24 – 引脚号86(不可与PWM12/16/19/21/28同时使用)
PWM25 – 引脚号87(不可与PWM26同时使用)
PWM26 – 引脚号100(不可与PWM25同时使用)
PWM27 – 引脚号101(不可与PWM9/10同时使用)
PWM28 – 引脚号103(不可与PWM12/16/19/21/24同时使用) | +| EG912U | PWM0 – 引脚号20 | +| EC600K | PWM0 – 引脚号10
PWM2 – 引脚号70
PWM3 – 引脚号69 | +| EC800K/EG800K/EG800AK | PWM1 – 引脚号78
PWM2 – 引脚号83 | +| FCM360W | PWM0 – 引脚号13
PWM1 – 引脚号14
PWM2 – 引脚号15
PWM3 – 引脚号16
PWM4 – 引脚号8
PWM5 – 引脚号7 | +| EG915N | PWM0 – 引脚号25
PWM1 – 引脚号26
PWM2 – 引脚号104
PWM3 – 引脚号18 | +| BG950S | PWM0 – 引脚号66
PWM1 – 引脚号38
PWM2 – 引脚号30 | +| EG800Z | PWM0 – 引脚号20
PWM1 – 引脚号33
PWM2 – 引脚号32
PWM3 – 引脚号31
PWM4 – 引脚号30
PWM7 – 引脚号16
PWM8 – 引脚号49
PWM9 – 引脚号22
PWM10 – 引脚号26
PWM11 – 引脚号25
PWM12 – 引脚号54
PWM13 – 引脚号101
PWM14 – 引脚号100 | + +## 方法 + +### `PWM.open` + +```python +PWM.open([PWM.ABOVE_xx],[highTime],[cycleTime]) +``` + +该方法用于开启PWM输出,PWM.ABOVE_xx,highTime,cycleTime为可缺省参数,只允许参数都缺省或传入3个参数;若缺省,按照初始化时的参数输出;若传参,按照传入的参数输出。 + +**参数描述:** + +- 参照构造函数说明。 + +**返回值描述:** + +`0`表示开启成功,`-1`表示开启失败。 + +### `PWM_V2.open` + +```python +PWM_V2.open([frequency],[duty]) +``` + +该方法用于开启PWM输出,frequency,duty为可缺省参数,只允许参数都缺省或传入2个参数;若缺省,按照初始化时的参数输出;若传参,按照传入的参数输出。 + +**参数描述:** + +- 参照构造函数说明。 + +**返回值描述:** + +`0`表示开启成功,`-1`表示开启失败。 + +### `PWM.close` + +``` +PWM.close() +``` + +该方法用于关闭PWM输出。 + +**返回值描述:** + +`0`表示关闭成功,`-1`表示关闭失败。 + +### `PWM_V2.close` + +``` +PWM_V2.close() +``` + +该方法用于关闭PWM输出。 + +**返回值描述:** + +`0`表示关闭成功,`-1`表示关闭失败。 + +**示例:** + +```python +from misc import PWM +import utime + +if __name__ == '__main__': + pwm = PWM(PWM.PWM0, PWM.ABOVE_MS, 1, 2) #初始化一个pwm对象,频率500Hz,占空比50% + pwm.open() #开启PWM输出 + utime.sleep(10) + pwm.open(PWM.ABOVE_MS, 5, 10) #开启PWM输出,并设置频率为100Hz,占空比50% + utime.sleep(10) + pwm.close() #关闭pwm输出 +``` + +```python +from misc import PWM_V2 +import utime + +if __name__ == '__main__': + pwm = PWM_V2(PWM_V2.PWM0,100.0,50) #初始化一个pwm对象,频率100Hz,占空比50% + pwm.open() # 开启PWM输出 + utime.sleep(10) + pwm.open(200.0,40)#开启PWM输出,并设置pwm频率为200Hz,占空比40% + utime.sleep(10) + pwm.close() #关闭pwm输出 +``` + + + +## 常量 + +| 常量 | 说明 | 使用平台 | +| --------- | ----- | ------------------------------------------------------------ | +| PWM.PWM0 | PWM0 | EC600S / EC600N / EC100Y/EC600U/EC200U/EC800N/EC600M/EG915U/EC800M/EG912N/BG95/EC600E/EC800E/
EC600G/EC800G/EC200A/EC200AEUV1/EG912U/EC600K/FCM360W/EG915N/BG950S/EG800Z | +| PWM.PWM1 | PWM1 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/BG95/EC600E/EC800E/
EC600G/EC800G/EC200A/EC200AEUV1/EC800K/EG800K/EG800AK/EG800Z/FCM360W/EG915N/BG950S | +| PWM.PWM2 | PWM2 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EC600E/EC800E/EC600G/
EC800G/EC200A/EC200AEUV1/EC600K/FCM360W/EG915N/EC800K/EG800K/EG800AK/EG800Z/BG950S| +| PWM.PWM3 | PWM3 | EC600S / EC600N / EC100Y/EC800N/EC600M/EC800M/EG912N/EC600E/EC800E/EC600G/
EC800G/EC200AEUV1/EC600K/FCM360W/EG915N/EG800Z | +| PWM.PWM4 | PWM4 | EC600E/EC800E/EC800G/FCM360W/EG800Z | +| PWM.PWM5 | PWM5 | EC600E/EC800E/EC800G/FCM360W | +| PWM.PWM6 | PWM6 | EC600E/EC800E/EC800G | +| PWM.PWM7 | PWM7 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM8 | PWM8 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM9 | PWM9 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM10 | PWM10 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM11 | PWM11 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM12 | PWM12 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM13 | PWM13 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM14 | PWM14 | EC600E/EC800E/EC800G/EG800Z | +| PWM.PWM15 | PWM15 | EC600E/EC800E/EC800G | +| PWM.PWM16 | PWM16 | EC600E/EC800E/EC800G | +| PWM.PWM17 | PWM17 | EC800G | +| PWM.PWM18 | PWM18 | EC800G | +| PWM.PWM19 | PWM19 | EC800G | +| PWM.PWM20 | PWM20 | EC800G | +| PWM.PWM21 | PWM21 | EC800G | +| PWM.PWM22 | PWM22 | EC800G | +| PWM.PWM23 | PWM23 | EC800G | +| PWM.PWM24 | PWM24 | EC800G | +| PWM.PWM25 | PWM25 | EC800G | +| PWM.PWM26 | PWM26 | EC800G | +| PWM.PWM27 | PWM27 | EC800G | +| PWM.PWM28 | PWM28 | EC800G | + diff --git a/docs/API_reference/zh/peripherals/misc.Power.md b/docs/API_reference/zh/peripherals/misc.Power.md new file mode 100644 index 0000000000000000000000000000000000000000..14dccefb0c9a3d4ba5d67b73ccbbca90188d3c34 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.Power.md @@ -0,0 +1,132 @@ +# power - 关机以及软件重启 + +提供关机、软件重启、获取开机原因、获取上次关机原因、获取电池电压功能。 + +## 关机功能 + +### `Power.powerDown` + +```python +Power.powerDown() +``` + +模块关机。 + +**示例:** + +```python +from misc import Power + +Power.powerDown() +``` + +## 重启功能 + +### `Power.powerRestart` + +```python +Power.powerRestart() +``` + +模块重启。 + +## 获取开机原因功能 + +### `Power.powerOnReason` + +```python +Power.powerOnReason() +``` + +获取开机原因。 + +**返回值描述:** + +| 值 | 说明 | +| ---- | -------------------------------- | +| 0 | 获取开机原因失败或者开机原因未知 | +| 1 | 按 PWRKEY 开机 | +| 2 | 按 RESET 重启 | +| 3 | VBAT 触发的开机 | +| 4 | RTC 定时开机 | +| 5 | watchdog 触发重启或异常开机 | +| 6 | VBUS 触发的开机 | +| 7 | 充电开机 | +| 8 | PSM 唤醒开机 | +| 9 | 发生 Dump 后重启 | + +## 获取上次关机原因 + +### `Power.powerDownReason` + +``` +Power.powerDownReason() +``` + +获取关机原因。 + +**返回值描述:** + +| 值 | 说明 | +| ---- | --------------------- | +| 0 | 原因未知 | +| 1 | 正常关机 | +| 2 | 供电电压过高导致关机 | +| 3 | 供电电压过低导致关机 | +| 4 | 温度过高导致关机 | +| 5 | 看门狗触发的关机 | +| 6 | VRTC 电压过低触发关机 | + +> BC25PA系列和EC200U/EC600U系列不支持此方法。 + +## 获取电池电压 + +### `Power.getVbatt` + +```python +Power.getVbatt() +``` + +获取电池电压,单位mV。 + +**返回值描述:** + +返回整型电压值。 + +**示例:** + +```python +Power.getVbatt() +3590 +``` + +## CAM_VDD电源输出 + +### `Power.camVDDEnable` + +```python +Power.camVDDEnable(enable,[vol],[lp_enable]) +``` + +CAM_VDD管脚电源输出控制。 + +> 仅EC600U/EG912U/EG915U系列支持。 + +**参数描述:** + +- `enable` int类型,范围0/1,0:关闭输出,1:打开输出; +- `[vol]`- int类型,可缺省,范围:VDD_1V80,VDD_2V50,VDD_2V80,VDD_3V00,分别设置输出电压为1.8v,2.5v,2.8v,3.0v,缺省为输出2.8v。 +- `[lp_enable]`-int类型,可缺省,LP_ENABLE:低功耗状态可以输出,LP_DISABLE:低功耗状态不输出,缺省为低功耗状态不输出。 + +**返回值描述:** + +0表示成功,-1表示失败。 + +**示例:** + +```python +from misc import Power +Power.camVDDEnable(1,Power.VDD_1V80,Power.LP_ENABLE)#打开cam_vdd电源输出,电压1.8v,在低功耗下继续输出 +Power.camVDDEnable(0)#关闭输出 +``` + diff --git a/docs/API_reference/zh/peripherals/misc.PowerKey.md b/docs/API_reference/zh/peripherals/misc.PowerKey.md new file mode 100644 index 0000000000000000000000000000000000000000..9a112788d1ef5e6ec7e2b1dc7b6bb4e2b152a830 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.PowerKey.md @@ -0,0 +1,98 @@ +# class PowerKey - power key按键回调注册功能 + +提供power key事件回调注册功能。 + +## 构造函数 + +### `misc.PowerKey` + +```python +class misc.PowerKey() +``` + +**返回值描述:** + +返回创建的对象。 + +**示例:** + +```python +from misc import PowerKey +pk = PowerKey() +``` + +## 方法 + +### `PowerKey.powerKeyEventRegister` + +```python +PowerKey.powerKeyEventRegister(usrFun, pwk_mode) #ECX00U/EG91XU系列支持可选参数pwk_mode + +PowerKey.powerKeyEventRegister(usrFun) #其他平台仅支持设置usrFun +``` + +该方法用于注册powerkey按键的回调函数。 + +**参数描述:** + +- `usrfun`-回调函数,原型usrfun(status),参数status,int类型:`0`表示松开,`1`表示按下;按下或松开powerkey按键时触发回调。 + +- `pwk_mode`-(仅ECX00U/EG91XU系列支持)可选参数,powerkey工作模式,int类型:默认为 `0`,`0`表示只在按键松开时才会触发回调函数,并且按键按下的时间需要维持500ms以上;`1`表示按下和松开时,都会触发用户注册的回调函数。 + +**返回值描述:** + +`0`表示注册成功,`-1`表示注册失败。 + +> ECX00S/ECX00N/ECX00M/EG810M/ECX00E/ECX00G系列,对于powerkey,按下和松开时,都会触发用户注册的回调函数; +> +> ECX00U/EG91XU系列,通过可选参数控制powerkey工作模式,在两种特性间切换:当工作模式为0时,只在按键松开时才会触发回调函数,并且按键按下的时间需要维持500ms以上;工作模式为1时,按下和松开时,都会触发用户注册的回调函数; +> +> 上述所有平台在注册用户的回调函数后,powerkey长按不再触发关机。 + +### `PowerKey.getpowerKeyStatus` + +```python +PowerKey.getpowerKeyStatus() +``` + +该方法仅EC600M/EC800M系列支持,用于获取powerkey按键的状态。 + +**返回值描述:** + +`0`表示松开,`1`表示按下。 + +**示例:** + +ECX00S/ECX00N/ECX00M/EG810M/ECX00E/ECX00G系列: + +```python +from misc import PowerKey + +pk = PowerKey() + +def pwk_callback(status): + if status == 0: + print('powerkey release.') + elif status == 1: + print('powerkey press.') + +pk.powerKeyEventRegister(pwk_callback) +``` + +ECX00U/EG91XU系列: + +```python +from misc import PowerKey + +pk = PowerKey() + +def pwk_callback(status): + if status == 0: + print('powerkey release.') + elif status == 1: + print('powerkey press.') + +pk.powerKeyEventRegister(pwk_callback, 0) # 只有按键释放时才会触发回调 + +pk.powerKeyEventRegister(pwk_callback, 1) # 按键按下和释放时都触发回调 +``` diff --git a/docs/API_reference/zh/peripherals/misc.USB.md b/docs/API_reference/zh/peripherals/misc.USB.md new file mode 100644 index 0000000000000000000000000000000000000000..91b6192286dbd4e0fed161f055a12d58d58cbb34 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.USB.md @@ -0,0 +1,69 @@ +# class USB - USB插拔检测 + +提供USB插拔检测功能。 + +> EC600S/EC600N/EC800N/EG912N/EC200U/EC600U/EG915U/EC600M/EC800M/EC200A系列支持该功能。 + +## 构造函数 + +### `misc.USB` + +```python +class misc.USB() +``` + +**示例:** + +```python +from misc import USB +usb = USB() +``` + +## 方法 + +### `USB.getStatus` + +```python +USB.getStatus() +``` + +该方法用于获取当前USB连接状态。 + +**返回值描述:** + +`-1` 表示 获取状态失败,`0 `表示USB当前没有连接,`1 `表示 USB已连接。 + +### `usb.setCallback` + +``` +usb.setCallback(usrFun) +``` + +该方法用于注册USB插拔回调函数,当USB插入或者拔出时,会触发回调来通知用户当前USB状态。 + +**参数描述:** + +- `usrFun` -回调函数,原型usrFun (conn_status),参数conn_status:`0`表示未连接,`1`表示连接。 + +**返回值描述:** + +`0`表示注册成功,`-1`表示注册失败。 + +> 回调函数中不要进行阻塞性的操作。 + +**示例:** + +```python +from misc import USB + +usb = USB() + +def usb_callback(conn_status): + status = conn_status + if status == 0: + print('USB is disconnected.') + elif status == 1: + print('USB is connected.') +usb.setCallback(usb_callback) +``` + diff --git a/docs/API_reference/zh/peripherals/misc.USBNET.md b/docs/API_reference/zh/peripherals/misc.USBNET.md new file mode 100644 index 0000000000000000000000000000000000000000..8dcb9d6ee971136c6aeb316fd219ab02963f10c5 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.USBNET.md @@ -0,0 +1,163 @@ +# USBNET - USB网卡功能 + + 提供USB网卡功能。 + +> 除高通BG和WiFi平台外其余平台均支持。 + +## 设置USB网卡工作类型 + +### `USBNET.set_worktype` + +```python +USBNET.set_worktype(type) +``` + +**参数描述:** + +- `type`-USBNET 工作类型,int类型,Type_ECM:ECM模式, Type_RNDIS:RNDIS模式。 + +**返回值描述:** + +`0`表示设置成功,`-1`表示设置失败。 + +> 重启生效 + +## 获取USB网卡工作类型 + +### `USBNET.get_worktype` + +```python +USBNET.get_worktype() +``` + +**返回值描述:** + +成功返回USBNET当前工作类型,失败返回整型`-1`;`1`表示ECM模式,`3 `表示 RNDIS模式。 + +## 获取USBNET当前状态 + +### `USBNET.get_status` + +```python +USBNET.get_status() +``` + +**返回值描述:** + +成功返回USBNET当前状态,失败返回整型`-1`;`0`表示未连接,`1`表示连接成功。 + +## 打开USB网卡 + +### `USBNET.open` + +```python +USBNET.open() +``` + +**返回值描述:** + +`0`表示打开成功,`-1`表示打开失败。 + +## 关闭USB网卡 + +### `USBNET.close` + +``` +USBNET.close() +``` + +**返回值描述:** + +`0`表示关闭成功,`-1`表示关闭失败。 + +**示例:** + +```python +from misc import USBNET +from misc import Power + +#work on ECM mode default +USBNET.open() + +USBNET.set_worktype(USBNET.Type_RNDIS) + +#reset the module +Power.powerRestart() + + +#After restart +from misc import USBNET + +#work on RNDIS mode +USBNET.open() +``` + +## 获取NAT使能情况 + +### `USBNET.getNat` + +```python +USBNET.getNat(simid, pid) +``` + +获取某一路网卡的NAT使能情况。 + +> 目前仅EC200U/EC600U/EC800G系列支持:
EC200U/EC600U系列使能NAT模式会导致使能的那一路pid无法进行IPv6拨号
EC800G系列使能NAT模式会导致使能的那一路pid的IPv4/IPv6均无法拨号 + +**参数描述:** + +- `simid`- int类型,范围0/1,目前仅支持`0`; +- `pid`- int类型,PDP索引,范围`1-7`。 + +**返回值描述:** + +成功:返回NAT使能情况,整型0/1,`0`:未使能NAT模式;`1`:使能NAT模式。 + +失败:返回整型`-1`。 + +**示例:** + +```python +from misc import USBNET +USBNET.getNat(0, 1) +0 +``` + +## NAT设置 + +### `USBNET.setNat` + +```python +USBNET.setNat(simid, pid, nat) +``` + +NAT设置,设置成功后重启生效(USBNET.set_worktype()接口调用的时候会使对应的nat值变为1,使得该pid开启NAT模式,所以在close USBnet后,可以使用该接口关闭NAT模式,使该pid的拨号功能正常)。 + +> 目前仅EC200U/EC600U/EC800G系列支持:
EC200U/EC600U系列使能NAT模式会导致使能的那一路pid无法进行IPv6拨号
EC800G系列使能NAT模式会导致使能的那一路pid的IPv4/IPv6均无法拨号 + +**参数描述:** + +- `simid`- int类型,范围0/1,目前仅支持`0`; +- `pid`- int类型,PDP索引,范围`1-7`; +- `nat`- int类型,范围:0/1,`0`:未使能NAT模式;`1`:使能NAT模式。 + +**返回值描述:** + +`0`表示设置成功,`-1`表示设置失败。 + +**示例:** + +```python +USBNET.setNat(0, 1, 0) +0 +``` + +## 常量 + +### `USBNET.Type_ECM` + +ECM工作模式 + +### `USBNET.Type_RNDIS` + +RNDIS工作模式 \ No newline at end of file diff --git a/docs/API_reference/zh/peripherals/misc.md b/docs/API_reference/zh/peripherals/misc.md new file mode 100644 index 0000000000000000000000000000000000000000..9afa97ac271eab61f1754789ed9fc11f4c7af538 --- /dev/null +++ b/docs/API_reference/zh/peripherals/misc.md @@ -0,0 +1,100 @@ +# misc- 其他 + + 提供关机、软件重启、PWM以及ADC相关功能。 + +## 分集天线配置接口功能 + +### `misc.antennaSecRXOffCtrl` + +```python +misc.antennaSecRXOffCtrl(*args) +``` + +分集天线配置、查询接口(EC200A系列支持该接口)。 + +**参数描述:** + +该接口为可变参形式: + 参数个数为0,查询:misc.antennaSecRXOffCtrl(); + 参数个数为1,配置:misc.antennaSecRXOffCtrl(SecRXOff_set)。 + +- `SecRXOff_set`-int类型,范围0/1, `0`:不关闭分集天线 `1`:关闭分集天线。 + +**返回值描述:** + +查询:成功返回分集天线配置,失败返回整型值`-1`; + +设置:成功返回整形`0`,失败返回整型值`-1`。 + +**示例:** + +```python +import misc + +misc.antennaSecRXOffCtrl() +0 +misc.antennaSecRXOffCtrl(1) +0 +misc.antennaSecRXOffCtrl() +1 +``` + +## 禁止网络灯功能 + +### `misc.net_light` + +```python +misc.net_light([arg]) +``` + +设置是否打开网络灯功能或查询网络灯是否打开。点此查看网络灯对应引脚。 + +> EC200A/EC600U/EC200U系列支持。 + +**参数描述:** + 传入参数时:设置网络灯功能是否打开;不传参数时:查询网络灯是否打开。 + +- `arg`-int类型,范围0/1,`0`:关闭网络灯功能;`1`:打开网络灯功能。 + +**返回值描述:** + +查询:成功返回网络灯是否打开,`0`:关闭,`1`:打开;未设置过返回整型值`-1`; + +设置:成功返回整形`0`,失败返回整型值`-1`。 + +> 设置重启生效;未设置过默认网络灯功能打开。 + +**示例:** + +```python +import misc +misc.net_light()#未设置过 +-1 +misc.net_light(0)#设置关闭网络灯后重启模组 +misc.net_light()#查询 +0 +misc.net_light(1)#设置打开网络灯后重启模组 +misc.net_light()#查询 +1 +``` + +**网络灯引脚:** + +| 系列 | 对应引脚 | +| ------ | ------------ | +| EC200A | PIN5,PIN6 | +| EC200U | PIN5,PIN6 | +| EC600U | PIN52,PIN54 | + +## Classes + +- [class PowerKey – PowerKey按键回调注册](./misc.PowerKey.md) +- [class PWM – 脉宽调制](./misc.PWM.md) +- [class ADC - 模数转换](./misc.ADC.md) +- [class USB– USB插拔检测](./misc.USB.md) + +## Submodules + +- [module Power – 关机以及软件重启](./misc.Power.md) + +- [module USBNET – USB网卡](./misc.USBNET.md) \ No newline at end of file diff --git a/docs/API_reference/zh/sidebar.yaml b/docs/API_reference/zh/sidebar.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b572a9bf3441b1d6d1b63188b8ba3ea7e062f6c0 --- /dev/null +++ b/docs/API_reference/zh/sidebar.yaml @@ -0,0 +1,246 @@ +items: +- label: Python标准库 + file: stdlib/README.md + items: + - label: uos - 基本系统服务 + file: stdlib/uos.md + - label: gc - 内存相关功能 + file: stdlib/gc.md + - label: ubinascii - 二进制与ASCII转换 + file: stdlib/ubinascii.md + - label: ucollections - 集合和容器类型 + file: stdlib/ucollections.md + - label: urandom - 生成随机数 + file: stdlib/urandom.md + - label: math - 数学运算 + file: stdlib/math.md + - label: usocket - socket模块 + file: stdlib/usocket.md + - label: uio - 输入输出流 + file: stdlib/uio.md + - label: ustruct - 打包和解压原始数据类型 + file: stdlib/ustruct.md + - label: ujson - JSON编码和解码 + file: stdlib/ujson.md + - label: utime - 时间相关功能 + file: stdlib/utime.md + - label: sys - 系统相关功能 + file: stdlib/sys.md + - label: uzlib - zlib解压缩 + file: stdlib/uzlib.md + - label: _thread - 多线程 + file: stdlib/_thread.md + - label: uhashlib - 哈希算法 + file: stdlib/uhashlib.md + - label: ure - 正则表达式 + file: stdlib/ure.md +- label: 蜂窝通信 + file: iotlib/README.md + items: + - label: dataCall - 拨号 + file: iotlib/dataCall.md + - label: sim - SIM卡功能 + file: iotlib/sim.md + - label: sms - 短信功能 + file: iotlib/sms.md + - label: voiceCall - 电话功能 + file: iotlib/voiceCall.md + - label: net - 网络相关功能 + file: iotlib/net.md + - label: checkNet - 网络就绪检测 + file: iotlib/checkNet.md + - label: ussd - USSD功能 + file: iotlib/ussd.md +- label: 外设接口 + file: peripherals/README.md + items: + - label: machine - 硬件相关功能 + file: peripherals/machine.md + items: + - label: Pin - 控制I/O引脚 + file: peripherals/machine.Pin.md + - label: UART - 串口通信 + file: peripherals/machine.UART.md + - label: Timer - 硬件定时器 + file: peripherals/machine.Timer.md + - label: ExtInt - 外部中断 + file: peripherals/machine.ExtInt.md + - label: RTC - 实时时钟 + file: peripherals/machine.RTC.md + - label: I2C - I2C通信 + file: peripherals/machine.I2C.md + - label: I2C_simulation - 模拟I2C通信 + file: peripherals/machine.I2C_simulation.md + - label: SPI - SPI通信 + file: peripherals/machine.SPI.md + - label: SoftSPI - 模拟SPI通信 + file: peripherals/machine.SoftSPI.md + - label: LCD - LCD显示屏 + file: peripherals/machine.LCD.md + - label: WDT - 看门狗定时器 + file: peripherals/machine.WDT.md + - label: KeyPad - 矩阵键盘 + file: peripherals/machine.KeyPad.md + - label: OneWire - 单总线 + file: peripherals/machine.OneWire.md + - label: misc - 杂项功能 + file: peripherals/misc.md + items: + - label: Power - 关机和重启 + file: peripherals/misc.Power.md + - label: PowerKey - PowerKey按键回调注册 + file: peripherals/misc.PowerKey.md + - label: PWM - 脉宽调制 + file: peripherals/misc.PWM.md + - label: ADC - 模数转换 + file: peripherals/misc.ADC.md + - label: USB - USB插拔检测 + file: peripherals/misc.USB.md + - label: USBNET - USB网卡 + file: peripherals/misc.USBNET.md + - label: ethernet - 以太网相关功能 + file: peripherals/ethernet.md + items: + - label: W5500 - W5500驱动 + file: peripherals/ethernet.W5500.md + - label: DM9051 - DM9051驱动 + file: peripherals/ethernet.DM9051.md + - label: CH395 - CH395驱动 + file: peripherals/ethernet.CH395.md + - label: YT8512H - YT8512H驱动 + file: peripherals/ethernet.YT8512H.md +- label: 系统功能 + file: syslib/README.md + items: + - label: modem - 设备相关 + file: syslib/modem.md + - label: example - 执行python脚本 + file: syslib/example.md + - label: atcmd - 发送AT指令功能 + file: syslib/atcmd.md + - label: log - 日志输出 + file: syslib/log.md + - label: system - 环境配置 + file: syslib/system.md + - label: Queue - 消息队列 + file: syslib/Queue.md + - label: sys_bus - 会话总线 + file: syslib/sys_bus.md + - label: osTimer - os定时器 + file: syslib/osTimer.md + - label: fota - 固件升级相关功能 + file: syslib/fota.md + - label: app_fota - 用户文件升级相关功能 + file: syslib/app_fota.md + - label: ql_fs - 高级文件操作 + file: syslib/ql_fs.md + - label: securedata - 数据安全区 + file: syslib/securedata.md + - label: pm - 低功耗 + file: syslib/pm.md + items: + - label: WakeUp - 唤醒中断 + file: syslib/pm.WakeUp.md +- label: 多媒体 + file: medialib/README.md + items: + - label: camera - 摄像扫码 + file: medialib/camera.md + items: + - label: CamPreview - 摄像头预览 + file: medialib/camera.CamPreview.md + - label: CamDecoder - 摄像头扫码 + file: medialib/camera.CamDecoder.md + - label: CamCapture - 摄像头拍照 + file: medialib/camera.CamCapture.md + - label: audio - 音频播放 + file: medialib/audio.md + items: + - label: TTS - 文本到语音播放 + file: medialib/audio.TTS.md + - label: Audio - 音频播放 + file: medialib/audio.Audio.md + - label: Record - 录音 + file: medialib/audio.Record.md + - label: PCM - 音频数据编码 + file: medialib/audio.PCM.md + - label: qrcode - 二维码显示 + file: medialib/qrcode.md +- label: Wi-Fi通信 + file: wifilib/README.md + items: + - label: WLAN - 无线网络控制 + file: wifilib/WLAN.md + - label: ESP8266 - 乐鑫ESP8266驱动 + file: wifilib/WLAN.ESP8266.md + - label: ASR5803W - ASR5803W驱动 + file: wifilib/WLAN.ASR5803W.md +- label: 蓝牙通信 + file: btlib/README.md + items: + - label: ble - 低功耗蓝牙相关功能 + file: btlib/ble.md + - label: bt - 经典蓝牙相关功能 + file: btlib/bt.md +- label: 网络应用 + file: networklib/README.md + items: + - label: ussl - SSL算法 + file: networklib/ussl.md + - label: request - HTTP客户端 + file: networklib/request.md + - label: umqtt - MQTT客户端 + file: networklib/umqtt.md + - label: uwebsocket - websocket客户端 + file: networklib/uwebsocket.md + - label: uping - 发送ping包 + file: networklib/uping.md + - label: ntptime - 网络时间同步 + file: networklib/ntptime.md + - label: ftplib - ftp 客户端 + file: networklib/ftp.md + - label: lwm2m - 轻量级 M2M 协议 + file: networklib/Lwm2m.md +- label: 定位应用 + file: gnsslib/README.md + items: + - label: gnss - 外置GNSS + file: gnsslib/gnss.md + - label: quecgnss - 内置GNSS + file: gnsslib/quecgnss.md + - label: cellLocator - 基站定位 + file: gnsslib/cellLocator.md + - label: wifilocator - WIFI定位 + file: gnsslib/wifilocator.md + - label: wifiScan - WiFi扫描 + file: gnsslib/wifiScan.md +- label: AI 聊天机器人 + file: ailib/README.md + items: + - label: TiktokRTC - 豆包火山 RTC 平台 + file: ailib/TiktokRTC.md +- label: IoT 平台 + file: cloudlib/README.md + items: + - label: aLiYun - 阿里 IoT 平台 + file: cloudlib/aLiYun.md + - label: TXyun- 腾讯 IoT 平台 + file: cloudlib/TenCentYun.md + - label: Aws- 亚马逊 IoT 平台 + file: cloudlib/aws.md + - label: Azure - Azure IoT 平台 + file: cloudlib/azure.md + - label: Aws S3 – AWS S3 客户端 + file: cloudlib/aws_s3.md +- label: 行业应用 + file: industry/README.md + items: + - label: POC - 公网对讲机 + file: industry/poc.md +- label: 开源组件 + file: componentlib/README.md + items: + - label: uasyncio - 协程 + file: componentlib/uasyncio.md +- label: 错误码 + file: errcode/README.md diff --git a/docs/API_reference/zh/stdlib/README.md b/docs/API_reference/zh/stdlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d862ba6bf9b53f1447670eee2a1221ae3c600bc --- /dev/null +++ b/docs/API_reference/zh/stdlib/README.md @@ -0,0 +1,33 @@ +# QuecPython 标准库 + +> - QuecPython 提供了内置模块,这些模块反映了 Python 标准库(例如 `os`,`time`),以及 QuecPython 特定的模块(例如 `bluetooth`,`machine`)。

+> - 大多数标准库模块实现了等效的 Python 模块,并在少数情况下提供一些特定于 QuecPython 的扩展模块(例如`array`,`os`)。

+> - 为了允许扩展,内置模块可以从加载到设备上的 Python 代码扩展而来。 + +本文描述了 QuecPython 内置的模块(函数和类库)。 + +通过在REPL上输入以下代码,以查看所有可被导入的内置库: + +```python +help('modules') +``` + +## QuecPython 标准库列表 + +- [uos - 基本系统服务](./uos.md) +- [gc - 内存相关功能](./gc.md) +- [ubinascii - 二进制与ASCII转换](./ubinascii.md) +- [ucollections - 集合和容器类型](./ucollections.md) +- [urandom - 生成随机数](./urandom.md) +- [math - 数学运算](./math.md) +- [usocket - socket模块](./usocket.md) +- [uio - 输入输出流](./uio.md) +- [ustruct - 打包和解压原始数据类型](./ustruct.md) +- [ujson - JSON编码和解码](./ujson.md) +- [utime - 时间相关功能](./utime.md) +- [sys - 系统相关功能](./sys.md) +- [uzlib - zlib解压缩](./uzlib.md) +- [_thread - 多线程](./_thread.md) +- [uhashlib - 哈希算法](./uhashlib.md) +- [ure - 正则表达式](./ure.md) + diff --git a/docs/API_reference/zh/stdlib/_thread.md b/docs/API_reference/zh/stdlib/_thread.md new file mode 100644 index 0000000000000000000000000000000000000000..21883f07368b577848db4855c3cf8b4cd0a59a77 --- /dev/null +++ b/docs/API_reference/zh/stdlib/_thread.md @@ -0,0 +1,289 @@ +# _thread- 多线程 + +`_thread` 模块包含线程操作相关的功能。提供创建、删除线程的方法,提供互斥锁、信号量相关的接口。 + +**示例:** + +```python +import _thread +import log +import utime + + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +thread_log = log.getLogger("Thread") + +a = 0 +state = 1 +state1 = 1 +# 创建一个lock的实例 +lock = _thread.allocate_lock() + +def th_func(delay, id): + global a + global state,state1 + while True: + lock.acquire() # 获取锁 + if a >= 10: + thread_log.info('thread %d exit' % id) + lock.release() # 释放锁 + if id == 1: + state = 0 + else: + state1 = 0 + break + a += 1 + thread_log.info('[thread %d] a is %d' % (id, a)) + lock.release() # 释放锁 + utime.sleep(delay) + +def th_func1(): + while True: + thread_log.info('thread th_func1 is running') + utime.sleep(1) + +if __name__ == '__main__': + for i in range(2): + _thread.start_new_thread(th_func, (i + 1, i)) # 创建一个线程,当函数无参时传入空的元组 + + thread_id = _thread.start_new_thread(th_func1, ()) # 创建一个线程,当函数无参时传入空的元组 + + while state or state1: + utime.sleep(1) + pass + + _thread.stop_thread(thread_id) # 删除线程 + _thread.delete_lock(lock) # 删除锁 + thread_log.info('thread th_func1 is stopped') +``` + +## 线程相关功能 + +### `_thread.get_ident` + +```python +_thread.get_ident() +``` + +获取当前线程号。 + +**返回值描述:** + +返回当前线程号。 + + +### `_thread.stack_size` + +```python +_thread.stack_size(size) +``` + +设置或获取创建新线程使用的栈大小(以字节为单位),取决于参数`size`是否提供。默认为8448字节,最小8192字节。 + +**参数描述:** + +- `size`- 提供该参数,用于创建新线程使用的栈大小。 + +**返回值描述:** + +当参数`size`没有提供时,返回创建新线程使用的栈大小。 + +### `_thread.start_new_thread` + +```python +_thread.start_new_thread(function, args) +``` + +创建一个新线程。接收执行函数和被执行函数参数,当 function 函数无参时传入空的元组。 + +**参数描述:** + +- `function`- 线程执行函数。函数参数由`args`传入。 +- `args`- 线程执行函数的参数,类型为元组。当 `function` 函数无参时传入空的元组。 + +**返回值描述:** + +返回创建的新线程的id。 + +**示例**: + +```python +import _thread +import utime + +def th_func(test1, test2, test3): + while True: + print('param1 %d, param2 %d, param3 %d' % (test1, test2, test3)) + utime.sleep(1) + +def th_func1(): + while True: + print('thread th_func1 is running') + utime.sleep(1) + +_thread.start_new_thread(th_func, (1, 2, 3))# 创建一个线程 + +_thread.start_new_thread(th_func1, ()) # 创建一个线程,当函数无参时传入空的元组 +``` + + + +### `_thread.stop_thread` + +```python +_thread.stop_thread(thread_id) +``` + +停止并删除一个线程。不可停止或删除主线程。 + +**参数描述:** + +- `thread_id`- 为创建线程时返回的线程id,为0时则停止并删除当前线程。 + +### `_thread.get_heap_size` + +```python +_thread.get_heap_size() +``` + +获取系统heap内存剩余大小。 + +**返回值描述:** + +返回系统heap内存剩余大小(以字节为单位)。 + +## 互斥锁相关功能 + +### `_thread.allocate_lock` + +```python +_thread.allocate_lock() +``` + +创建一个互斥锁对象。 + +**返回值描述:** + +返回创建的互斥锁对象。 + +**示例**: + +```python +import _thread +lock = _thread.allocate_lock() +``` + +### `lock.acquire` + +```python +lock.acquire() +``` + +获取锁。 + +**返回值描述:** + +成功返回True,失败返回False。 + +### `lock.release` + +```python +lock.release() +``` + +释放锁。 + +### `lock.locked` + +```python +lock.locked() +``` + +返回锁的状态。 + +**返回值描述:** + +True表示被某个线程获取,False则表示没有。 + +### `_thread.delete_lock` + +```python +_thread.delete_lock(lock) +``` + +删除已经创建的互斥锁。 + +**参数描述:** + +- `lock`- 为创建时返回的互斥锁对象。 + +## 信号量相关功能 + +### `_thread.allocate_semphore` + +```python +_thread.allocate_semphore(initcount) +``` + +创建一个信号量对象。 + +**参数描述:** + +`initcount`- 为信号量的计数初始值,也是最大值。 + +**返回值描述:** + +返回创建的信号量对象。 + +**示例**: + +``` +import _thread +semphore = _thread.allocate_semphore(1) +``` + +### `semphore.acquire` + +```python +semphore.acquire() +``` + +获取信号量。 + +**返回值描述:** + +成功返回True,失败返回False。 + +### `semphore.release` + +```python +semphore.release() +``` + +释放信号量。 + +### `semphore.getCnt` + +```python +semphore.getCnt() +``` + +获取信号量计数最大值和当前剩余计数值。 + +**返回值描述:** + +`(maxCnt, curCnt)`-元组:maxCnt为计数最大值,curCnt为当前剩余计数值。 + +### `_thread.delete_semphore` + +```python +_thread.delete_semphore(semphore) +``` + +删除已经创建的信号量。 + +**参数描述:** + +`semphore`- 为创建时返回的信号量对象。 + diff --git a/docs/API_reference/zh/stdlib/gc.md b/docs/API_reference/zh/stdlib/gc.md new file mode 100644 index 0000000000000000000000000000000000000000..b151b44cb4cfcd35c71cd912bd25d805ecc5ce18 --- /dev/null +++ b/docs/API_reference/zh/stdlib/gc.md @@ -0,0 +1,68 @@ +# gc-内存相关功能 + +`gc` 模块实现内存垃圾回收机制,该模块实现了CPython模块相应模块的子集。更多信息请参阅CPython文档:[gc](https://docs.python.org/3.5/library/gc.html#module-gc) + +## 内存回收相关功能 + +### `gc.enable` + +```python +gc.enable() +``` + +启用自动回收内存碎片机制。 + +### `gc.disable` + +```python +gc.disable() +``` + +禁用自动回收内存碎片机制。 + +### `gc.isenabled` + +```python +gc.isenabled() +``` + +查询是否启动了自动回收内存碎片机制。 + +**返回值描述:** + +True-已启动自动回收内存碎片机制,False-未启动自动回收内存碎片机制。 + +### `gc.collect` + +```python +gc.collect() +``` + +主动回收内存碎片。 + +## 内存查询相关功能 + +### `gc.mem_alloc` + +```python +gc.mem_alloc() +``` + +查询已申请的内存大小。 + +**返回值描述:** + +返回已申请的内存大小,单位字节。 + +### `gc.mem_free` + +```python +gc.mem_free() +``` + +查询剩余可用的内存大小。 + +**返回值描述:** + +返回剩余可用的内存大小,单位字节。 + diff --git a/docs/API_reference/zh/stdlib/math.md b/docs/API_reference/zh/stdlib/math.md new file mode 100644 index 0000000000000000000000000000000000000000..a79d4dacb7ea5deafc4d690e353d2c4e10495cdc --- /dev/null +++ b/docs/API_reference/zh/stdlib/math.md @@ -0,0 +1,806 @@ +# math - 数学运算 + +math 模块提供数学运算函数。该模块实现相应CPython模块的子集。更多信息请参阅阅CPython文档:[math](https://docs.python.org/3.5/library/math.html#module-math) + +## 返回x的y次方 + +### `math.pow` + +```python +math.pow(x, y) +``` + +返回x的y次方 + +**参数描述** + +* `x`:任意实数类型 +* `y`:任意实数类型 + +**返回值描述** +浮点数:`x`的 `y`次方 + +**示例:** + +``` +>>> import math +>>> math.pow(2, 3) +8.0 +``` + +## 返回x的反余弦弧度值 + +### `math.acos` + +```python +math.acos(x) +``` + +返回x的反余弦弧度值 + +**参数描述** + +* `x`:任意实数类型,是-1~1之间的数,包括-1和1,如果小于-1或者大于1,会产生错误。 + +**返回值描述** +浮点数:`x`的反余弦弧度值 + +**示例:** + +``` +>>> import math +>>> math.acos(0.6) +0.9272952 +``` + +## 返回x的反正弦弧度值 + +### `math.asin` + +```python +math.asin(x) +``` + +返回x的反正弦弧度值 + +**参数描述** + +* `x`:任意实数类型,是-1~1之间的数,包括-1和1,如果小于-1或者大于1,会产生错误。 + +**返回值描述** +浮点数:`x`的反正弦弧度值 + +**示例**: + +``` +>>> import math +>>> math.asin(-1) +-1.570796 +``` + +## 返回x的反正切弧度值 + +### `math.atan` + +```python +math.atan(x) +``` + +返回x的反正切弧度值 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +浮点数:`x`的反正切弧度值 + +**示例:** + +``` +>>> import math +>>> math.atan(-8) +-1.446441 +>>> math.atan(6.4) +1.4158 +``` + +## 返回给定的 X 及 Y 坐标值的反正切值 + +### `math.atan2` + +```python +math.atan2(x, y) +``` + +返回给定的 X 及 Y 坐标值的反正切值 + +**参数描述** + +* `x`:任意实数类型 +* `y`:任意实数类型 + +**返回值描述** +浮点数:坐标 (`x` ,`y`)的反正切值 + +**示例:** + +``` +>>> import math +>>> math.atan2(-0.50,0.48) +-0.8058035 +>>> math.atan2(7, 9) +0.6610432 +``` + +## 返回数字的上入整数 + +### `math.ceil` + +```python +math.ceil(x) +``` + +返回数字的上入整数 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +整数:`x`:大于等于入参的最小整数 + +**示例:** + +``` +>>> import math +>>> math.ceil(4.1) +5 +``` + +## 把y的正负号加到x前面 + +### `math.copysign` + +```python +math.copysign(x, y) +``` + +把y的正负号加到x前面 + +**参数描述** + +* `x`:任意实数类型 +* `y`:任意实数类型 + +**返回值描述** +浮点数,把 `y`的正负号加到 `x`前面 + +**示例:** + +``` +>>> import math +>>> math.copysign(5, 0) +5.0 +>>> math.copysign(5, -4) +-5.0 +>>> math.copysign(5, 9) +5.0 +``` + +## 返回x的弧度的余弦值 + +### `math.cos` + +```python +math.cos(x) +``` + +返回x的弧度的余弦值 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +浮点数,`x`的弧度的余弦值,范围-1~1之间 + +**示例:** + +```python +>>> import math +>>> math.cos(3) +-0.9899925 +``` + +## 将弧度转换为角度 + +### `math.degrees` + +```python +math.degrees(x) +``` + +将弧度转换为角度 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +浮点数,弧度 `x`转换为角度 + +**示例:** + +``` +>>> import math +>>> math.degrees(5) +286.4789 +>>> math.degrees(math.pi/2) +90.0 +``` + +## 数学常量 `e` + +### `math.e` + +数学常量 `e`,`e`即自然常数。 + +## 返回e的x次幂 + +### `math.exp` + +```python +math.exp(x) +``` + +返回e的x次幂 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +浮点数,`e`的 `x`次幂 + +**示例:** + +``` +>>> import math +>>> math.exp(1) +2.718282 +>>> print(math.e) +2.718282 +``` + +## 返回数字的绝对值 + +### `math.fabs` + +```python +math.fabs(x) +``` + +返回数字的绝对值 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +浮点数,`x`的绝对值 + +**示例:** + +``` +>>> import math +>>> math.fabs(-3.88) +3.88 +``` + +## 返回数字的下舍整数 + +### `math.floor` + +```python +math.floor(x) +``` + +返回数字的下舍整数 + +**参数描述** + +* `x`:任意实数类型 + +**返回值描述** +整数,`x`:小于等于入参的最大整数 + +**示例:** + +``` +>>> import math +>>> math.floor(8.7) +8 +>>> math.floor(9) +9 +>>> math.floor(-7.6) +-8 +``` + +## 返回x/y的余数 + +### `math.fmod` + +```python +math.fmod(x, y) +``` + +返回x/y的余数 + +**参数描述** + +* `x`:任意实数类型 +* `y`:任意实数类型 + +**返回值描述** + `x`/`y`的余数,浮点数 + +**示例:** + +``` +>>> import math +>>> math.fmod(15, 4) +3.0 +>>> math.fmod(15, 3) +0.0 +``` + +## 返回由x的小数部分和整数部分组成的元组 + +### `math.modf` + +```python +math.modf(x) +``` + +返回由x的小数部分和整数部分组成的元组。 + +**参数描述** + +* `x`:任意实数类型 + + +**返回值描述** + `x`/`y`的余数,浮点数 + +**示例:** + +``` +>>> import math +>>> math.modf(17.592) +(0.5919991, 17.0) +``` + +## 返回一个元组(m,e) + +### `math.frexp` + +```python +math.frexp(x) +``` + +返回一个元组(m,e) + +**参数描述** + +* `x`:浮点数 + +**返回值描述** +返回一个元组 `(m,e)`, 以 (m, e) 对的形式返回 x 的尾数和指数。 m 是一个浮点数, e 是一个整数,正好是 x == m * 2**e 。 如果 x 为零,则返回 (0.0, 0) ,否则返回 0.5 <= abs(m) < 1 + +**示例:** + +``` +>>> import math +>>> math.frexp(52) +(0.8125, 6) +``` + +## 判断 x 是否为有限数 + +### `math.isfinite` + +```python +math.isfinite(x) +``` + +判断 x 是否为有限数 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +判断 `x` 是否为有限数,是则返回 `True`,否则返回 `False`。 + +**示例:** + +``` +>>> import math +>>> math.isfinite(8) +True +``` + +## 判断是否无穷大或负无穷大 + +### `math.isinf` + +```python +math.isinf(x) +``` + +判断是否无穷大或负无穷大 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +如果 `x`是正无穷大或负无穷大,则返回 `True`,否则返回 `False`。 + +**示例:** + +``` +>>> import math +>>> math.isinf(123) +False +``` + +## 判断是否数字 + +### `math.isnan` + +```python +pymath.isnan(x) +``` + +判断是否非数字(NaN) + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +如果 `x`为非数字,返回 `True`,否则返回 `False`。 + +**示例:** + +``` +>>> import math +>>> math.isnan(23) +False +``` + +## 返回x*(2**i)的值 + +### `math.ldexp` + +```python +math.ldexp(x, exp) +``` + +**返回x*(2^i)的值** + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +浮点数,返回 `x`*(2**i)的值。 + +**示例:** + +``` +>>> import math +>>> math.ldexp(2, 1) +4.0 +``` + +## 返回x的自然对数 + +### `math.log` + +```python +math.log(x) +``` + +返回x的自然对数 + +**参数描述** + +* `x`,任意实数类型,小于0会报错 + +**返回值描述** + +浮点数,返回 `x`的自然对数 + +**示例:** + +``` +>>> import math +>>> math.log(2) +0.6931472 +``` + +## 数学常量 pi + +### `math.pi` + +数学常量 pi(圆周率,一般以π来表示)。 + +## 将角度转换为弧度 + +### `math.radians` + +```python +math.radians(x) +``` + +将角度转换为弧度 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +浮点数,将角度 `x`转换为弧度 + +**示例:** + +``` +>>> import math +>>> math.radians(90) +1.570796 +``` + +## 返回x弧度的正弦值 + +### `math.sin` + +```python +math.sin(x) +``` + +返回x弧度的正弦值 + +**参数描述** + +* `x`,任意实数 + +**返回值描述** + +返回 `x`弧度的正弦值,数值在 -1 到 1 之间。 + +**示例:** + +``` +>>> import math +>>> math.sin(-18) +0.7509873 +>>> math.sin(50) +-0.2623749 +``` + +## 返回数字x的平方根 + +### `math.sqrt` + +```python +math.sqrt(x) +``` + +返回x的平方根 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +返回数字 `x`的平方根,返回值为浮点数。 + +**示例:** + +``` +>>> import math +>>> math.sqrt(4) +2.0 +>>> math.sqrt(7) +2.645751 +``` + +## 返回 x 弧度的正切值 + +### `math.tan` + +```python +math.tan(x) +``` + +返回 x 弧度的正切值 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +返回 `x` 弧度的正切值,数值在 -1 到 1 之间,为浮点数。 + +**示例:** + +``` +>>> import math +>>> math.tan(9) +-0.4523157 +``` + +## 返回x的整数部分 + +### `math.trunc` + +```python +math.trunc(x) +``` + +返回x的整数部分 + +**参数描述** + +* `x`,任意实数类型 + +**返回值描述** + +返回x的整数部分,为整数。 + +**示例:** + +``` +>>> import math +>>> math.trunc(7.123) +7 +``` + +**使用示例** + +```python +# 数学运算math函数示例 + +import math +import log +import utime + + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_Math_example" +PROJECT_VERSION = "1.0.0" + + +if __name__ == '__main__': + # 设置日志输出级别 + log.basicConfig(level=log.INFO) + math_log = log.getLogger("Math") + + # x**y运算后的值 + result = math.pow(2,3) + math_log.info(result) + # 8.0 + + # 取大于等于x的最小的整数值,如果x是一个整数,则返回x + result = math.ceil(4.12) + math_log.info(result) + # 5 + + # 把y的正负号加到x前面,可以使用0 + result = math.copysign(2,-3) + math_log.info(result) + # -2.0 + + # 求x的余弦,x必须是弧度 + result = math.cos(math.pi/4) + math_log.info(result) + # 0.7071067811865476 + + # 把x从弧度转换成角度 + result = math.degrees(math.pi/4) + math_log.info(result) + # 45.0 + + # e表示一个常量 + result = math.e + math_log.info(result) + # 2.718281828459045 + + # exp()返回math.e(其值为2.71828)的x次方 + result = math.exp(2) + math_log.info(result) + # 7.38905609893065 + + # fabs()返回x的绝对值 + result = math.fabs(-0.03) + math_log.info(result) + # 0.03 + + # floor()取小于等于x的最大的整数值,如果x是一个整数,则返回自身 + result = math.floor(4.999) + math_log.info(result) + # 4 + + # fmod()得到x/y的余数,其值是一个浮点数 + result = math.fmod(20,3) + math_log.info(result) + # 2.0 + + # frexp()返回一个元组(m,e),其计算方式为:x分别除0.5和1,得到一个值的范围,2e的值在这个范围内,e取符合要求的最大整数值,然后x/(2e),得到m的值。如果x等于0,则m和e的值都为0,m的绝对值的范围为(0.5,1)之间,不包括0.5和1 + result = math.frexp(75) + math_log.info(result) + # (0.5859375, 7) + + # isfinite()如果x不是无穷大的数字,则返回True,否则返回False + result = math.isfinite(0.1) + math_log.info(result) + # True + + # isinf()如果x是正无穷大或负无穷大,则返回True,否则返回False + result = math.isinf(234) + math_log.info(result) + # False + + # isnan()如果x不是数字True,否则返回False + result = math.isnan(23) + math_log.info(result) + # False + + # ldexp()返回x*(2**i)的值 + result = math.ldexp(5,5) + math_log.info(result) + # 160.0 + + # modf()返回由x的小数部分和整数部分组成的元组 + result = math.modf(math.pi) + math_log.info(result) + # (0.14159265358979312, 3.0) + + # pi:数字常量,圆周率 + result = math.pi + math_log.info(result) + # 3.141592653589793 + + # sin()求x(x为弧度)的正弦值 + result = math.sin(math.pi/4) + math_log.info(result) + # 0.7071067811865476 + + # sqrt()求x的平方根 + result = math.sqrt(100) + math_log.info(result) + # 10.0 + + # tan()返回x(x为弧度)的正切值 + result = math.tan(math.pi/4) + math_log.info(result) + # 0.9999999999999999 + + # trunc()返回x的整数部分 + result = math.trunc(6.789) + math_log.info(result) + # 6 + +``` diff --git a/docs/API_reference/zh/stdlib/sys.md b/docs/API_reference/zh/stdlib/sys.md new file mode 100644 index 0000000000000000000000000000000000000000..3bb3bf88275a28f0fe626055aa7effc440e71448 --- /dev/null +++ b/docs/API_reference/zh/stdlib/sys.md @@ -0,0 +1,106 @@ +# sys - 系统相关功能 + +> 新架构代码升级了MPY的版本,sys变更为usys。导入模块时建议使用以下方式进行导入 + +```python +try: + import usys as sys +except ImportError: + import sys +``` + +## 常数说明 + +### `sys.argv` + +当前程序启动的可变参数列表。 + +### `sys.byteorder` + +字节顺序 (‘little’ - 小端, ‘big’ - 大端)。 + +### `sys.implementation` + +返回当前microPython版本信息。对于MicroPython,它具有以下属性: + +- name - 字符串“ micropython” + +- version - 元组(主要,次要,微型),例如(1、7、0) + +- _mpy - mpy文件的版本信息,解析方法如下,mpy_cross生成mpy时需要与此版本信息相适配 + +```python +import sys +sys_mpy = sys.implementation._mpy +arch = [None, 'x86', 'x64', + 'armv6', 'armv6m', 'armv7m', 'armv7em', 'armv7emsp', 'armv7emdp', + 'xtensa', 'xtensawin'][sys_mpy >> 10] +print('mpy version:', sys_mpy & 0xff) +print('mpy sub-version:', sys_mpy >> 8 & 3) +print('mpy flags:', end='') +if arch: + print(' -march=' + arch, end='') +print() +``` + +建议使用此对象来将MicroPython与其他Python实现区分开。 + +### `sys.maxsize` + +本机整数类型可以在当前平台上保留的最大值,如果它小于平台最大值,则为MicroPython整数类型表示的最大值(对于不支持长整型的MicroPython端口就是这种情况)。 + +### `sys.modules` + +以字典形式返回当前Python环境中已经导入的模块。 + +### `sys.platform` + +MicroPython运行的平台。 + +### `sys.stdin` + +标准输入(默认是USB虚拟串口,可选其他串口)。 + +### `sys.stdout` + +标准输出(默认是USB虚拟串口,可选其他串口)。 + +### `sys.version` + +MicroPython 版本,字符串格式。 + +### `sys.version_info` + +MicroPython 版本,整数元组格式。 + +## **方法** + +### `sys.exit` + +```python +sys.exit(retval=0) +``` + +使用给定的参数退出当前程序。 + +**参数描述** + +* `retval`,int型,退出参数 + +**返回值描述** + +该函数会引发 `SystemExit`退出。如果给定了参数,则将其值作为参数赋值给 `SystemExit`。 + +### `sys.print_exception` + +```python +sys.print_exception(exc, file=sys.stdout) +``` + +打印异常到文件对象,默认是 sys.stdout,即输出异常信息的标准输出。 + +**参数描述** + +* `exc`,exception对象 + +* `file`,指定输出文件,默认为sys.stdout diff --git a/docs/API_reference/zh/stdlib/ubinascii.md b/docs/API_reference/zh/stdlib/ubinascii.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6460067b182c7dc0848c98382c99ba38d6fd39 --- /dev/null +++ b/docs/API_reference/zh/stdlib/ubinascii.md @@ -0,0 +1,68 @@ +# ubinascii - 二进制与ASCII转换 + + +该模块实现了二进制数据与各种ASCII编码之间的转换(双向)。该模块实现相应CPython模块的子集,更多信息请参阅阅CPython文档:[binascii](https://docs.python.org/3.5/library/binascii.html#module-binascii) + +## 解码base64编码的数据 + +### `ubinascii.a2b_base64` + +```python +ubinascii.a2b_base64(data) +``` + +解码base64编码的数据,会自动忽略输入中的无效字符,返回 bytes 对象。 + +## 以base64格式编码二进制数据 + +### `ubinascii.b2a_base64` + +```python +ubinascii.b2a_base64(data) +``` + +以base64格式编码二进制数据,返回编码数据。后面跟换行符,作为 bytes 对象。 + +## 将二进制数据转换为十六进制字符串表示 + +### `ubinascii.hexlify` + +```python +ubinascii.hexlify(data, [sep]) +``` + +将二进制数据转换为十六进制字符串表示。 + +**示例:** + +```python +>>> import ubinascii +# 没有sep参数 +>>> ubinascii.hexlify('\x11\x22123') +b'1122313233' +>>> ubinascii.hexlify('abcdfg') +b'616263646667' +# 指定了第二个参数sep,它将用于分隔两个十六进制数 +>>> ubinascii.hexlify('\x11\x22123', ' ') +b'11 22 31 32 33' +>>> ubinascii.hexlify('\x11\x22123', ',') +b'11,22,31,32,33' +``` + +## 将十六进制形式的字符串转换成二进制形式的字符串表示 + +### `ubinascii.unhexlify` + +```python +ubinascii.unhexlify(data) +``` + +将十六进制形式的字符串转换成二进制形式的字符串表示。 + +**示例:** + +```python +>>> import ubinascii +>>> ubinascii.unhexlify('313222') +b'12"' +``` diff --git a/docs/API_reference/zh/stdlib/ucollections.md b/docs/API_reference/zh/stdlib/ucollections.md new file mode 100644 index 0000000000000000000000000000000000000000..c76570fdd18df244afc70c4deb9048e6b177ae62 --- /dev/null +++ b/docs/API_reference/zh/stdlib/ucollections.md @@ -0,0 +1,95 @@ + +# ucollections - 集合和容器类型 + +`ucollections`模块可以创建一个新的容器类型,用于保存各种对象。该模块实现了CPython模块相应模块的子集。更多信息请参阅CPython文档:[collections](https://docs.python.org/3/library/collections.html) + +## ucollections方法 +### `ucollections.namedtuple` + +```python +mytuple = ucollections.namedtuple(name, fields) +``` + +创建一个具有特定名称和一组字段的新`namedtuple`容器类型,`namedtuple`是元组的子类,允许通过索引来访问它的字段。 + +**参数描述:** + +- `name` - str类型,表示新建容器的类型名称 +- `fields` - tuple类型,表示新创建容器类型包含子类型的字段 + +**示例:** + +```python +>>> import ucollections +>>> mytuple = ucollections.namedtuple("mytuple", ("id", "name")) +>>> t1 = mytuple(1, "foo") +>>> t2 = mytuple(2, "bar") +>>> print(t1.name) +foo +``` + +### `ucollections.deque` + +```python +ucollections.deque(iterable, maxlen, flag) +``` + +创建`deque`双向队列 + +**参数描述:** + +- `iterable` - tuple类型,必须是一个空元组 +- `maxlen` - int类型,表示指定maxlen并将双端队列限制为此最大长度 +- `flag` - int类型,可选参数;`0`(默认):不检查队列是否溢出,达到最大长度时继续append会丢弃之前的值 ,`1`:当队列达到最大设定长度会抛出IndexError: full + +**返回值描述:** + +- deque对象 + + + +## deque对象方法 + +### `deque.append` + +```python +deque.append(data) +``` + +往队列中插入值。 + +**参数描述:** + +- `data` - 基本数据类型,表示需要添加到队列的数值 + + + +### `deque.popleft` + +```python +deque.popleft() +``` + +从`deque`的左侧移除并返回移除的数据。如果`deque`为空,会引起索引错误 + +**返回值描述:** + +- 返回pop出的值 + +**示例** + +```python +from ucollections import deque + +>>> dq = deque((),5) +>>> dq.append(1) +>>> dq.append(['a']) +>>> dq.append('a') + +>>> dq.popleft() +1 +>>> dq.popleft() +['a'] +>>> dq.popleft() +'a' +``` \ No newline at end of file diff --git a/docs/API_reference/zh/stdlib/uhashlib.md b/docs/API_reference/zh/stdlib/uhashlib.md new file mode 100644 index 0000000000000000000000000000000000000000..1338596985bc59f39ebe032d27badc866cefa7fc --- /dev/null +++ b/docs/API_reference/zh/stdlib/uhashlib.md @@ -0,0 +1,86 @@ +# class uhashlib - 哈希算法 + +该模块实现二进制数据散列算法。 + +> 目前仅支持sha256,sha1,MD5。 + +**示例:** + +```python +import uhashlib +import ubinascii + +hash_obj = uhashlib.sha256() # 创建hash对象 +hash_obj.update(b"QuecPython") +res = hash_obj.digest() +# b"\x1e\xc6gq\xb3\xa9\xac>\xa4\xc4O\x00\x9eTW\x97\xd4.\x9e}Bo\xff\x82u\x89Th\xfe'\xc6\xcd" +# 转成十六进制表示 +hex_msg = ubinascii.hexlify(res) +# b'1ec66771b3a9ac3ea4c44f009e545797d42e9e7d426fff8275895468fe27c6cd' +``` + + +## 构造函数 + +### `uhashlib.sha256` + +```python +class uhashlib.sha256(bytes) +``` + +创建一个SHA256哈希对象 + +**参数描述:** + +- `bytes` - 可选参数,bytes型数据。可在创建时传入bytes数据,也可通过update方法。 + +### `uhashlib.sha1` + +```python +class uhashlib.sha1(bytes) +``` + +创建一个SHA1哈希对象 + +**参数描述:** + +- `bytes` - 可选参数,bytes型数据。可在创建时传入bytes数据,也可通过update方法。 + +### `uhashlib.md5` + +```python +class uhashlib.md5(bytes) +``` + +创建一个MD5哈希对象 + +**参数描述:** + +- `bytes` - 可选参数,bytes型数据。可在创建时传入bytes数据,也可通过update方法。 + + +## 方法 + +### `hash_obj.update()` + +```python +hash_obj.update(bytes) +``` + +将更多的bytes数据加到散列。 + +**参数描述** + +- `bytes` - 需要被加密的bytes类型数据。 + +### `hash_obj.digest()` + +```python +hash_obj.digest() +``` + +返回通过哈希传递的所有数据的散列,数据为字节类型。调用此方法后,无法再将更多的数据送入散列。 + +**返回值描述:** + +返回加密后字节类型的数据。 diff --git a/docs/API_reference/zh/stdlib/uio.md b/docs/API_reference/zh/stdlib/uio.md new file mode 100644 index 0000000000000000000000000000000000000000..bc9d04871b037c37c9527d11dd761a2bca608a30 --- /dev/null +++ b/docs/API_reference/zh/stdlib/uio.md @@ -0,0 +1,49 @@ +# uio - 输入输出流 + +`uio`模块包含其他类型的stream(类文件)对象和辅助函数。该模块实现相应CPython模块的子集。更多信息请参阅CPython文档:[io](https://docs.python.org/3.5/library/io.html#module-io) + +> 支持IOBase,BytesIO,FileIO,StringIO,TextIO。 + +**示例**: + +```python +fd = uio.open('/usr/test.py', mode='r', encoding='UTF-8') +fd.close() +``` + +## 打开文件 + +### `uio.open` + +```python +uio.open(name, mode='r', **kwarg) +``` + +打开文件,内置`open()`函数是该函数的别名。 + +**参数描述** + +* `name` :字符串,表示文件名 + +* `mode` :字符串,打开模式 + +|打开模式|含义| +| ---- | ---- | +| 'r' |只读模式打开文件| +| 'w' |写入模式打开文件,每次写入会覆盖上次写入数据| +| 'a' |只写追加模式打开文件,可连续写入文件数据而不是覆盖数据| + +* `**kwarg`:可变长参数列表 + +**返回值描述** +成功则返回uio的对象,失败则根据不同的失败类型抛出error + +## 关闭打开的文件 + +### `uio.close` + +```python +uio.close() +``` + +关闭打开的文件。 \ No newline at end of file diff --git a/docs/API_reference/zh/stdlib/ujson.md b/docs/API_reference/zh/stdlib/ujson.md new file mode 100644 index 0000000000000000000000000000000000000000..ed6eeea0f6ddc801a82240013c0ad7d9a04384cf --- /dev/null +++ b/docs/API_reference/zh/stdlib/ujson.md @@ -0,0 +1,100 @@ +# ujson - JSON编码和解码 +`ujson`模块实现在Python对象和JSON数据格式之间进行转换的功能。该模块实现相应CPython模块的子集。更多信息请参阅CPython文档:[json](https://docs.python.org/3.5/library/json.html#module-json) + +**示例:** + +```python +# ujson使用。 + +import ujson +from uio import StringIO + +# 初始化空数据流io。 +io = StringIO() +# 解析字典类型数据并转换成json字符串到io。 +ujson.dump({"say": "hello"}, io) +# 获取io信息。 +io.getvalue() + +# 解析字典类型数据并返回json字符串。 +ujson.dumps({"say": "hello"}) + +# 初始化数据流io,并写入json字符串。 +io = StringIO('{"say": "hello"}') +# 加载io中json字符串,返回字典类型数据。 +ujson.load(io) + +# 加载json字符串,返回字典类型数据。 +ujson.loads('{"say": "hello"}') + +``` + +## 编码json数据 + +将`Python`对象编码成json字符串 + +### `ujson.dump` + +```python +ujson.dump(obj, stream) +``` + +序列化`obj`对象转化成`JSON`字符串,并将其写入到给定的`stream`中。 + +**参数描述:** + +- `obj` - `Python`对象,需要转换成`JSON`字符串的数据对象。 +- `stream` - 数据流对象,转换成`JSON`字符串后写入的位置。 + +### `ujson.dumps` + +```python +ujson.dumps(obj) +``` + +将`Python`对象转换成`JSON`字符串。 + +**参数描述:** + +- `obj` - `Python`对象,需要转换成`JSON`字符串的数据对象。 + +**返回值描述:** + +返回`JSON`字符串。 + + +## 解码json数据 + +将JSON数据解码成`Python`对象。 + +### `ujson.load` + +```python +ujson.load(stream) +``` + +解析给定的数据`stream`,将其解析为`JSON`字符串并反序列化成`Python`对象,最终将对象返回。 + +**参数描述:** + +- `stream` -数据流对象,能够读取`JSON`字符串的数据流对象。 + +**返回值描述:** + +返回`Python`对象。 + +### `ujson.loads` + +```python +ujson.loads(str) +``` + +解析`JSON`字符串`str`并返回一个`Python`对象。 + +**参数描述:** + +- `str` -`JSON`字符串。 + +**返回值描述:** + +返回`Python`对象。 \ No newline at end of file diff --git a/docs/API_reference/zh/stdlib/uos.md b/docs/API_reference/zh/stdlib/uos.md new file mode 100644 index 0000000000000000000000000000000000000000..639ed16e61c596334388d324c48243046eab8aac --- /dev/null +++ b/docs/API_reference/zh/stdlib/uos.md @@ -0,0 +1,619 @@ +# uos - 基本系统服务 + +`uos`模块包含文件系统访问和挂载构建,该模块实现了CPython模块相应模块的子集。更多信息请参阅CPython文档:[os](https://docs.python.org/3.5/library/os.html#module-os) + +## 删除文件 + +### `uos.remove` + +```python +uos.remove(path) +``` + +删除文件。 + +**参数描述** + +* `path`,字符串,表示文件名。 + +## 改变当前目录 + +### `uos.chdir` + +```python +uos.chdir(path) +``` + +改变当前目录。 + +**参数描述** + +* `path`,字符串,表示目录名。 + +## 获取当前路径 + +### `uos.getcwd` + +```python +uos.getcwd() +``` + +获取当前路径。 + +**返回值描述** + +字符串,当前路径 + +## 列出指定目录文件 + +### `uos.listdir` + +```python +uos.listdir( [dir] ) +``` + +没有参数列出当前目录文件,否则列出给定目录的文件。 + +**参数描述** + +* `dir`为字符串,可选参数,表示目录名,默认为 ‘/’ 目录。 + +**返回值描述** + +元组,列出路径下所有存在的对象(目录&文件) + +**示例:** + +```python +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’] +``` + +## 创建新目录 + +### `uos.mkdir` + +``` +uos.mkdir(path) +``` + +创建一个新的目录。 + +**参数描述** + +* `path`表示准备创建的目录名,为所在目录的相对路径。 + +**示例:** + +```python +>>> uos.mkdir('testdir') +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’, 'testdir'] +``` + +## 重命名文件 + +### `uos.rename` + +```python +uos.rename(old_path, new_path) +``` + +重命名文件。 + +**参数描述** + +* `old_path`,字符串,表示旧文件或目录名, +* `new_path`,字符串,表示新文件或目录名。 + +**示例:** + +```python +>>> uos.rename('testdir', 'testdir1') +``` + +## 删除指定目录 + +### `uos.rmdir` + +```python +uos.rmdir(path) +``` + +删除指定目录。 + +**参数描述** + +* `path`,字符串,表示目录名,为所在目录的相对路径。 + +**示例:** + +```python +>>> uos.rmdir('testdir') +>>> uos.listdir() +[‘file1’, ‘read.txt’, ‘demo.py’] +``` + +## 列出当前目录参数 + +### `uos.ilistdir` + +```python +uos.ilistdir( [dir] ) +``` + +该函数返回一个迭代器,该迭代器会生成所列出条目对应的3元组。 + +**参数描述** + +* `dir`为可选参数,字符串,表示目录名,没有参数时,默认列出当前目录,有参数时,则列出dir参数指定的目录。 + +**返回值描述** + +返回一个迭代器,该迭代器会生成所列出条目对应的3元组 + +元组的形式为 `(name, type, inode[, size])`: + +* `name` 是条目的名称,字符串类型,如果dir是字节对象,则名称为字节; +* `type` 是条目的类型,整型数,0x4000表示目录,0x8000表示常规文件; +* `inode`是一个与文件的索引节点相对应的整数,对于没有这种概念的文件系统来说,可能为0; +* 一些平台可能会返回一个4元组,其中包含条目的size。对于文件条目,size表示文件大小的整数,如果未知,则为-1。对于目录项,其含义目前尚未定义。 + +## 获取文件或目录的状态 + +### `uos.stat` + +```python +uos.stat(path) +``` + +获取文件或目录的状态。 + +**参数描述** + +* `path`,字符串,表示文件或目录名。 + +**返回值描述** + +返回值是一个元组,返回值形式为: + +`(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)` + +* `mode` – inode保护模式 +* `ino` – inode节点号 +* `dev` – inode驻留的设备 +* `nlink` – inode的链接数 +* `uid ` – 所有者的用户ID +* `gid` – 所有者的组ID +* `size` – 文件大小,单位字节 +* `atime` – 上次访问的时间 +* `mtime` – 最后一次修改的时间 +* `ctime` – 操作系统报告的“ctime”,在某些系统上是最新的元数据更改的时间,在其它系统上是创建时间,详细信息参见平台文档 + +## 获取文件系统状态信息 + +### `uos.statvfs` + +```python +uos.statvfs(path) +``` + +获取文件系统状态信息。 + +**参数描述** + +* `path`,字符串,表示文件或目录名。 + +**返回值描述** + +返回一个包含文件系统信息的元组: + +`(f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax)` + +* `f_bsize` – 文件系统块大小,单位字节 +* `f_frsize` – 分栈大小,单位字节 +* `f_blocks` – 文件系统数据块总数 +* `f_bfree` – 可用块数 +* `f_bavai` – 非超级用户可获取的块数 +* `f_files` – 文件结点总数 +* `f_ffree` – 可用文件结点数 +* `f_favail` – 超级用户的可用文件结点数 +* `f_flag` – 挂载标记 +* `f_namemax` – 最大文件长度,单位字节 + +**示例:** + +```python +>>> import uos +>>> res = uos.statvfs("main.py") +>>> print(res) +(4096, 4096, 256, 249, 249, 0, 0, 0, 0, 255) +``` + +## 获取关于底层信息或其操作系统的信息 + +### `uos.uname` + +```python +uos.uname() +``` + +获取关于底层信息或其操作系统的信息。 + +**返回值描述** + +该接口与micropython官方接口返回值形式有所区别,返回一个元组,形式为: + +`(sysname, nodename, release, version, machine)` + +* `sysname` – 底层系统的名称,string类型 +* `nodename` – 网络名称(可以与 sysname 相同) ,string类型 +* `release` – 底层系统的版本,string类型 +* `version` – MicroPython版本和构建日期,string类型 +* `machine` – 底层硬件(如主板、CPU)的标识符,string类型 +* `qpyver` – QuecPython 短版本号,string类型 + +**示例:** + +```python +>>> import uos +>>> uos.uname() +('sysname=EC600S-CNLB', 'nodename=EC600S', 'release=1.12.0', 'version=v1.12 on 2020-06-23', 'machine=EC600S with QUECTEL', 'qpyver=V0001') +>>> uos.uname()[0].split('=')[1] # 可通过这种方式来获取sysname的值 +'EC600S-CNLB' +``` + +### `uos.uname2` + +```python +uos.uname2() +``` + +获取关于底层信息或其操作系统的信息。 + +**返回值描述** + +该接口与micropython官方接口返回值形式一致。注意与上面uos.uname()接口返回值的区别,返回值形式为: + +`(sysname, nodename, release, version, machine, qpyver)` + +* `sysname` – 底层系统的名称,string类型 +* `nodename` – 网络名称(可以与 sysname 相同) ,string类型 +* `release` – 底层系统的版本,string类型 +* `version` – MicroPython版本和构建日期,string类型 +* `machine` – 底层硬件(如主板、CPU)的标识符,string类型 +* `qpyver` – QuecPython 短版本号,string类型 + +**示例:** + +```python +>>> import uos +>>> uos.uname2() +(sysname='EC600S-CNLB', nodename='EC600S', release='1.12.0', version='v1.12 on 2020-06-23', machine='EC600S with QUECTEL', qpyver='V0001') +>>> uos.uname2().sysname # 可通过这种方式直接获取sysname的值 +'EC600S-CNLB' +>>> uos.uname2().machine +'EC600S with QUECTEL' +``` + +## 返回具有*n个*随机字节的bytes对象 + +### `uos.urandom` + +```python +uos.urandom(n) +``` + +返回具有*n个*随机字节的bytes对象,如果模组搭载了硬件随机数生成器,它就会由硬件随机数生成器生成。 + +**参数描述** + +* `n`,整型,随机字节的个数 + +**返回值描述** + +具有*n个*随机字节的bytes对象 + +**示例:** + +```python +>>> import uos +>>> uos.urandom(5) +b'\xb3\xc9Y\x1b\xe9' +``` + +## 注册存储设备 - SPI - SD卡 + +> 目前仅ECx00N&EG91xN平台支持。 + +### `uos.VfsFat` + +```python +uos.VfsFat(spi_port, spimode, spiclk, spics) +``` + +初始化SD卡,和SD卡通信。使用SPI通信方式。 + +**参数描述** + +* `spi_port`,int,通道选择[0,1] +* `spimode`,int,SPI 的工作模式(模式0最常用):
+|参数|工作模式| +| ---- | ---- | +| 0 |CPOL=0, CPHA=0| +| 1 | CPOL=0, CPHA=1| +| 2 |CPOL=1, CPHA=0| +| 3 |CPOL=1, CPHA=1| +> 时钟极性CPOL: 即SPI空闲时,时钟信号SCLK的电平(0:空闲时低电平; 1:空闲时高电平) + +* `spiclk`, int + +|参数|时钟频率| +| ---- | ---- | +| 0 |812.5kHz| +| 1 |1.625MHz| +| 2 |3.25MHz| +| 3 |6.5MHz| +| 4 |13MHz| + +* `spics`,int,指定CS片选引脚为任意GPIO,硬件CS可以接这里指定的脚,也可以接默认的SPI CS脚 + +> 1-n:指定Pin.GPIO1-Pin.GPIOn为CS脚 + +**返回值描述** + +成功则返回VfsFat object,失败则会报错。 + +**示例:** + +```python +>>> cdev = uos.VfsFat(1, 0, 4, 1) +>>> uos.mount(cdev, '/sd') +>>> f = open('/sd/test.txt','w+') +>>> f.write('0123456') +>>> f.close() +>>> uos.listdir('/sd') +>>> f = open('/sd/test.txt','r') +>>> f.read() +>>> f.close() +``` + +## 注册存储设备 - SDIO - SD卡 + +> 目前仅EC600U/EC200U/EC200A平台支持。 + +### `uos.VfsSd` + +```python +uos.VfsSd(str) +``` + +初始化SD卡,使用SDIO通信方式。 + +**参数描述** + +* `str`,str类型,固定为"sd_fs",后续扩展。 + +**返回值描述** + +成功则返回vfs object,失败则会报错。 + +**引脚说明** + +| 平台 | 引脚 | +| ------ | --------------------------------------------------------------------------------------------------------------- | +| EC600U | CMD:引脚号48
DATA0:引脚号39
DATA1:引脚号40
DATA2:引脚号49
DATA3:引脚号50
CLK:引脚号132 | +| EC200U | CMD:引脚号33
DATA0:引脚号31
DATA1:引脚号30
DATA2:引脚号29
DATA3:引脚号28
CLK:引脚号32 | +| EC200A | CMD:引脚号33
DATA0:引脚号31
DATA1:引脚号30
DATA2:引脚号29
DATA3:引脚号28
CLK:引脚号32 | + +**示例:** + +```python +>>> from uos import VfsSd +>>> udev = VfsSd("sd_fs") +``` + +## 设置SD卡检测管脚 + +### `uos.set_det` + +```python +uos.set_det(vfs_obj.GPIOn,mode) +``` + +指定sd卡插拔卡的检测管脚和模式。 + +**参数描述** + +* `vfs_obj.GPIOn`,int类型,用于sd卡插拔卡检测的GPIO引脚号,参照[Pin](../peripherals/machine.Pin.md)模块的定义 +* `mode`,int类型
0:sd卡插上后,检测口为低电平;sd卡取出后,检测口为高电平
1:sd卡插上后,检测口为高电平;sd卡取出后,检测口为低电平 + +**返回值描述** + +成功返回 `0`,失败返回 `-1`。 + +**示例:** + +```python +>>> from uos import VfsSd +>>> udev = VfsSd("sd_fs") +>>> uos.mount(udev, '/sd') +>>> udev.set_det(udev.GPIO10,0)#使用GPIO10作为卡检测管脚,sd卡插上,检测口为低电平,sd卡取出,检测口为高电平(实际使用根据硬件) +``` + +## 设置插拔SD卡回调函数 + +### `uos.set_callback` + +```python +uos.set_callback(fun) +``` + +设定发生插拔卡事件时的用户回调函数。 + +**参数描述** + +* `fun`,插拔卡的回调函数,function类型,原型为fun(args),参数`args`为int类型,0表示拔卡,1表示插卡 + +**返回值描述** + +成功返回 `0`,失败返回 `-1`。 + +**SD卡使用示例(SDIO接口)** + +> 目前仅EC600U/EC200U/EC200A平台支持。 + +**示例:** + +```python +from uos import VfsSd +import ql_fs +udev = VfsSd("sd_fs") +uos.mount(udev, '/sd') +udev.set_det(udev.GPIO10,0) +#文件读写 +f = open('/sd/test.txt','w+') +f.write('1234567890abcdefghijkl') +f.close() +uos.listdir('/sd') +f = open('/sd/test.txt','r') +f.read() +f.close() +#插拔卡回调函数 +def call_back(para): + if(para == 1): + print("insert") + print(uos.listdir('/usr')) + print(ql_fs.file_copy('/usr/1.txt','/sd/test.txt'))#复制sd卡里的test.txt内容到usr下的1.txt中 + print(uos.listdir('/usr')) + elif(para == 0): + print("plug out") + +udev.set_callback(call_back) +``` + +## 注册存储设备 - SPI NOR FLASH + +> 目前仅ECx00N&EG91xN&ECx00M&EG810M&ECx00U&EG91xU系列平台支持。且只支持4线spi nor flash。ECx00U&EG91xU不建议使用spi_clk = 3。 + +### `uos.VfsLfs1` + +```python +uos.VfsLfs1(readsize,progsize,lookahead,pname,spi_port,spi_clk) +``` + +初始化spi nor flash,和外挂nor flash通信。使用SPI通信方式将此存储设备挂载为littleFS文件系统。 + +**参数描述** + +* `readsize`,int类型,预留,暂未使用 +* `progsize`,int类型,预留,暂未使用 +* `lookahead`,int类型,预留,暂未使用 +* `pname`,str类型,固定为“ext_fs”。后续扩展 +* `spi_port`,int类型,支持的端口参照SPI章节说明 +* `spi_clk`,int类型
+|参数|时钟频率| +| ---- | ---- | +| 0 |6.25MHz| +| 1 |12.5MHz| +| 2 |25MHz| +| 3 |50MHz| +| 4 |3.125MHz| +| 5 |1.5625MHz| +| 6 |781.25KHz| +**返回值描述** + +成功则返回VfsLfs1 object,失败则返回 OSError 19。 + +**示例:** + +```python +>>>ldev = uos.VfsLfs1(32, 32, 32, "ext_fs",1,0) +>>>uos.mount(ldev,'/ext') +>>>f = open('/ext/test.txt','w+') +>>>f.write('hello world!!!') +>>>f.close() + +>>>uos.listdir('ext') + +>>>f = open('/ext/test.txt','r') +>>>f.read() +>>>f.close() + +``` + +## 注册存储设备 - EMMC + +> 目前仅EC200ACNLA平台支持 + +### `uos.VfsEmmc` + +```python +uos.VfsEmmc(str) +``` + +初始化EMMC存储,使用SDIO通信方式。 + +**参数描述** + +* `str`,str类型,预留,暂未使用。 + +**返回值描述** + +成功则返回vfs object,失败则会报错。 + +**示例:** + +```python +edev = uos.VfsEmmc('emmc') +uos.mount(edev,'/emmc') +f = open('/emmc/test.txt','w+') +f.write('hello world!!!') +f.close() + +uos.listdir('emmc') +f = open('/emmc/test.txt','r') +f.read() +f.close() +``` + +## 挂载文件系统 + +### `uos.mount` + +```python +uos.mount(vfs_obj, path, mkfs=) +``` + +挂载实体文件系统(如littleFS/FATFS等)到虚拟文件系统(VFS)。 + +**参数描述** + +* `vfs_obj`,vfs object,文件系统对象 +* `path`,str类型,文件系统的根目录 +* `mkfs=`,int类型,可选参数,是否格式化存储设备。传入1执行格式化,不传入该参数或传入0不执行格式化。 + +**示例:** + +```python +import uos + +#SPI NOR FLASH存储场景 +ldev = uos.VfsLfs1(32, 32, 32, "ext_fs", 1, 0) +uos.mount(ldev, '/ext') #不传入mkfs=1只挂载不格式化 +#uos.mount(ldev, '/ext', mkfs=1) #传入mkfs=1进行格式化 + +#SPI SD卡存储场景 +cdev = uos.VfsFat(1, 0, 4, 1) +uos.mount(cdev, '/sd') #不传入mkfs=1只挂载不格式化 +#uos.mount(cdev, '/sd', mkfs=1) #传入mkfs=1进行格式化 + +#SDIO SD卡存储场景 +from uos import VfsSd +udev = VfsSd("sd_fs") +uos.mount(udev, '/sd') #不传入mkfs=1只挂载不格式化 +#uos.mount(udev, '/sd', mkfs=1) #传入mkfs=1进行格式化 +``` + +> 格式化功能适用于SD卡存储及EC600MCN_CC_EXT&ECx00U&EGx00U系列平台外置SPI NOR flash存储场景。 + diff --git a/docs/API_reference/zh/stdlib/urandom.md b/docs/API_reference/zh/stdlib/urandom.md new file mode 100644 index 0000000000000000000000000000000000000000..ff35609e224fd6361402025a6df0531a3ef79265 --- /dev/null +++ b/docs/API_reference/zh/stdlib/urandom.md @@ -0,0 +1,266 @@ +# urandom - 生成随机数 + +urandom 模块提供了生成随机数的工具。 + +## 随机生成对象 obj 中的元素 + +### `urandom.choice` + +```python +urandom.choice(obj) +``` + +随机生成对象 obj 中的元素,obj 类型 string。 + +**参数描述** + +* `obj`,str类型 + +**返回值描述** + +`obj`中随机某个元素,str + +**示例**: + +``` +>>> import urandom +>>> urandom.choice("QuecPython") +'t' +``` + +## 随机产生一个在k bits范围内的十进制数 + +### `urandom.getrandbits` + +```python +urandom.getrandbits(k) +``` + +随机产生一个在k bits范围内的十进制数。 + +**参数描述** + +* `k`,int类型,表示范围(单位bit) + +**返回值描述** + +int类型,在k bits范围内的十进制随机数 + +**示例**: + +``` +>>> import urandom +>>> urandom.getrandbits(1) #1位二进制位,范围为0~1(十进制:0~1) +1 +>>> urandom.getrandbits(1) +0 +>>> urandom.getrandbits(8) #8位二进制位,范围为0000 0000~1111 11111(十进制:0~255) +224 +``` + +## 随机生成一个 start 到 end 之间的整数 + +### `urandom.randint` + +``` +urandom.randint(start, end) +``` + +随机生成一个 start 到 end 之间的整数。 + +**参数描述** + +* `start`,int类型,区间最小值 +* `end`,int类型,区间最大值 + +**返回值描述** + +int类型,在`start `到 `end` 之间的随机整数 + +**示例**: + +``` +>>> import urandom +>>> urandom.randint(1, 4) +4 +>>> urandom.randint(1, 4) +2 +``` + +## 随机生成一个 0 到 1 之间的浮点数 + +### `urandom.random` + +```python +urandom.random() +``` + +随机生成一个 0 到 1 之间的浮点数。 + +**返回值描述** + +浮点数,在0 到 1 之间。 + +**示例**: + +``` +>>> import urandom +>>> urandom.random() +0.8465231 +``` + +## 随机生成 start 到 end 间并且递增为 step 的正整数 + +### `urandom.randrange` + +```python +urandom.randrange(start, end, step) +``` + +随机生成 start 到 end 间并且递增为 step 的正整数。 + +**参数描述** + +* `start`,int类型,区间最小值 +* `end`,int类型,区间最大值 +* `step`,int类型,递增长度 + +**返回值描述** + +int类型,在 `start `到 `end` 之间的随机整数 + +**示例**: + +``` +>>> import urandom +>>> urandom.randrange(0, 8, 2) +0 +>>> urandom.randrange(0, 8, 2) +6 +``` + +## 指定随机数种子 + +### `urandom.seed` + +```python +urandom.seed(sed) +``` + +指定随机数种子,通常和其它随机数生成函数搭配使用。 + +**参数描述** + +* `sed`,int类型 + +**示例**: + +```python +>>> import urandom +>>> urandom.seed(20) #指定随机数种子 +>>> for i in range(0, 15): #生成0~15范围内的随机序列 +... print(urandom.randint(1, 10)) +... +8 +10 +9 +10 +2 +1 +9 +3 +2 +2 +6 +1 +10 +9 +6 +``` + +## 随机生成 start 到 end 范围内的浮点数 + +### `urandom.uniform` + +```python +urandom.uniform(start, end) +``` + +**参数描述** + +* `start`,任意实数类型,区间最小值 +* `end`,任意实数类型,区间最大值 + +**返回值描述** + +浮点数类型,在 `start `到 `end` 之间的随机数 + +**示例**: + +``` +>>> import urandom +>>> urandom.uniform(3, 5) +3.219261 +>>> urandom.uniform(3, 5) +4.00403 +``` + +**使用示例** + +```python +''' +@Author: Baron +@Date: 2020-06-22 +@LastEditTime: 2020-06-22 17:16:20 +@Description: example for module urandom +@FilePath: example_urandom_file.py +''' +import urandom as random +import log +import utime + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_Random_example" +PROJECT_VERSION = "1.0.0" + +log.basicConfig(level=log.INFO) +random_log = log.getLogger("random") + + +if __name__ == '__main__': + # urandom.randint(start, end) + # 随机1 ~ 4之间 + num = random.randint(1, 4) + random_log.info(num) + + # random between 0~1 + num = random.random() + random_log.info(num) + + # urandom.unifrom(start, end) + # 在开始和结束之间生成浮点数 + num = random.uniform(2, 4) + random_log.info(num) + + # urandom.randrange(start, end, step) + # 2-bit binary,the range is [00~11] (0~3) + num = random.getrandbits(2) + random_log.info(num) + + # 8-bit binary,the range is [0000 0000~1111 11111] (0~255) + num = random.getrandbits(8) + random_log.info(num) + + # urandom.randrange(start, end, step) + # 从开始到结束随机生成递增的正整数 + num = random.randrange(2, 8, 2) + random_log.info(num) + + # urandom.choice(obj) + # 随机生成对象中元素的数量 + num = random.choice("QuecPython") + random_log.info(num) + +``` diff --git a/docs/API_reference/zh/stdlib/ure.md b/docs/API_reference/zh/stdlib/ure.md new file mode 100644 index 0000000000000000000000000000000000000000..9c4130cd4fc200925ff082facb08e83f24361bc4 --- /dev/null +++ b/docs/API_reference/zh/stdlib/ure.md @@ -0,0 +1,126 @@ +# ure - 正则表达式 + +该模块通过正则表达式匹配数据。 + +>目前支持的操作符较少,部分操作符暂不支持。 + +**示例:** + +```python +import ure + +res = ''' +$GNRMC,133648.00,A,3149.2969,N,11706.9027,E,0.055,,311020,,,A,V*18 +$GNGGA,133648.00,3149.2969,N,11706.9027,E,1,24,1.03,88.9,M,,M,,*6C +$GNGLL,3149.2969,N,11706.9027,E,133648.00,A,A*7A +$GNGSA,A,3,31,26,11,194,27,195,08,09,03,193,04,16,1.41,1.03,0.97,1*31 +''' + +r = ure.search("GNGGA(.+?)M", res) +print(r.group(0)) +``` + +## 编译并生成正则表达式对象 + +### `ure.compile` + +```python +ure.compile(regex) +``` + +用于编译正则表达式,生成一个正则表达式对象,供 match() 和 search() 这两个函数使用。 + +**参数描述:** + +- `regex` - 正则表达式,字符串类型。 + + +## 匹配 + +### `ure.match` + +```python +ure.match(regex, string) +``` + +将正则表达式对象 与 string 匹配,匹配通常从字符串的起始位置进行。 + +**参数描述:** + +- `regex` - 正则表达式,字符串类型。 +- `string` - 需要匹配的字符串数据。 + +**返回值描述:** + +- 匹配成功返回一个匹配的对象,否则返回None。 + +## 查找 + +### `ure.search` + +```python +ure.search(regex, string) +``` + +扫描整个字符串并返回第一个成功的匹配。 + +**参数描述:** + +- `regex` - 正则表达式,字符串类型。 +- `string` - 需要查找的字符串数据。 + +**返回值描述:** + +- 匹配成功返回一个匹配的对象,否则返回None。 + + +## 匹配单个字符串 + +### `match.group` + +```python +match.group(index) +``` + +匹配 match() 和 serach() 方法返回的对象。 + +**参数描述:** + +- `index` - 整型,正则表达式中,group()用来提出分组截获的字符串, index=0返回整体,根据编写的正则表达式进行获取,当分组不存在时会抛出异常。 + +**返回值描述:** + +- 返回匹配的整个表达式的字符串。 + + +## 常量 + +### 支持的操作符 +- `‘.’` - 字符类型,匹配任意字符。 +- `‘[]’` - 字符类型,匹配字符集合,支持单个字符和一个范围,包括负集。 +- `‘^’` - 字符类型,匹配字符串的开头。 +- `‘$’` - 字符类型,匹配字符串的结尾。 +- `‘?’` - 字符类型,匹配零个或前面的子模式之一。 +- `‘*’` - 字符类型,匹配零个或多个先前的子模式。 +- `‘+’` - 字符类型,匹配一个或多个先前的子模式。 +- `‘??’` - 字符类型,非贪婪版本的 ? ,匹配0或1。 +- `‘*?’` - 字符类型,非贪婪版本的*,匹配零个或多个。 +- `‘+?’` - 字符类型,非贪婪版本的+,匹配一个或多个。 +- `‘\|’` - 字符类型,匹配该操作符的左侧子模式或右侧子模式。 +- `‘\d’` - 字符类型,数字匹配。 +- `‘\D’` - 字符类型,非数字匹配。 +- `‘\s’` - 字符类型,匹配空格。 +- `‘\S’` - 字符类型,匹配非空格。 +- `‘\w’` - 字符类型,匹配”单词字符” (仅限ASCII)。 +- `‘\W’` - 字符类型,匹配非“单词字符”(仅限ASCII)。 + + +### 不支持的操作符 +- `‘{m,n}’` - 重复次数。 +- `‘(?P...)’` - 命名组。 +- `‘(?:...)’` - 非捕获组。 +- `‘\b’` - 更高级的断言。 +- `‘\B’` - 更高级的断言。 +- `‘\r’` - 特殊字符转义,改用Python自己的转义。 +- `‘\n’` - 特殊字符转义,改用Python自己的转义。 + diff --git a/docs/API_reference/zh/stdlib/usocket.md b/docs/API_reference/zh/stdlib/usocket.md new file mode 100644 index 0000000000000000000000000000000000000000..623c3bc4a998d0915a7d9a1dea8f043fdd5d90e3 --- /dev/null +++ b/docs/API_reference/zh/stdlib/usocket.md @@ -0,0 +1,440 @@ +# class usocket - socket模块 + + +该模块提供对BSD套接字接口的访问。该模块实现相应CPython模块的子集。更多信息请参阅阅CPython文档:[socket](https://docs.python.org/3.5/library/socket.html#module-socket) + +**示例:** + +```python +# 导入usocket模块 +# -*- coding: UTF-8 -*- +import usocket +import log +import utime +import checkNet + + +''' +下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值 +''' +PROJECT_NAME = "QuecPython_Socket_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +socket_log = log.getLogger("SOCKET") + +if __name__ == '__main__': + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + socket_log.info('Network connection successful!') + + # 创建一个socket实例 + sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) + # 解析域名 + sockaddr=usocket.getaddrinfo('www.tongxinmao.com', 80)[0][-1] + # 建立连接 + sock.connect(sockaddr) + # 向服务端发送消息 + ret=sock.send('GET /News HTTP/1.1\r\nHost: www.tongxinmao.com\r\nAccept-Encoding: deflate\r\nConnection: keep-alive\r\n\r\n') + socket_log.info('send %d bytes' % ret) + #接收服务端消息 + data=sock.recv(256) + socket_log.info('recv %s bytes:' % len(data)) + socket_log.info(data.decode()) + + # 关闭连接 + sock.close() + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) +``` + + +## 构造函数 + +### `usocket.socket` + +```python +class usocket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) +``` + +根据给定的地址族、套接字类型以及协议类型参数,创建一个新的套接字对象。注意,在大多数情况下不需要指定*proto*,也不建议这样做,因为某些MicroPython端口可能会省略 `IPPROTO_*`常量。 + +**参数描述:** + +- `af` - 地址族(参考常量说明)。 + +- `type` - socket类型(参考常量说明)。 + +- `proto` - 协议号(参考常量说明)。 + + +示例: +```python +import usocket +# 创建基于TCP的流式套接字 +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) +# 创建基于UDP的数据报套接字 +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) +# 创建基于TCP的服务端套接字 +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.IPPROTO_TCP_SER) +# 创建基于TCP的客户端套接字(配合bind使用,可自定义socket address) +socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.TCP_CUSTOMIZE_PORT) +``` + +### `usocket.getaddrinfo` + +```python +usocket.getaddrinfo(host, port, family=0) +``` + +DNS域名解析,将主机域名(host)和端口(port)解析为用于创建套接字的5元组序列,元组结构如下: +`(family, type, proto, canonname, sockaddr)` + +**参数描述:** + +- `host` - 主机域名。 +- `port` - 端口。 +- `family` - 地址族,可选参数: + - `usocket.AF_INET` - 仅返回IPv4地址 + - `usocket.AF_INET6` - 仅返回IPv6地址 + - 不指定或设为0 - 返回所有地址类型(IPv4 + IPv6) + +**返回值描述:** + +- `family` - 地址族(参考常量说明)。 +- `type` - socket类型(参考常量说明)。 +- `proto` - 协议号(参考常量说明)。 +- `canonname` - 主机域名。 +- `sockaddr` - 包含地址和端口号的列表。 + +示例: +```python +import usocket + +# 返回所有地址类型(IPv4 + IPv6) +result1 = usocket.getaddrinfo('iservice.10010.com', 443) +# 仅返回IPv4地址 +result2 = usocket.getaddrinfo('iservice.10010.com', 443, usocket.AF_INET) +# 仅返回IPv6地址 +result3 = usocket.getaddrinfo('iservice.10010.com', 443, usocket.AF_INET6) +``` + + +## 方法 + +### `socket.bind` + +```python +socket.bind(address) +``` + +该方法用于套接字绑定指定address,必须尚未绑定。 + +> 1.作为服务器时,需要进行绑定,以固定服务器的address。 +> 2.作为客户端时,绑定address用来指定套接字进行数据处理(配合usocket.TCP_CUSTOMIZE_PORT使用)。 + +**参数描述** + +- `address` - 包含地址和端口号的元组或列表。 + +示例: +``` +#绑定指定address +socket.bind(("192.168.0.1",80)) +#绑定拨号IP,端口自定义(端口为0时,会自动分配) +socket.bind(("",0)) +``` + +### `socket.listen` + +```python +socket.listen(backlog) +``` + +该方法用于套接字服务端开启监听客户端连接,可指定最大客户端连接数。 + +**参数描述:** + +- `backlog` - 接受套接字的最大个数,至少为0。 + +### `socket.accept` + +```python +socket.accept() +``` + +该方法用于套接字服务端接受连接请求,成功返回元组,包含新的套接字和客户端地址以及客户端端口,形式为:`(conn, address, port)`。 + +**返回值:** + +- `conn` - 新的套接字对象,用来和客户端交互。 +- `address` - 连接到服务器的客户端地址。 +- `port` - 连接到服务器的客户端端口。 + +### `socket.connect` + +```python +socket.connect(address) +``` + +该方法用于套接字连接到指定address的服务器。 + +**参数描述:** + +- `address` - 包含地址和端口号的元组或列表。 + +示例: +``` +#连接指定address +socket.connect(("192.168.0.1",80)) +``` + +### `socket.read` + +```python +socket.read( [ size ] ) +``` + +该方法用于从套接字中读取size字节数据,返回一个字节对象。如果没有指定size,则会从套接字读取所有可读数据,直到读取到数据结束,此时作用和 `socket.readall()` 相同。 + +### `socket.readinto` + +```python +socket.readinto(buf, [ , nbytes ]) +``` + +该方法用于从套接字读取字节到缓冲区buf中。如果指定了nbytes,则最多读取nbytes数量的字节;如果没有指定nbytes,则最多读取len(buf)字节。返回值是实际读取的字节数。 + +### `socket.readline` + +```python +socket.readline() +``` + +该方法用于从套接字按行读取数据,遇到换行符结束,返回读取的数据行。 + +### `socket.write` + +```python +socket.write(buf) +``` + +该方法用于套接字发送缓冲区的数据,buf为待发送的数据,返回实际发送的字节数。 + +### `socket.send` + +```python +socket.send(bytes) +``` + +该方法用于套接字发送数据,返回实际发送的字节数。 + +**参数描述:** + +- `bytes` - bytes型数据。 + +### `socket.sendall` + +```python +socket.sendall(bytes) +``` + +该方法用于套接字将所有数据都发送到套接字。与`send()`方法不同的是,此方法将尝试通过依次逐块发送数据来发送所有数据。 +> 该方法再非阻塞套接字上的行为是不确定的,建议在MicroPython中,使用 `write()` 方法,该方法具有相同的“禁止短写”策略来阻塞套接字,并且将返回在非阻塞套接字上发送的字节数。 + +**参数描述:** + +- `bytes` - bytes型数据。 + +### `socket.sendto` + +```python +socket.sendto(bytes, address) +``` + +该方法用于套接字发送数据到指定*address*,返回实际发送的字节数。 + +**参数描述:** + +- `bytes` - bytes型数据。 +- `address` - 包含地址和端口号的元组或列表。 + +### `socket.recv` + +```python +socket.recv(bufsize) +``` + +该方法用于从套接字接收数据。返回值是一个字节对象,表示接收到的数据。一次接收的最大数据量由bufsize指定。 + +**参数描述:** + +- `bufsize` - 一次接收的最大数据量。 + +### `socket.recvfrom` + +```python +socket.recvfrom(bufsize) +``` + +该方法用于从套接字接收数据。返回一个元组,包含字节对象和地址。返回值形式为:`(bytes, address)`。 + +**参数描述:** + +- `bufsize` - 一次接收的最大数据量。 + +**返回值:** + +- `bytes` :接收数据的字节对象。 +- `address` :发送数据的套接字的地址。 + +### `socket.close` + +```python +socket.close() +``` + +该方法用于将套接字标记为关闭并释放所有资源。 + +### `socket.setsockopt` + +```python +socket.setsockopt(level, optname, value) +``` + +该方法用于设置套接字选项的值。 + +**参数描述:** + +- `level` - 套接字选项级别。 +- `optname` - socket功能选项。 +- `value` - 既可以是一个整数,也可以是一个表示缓冲区的bytes类对象。 + +示例: +``` +#设置端口复用允许 +socket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1) +#设置TCP保活包间隔时间,value 单位为分钟,范围:1-120 +socket.setsockopt(usocket.SOL_SOCKET, usocket.TCP_KEEPALIVE, 1) +``` + +### `socket.setblocking` + +```python +socket.setblocking(flag) +``` + +该方法用于设置套接字为阻塞模式或者非阻塞模式。该方法是 `settimeout()` 调用的简写。 + +**参数描述:** + +- `flag` - 设置套接字是否阻塞(默认为阻塞模式)。 + +示例: +``` +#将套接字设置为阻塞 +`socket.setblocking(True)` 相当于 `socket.settimeout(None)` +#将套接字设置为非阻塞 +`socket.setblocking(False)` 相当于 `socket.settimeout(0)` +``` + +### `socket.settimeout` + +```python +socket.settimeout(value) +``` + +该方法用于设置套接字的发送和接收数据超时时间,单位秒。 + +**参数描述:** + +- `value` - 可以是表示秒的非负浮点数,也可以是None。如果给定零,则将套接字置为非阻塞模式,否则套接字将处于阻塞模式。 + +### `socket.makefile` + +```python +socket.makefile(mode='rb') +``` + +该方法用于返回与套接字关联的文件对象,返回值类型与指定的参数有关。仅支持二进制模式 (rb和wb)。 + +### `socket.getsocketsta` + +```python +socket.getsocketsta() +``` + +该方法用于获取TCP套接字的状态。 + +> 1.BG95平台不支持该API。 +> 2.如果调用了 `socket.close()` 方法之后,再调用 `socket.getsocketsta()` 会返回-1,因为此时创建的对象资源等都已经被释放。 + +**返回值:** + +| 状态值 | 状态 | 描述 | +| ------ | ----------- | ------------------------------------------------------------ | +| 0 | CLOSED | 套接字创建了,但没有使用这个套接字 | +| 1 | LISTEN | 套接字正在监听连接 | +| 2 | SYN_SENT | 套接字正在试图主动建立连接,即发送SYN后还没有收到ACK | +| 3 | SYN_RCVD | 套接字正在处于连接的初始同步状态,即收到对方的SYN,但还没收到自己发过去的SYN的ACK | +| 4 | ESTABLISHED | 套接字已成功建立连接 | +| 5 | FIN_WAIT_1 | 套接字已关闭,正在关闭连接,即发送FIN,没有收到ACK也没有收到FIN | +| 6 | FIN_WAIT_2 | 套接字已关闭,正在等待远程套接字关闭,即在FIN_WAIT_1状态下收到发过去FIN对应的ACK | +| 7 | CLOSE_WAIT | 远程套接字已经关闭,正在等待关闭这个套接字,被动关闭的一方收到FIN | +| 8 | CLOSING | 套接字已关闭,远程套接字正在关闭,暂时挂起关闭确认,即在FIN_WAIT_1状态下收到被动方的FIN | +| 9 | LAST_ACK | 远程套接字已关闭,正在等待本地套接字的关闭确认,被动方在CLOSE_WAIT状态下发送FIN | +| 10 | TIME_WAIT | 套接字已经关闭,正在等待远程套接字的关闭,即FIN、ACK、FIN、ACK都完毕,经过2MSL时间后变为CLOSED状态 | + + +## 常量 + +### `usocket.AF_INET` + +地址族,IPV4类型。 + +### `usocket.AF_INET6` + +地址族,IPV6类型。 + +### `usocket.SOCK_STREAM` + +socket类型,TCP的流式套接字。 + +### `usocket.SOCK_DGRAM` + +socket类型,UDP的数据包套接字。 + +### `usocket.SOCK_RAW` + +socket类型,原始套接字。 + +### `usocket.IPPROTO_TCP` + +协议号,TCP协议。 + +### `usocket.IPPROTO_UDP` + +协议号,UDP协议。 + +### `usocket.IPPROTO_TCP_SER` + +协议号,TCP服务器。 + +### `usocket.TCP_CUSTOMIZE_PORT` + +协议号,TCP客户端自定义address使用。 + +### `usocket.SOL_SOCKET` + +套接字选项级别。 + +### `usocket.SO_REUSEADDR` + +socket功能选项,允许设置端口复用。 + +### `usocket.TCP_KEEPALIVE` + +socket功能选项,设置TCP保活包间隔时间。 diff --git a/docs/API_reference/zh/stdlib/ustruct.md b/docs/API_reference/zh/stdlib/ustruct.md new file mode 100644 index 0000000000000000000000000000000000000000..75c1a4dd68d05c0a24828952eaa32c1e9a925220 --- /dev/null +++ b/docs/API_reference/zh/stdlib/ustruct.md @@ -0,0 +1,198 @@ + +# ustruct - 打包和解压原始数据类型 + +`ustruct`模块实现相应CPython模块的子集。更多信息请参阅CPython文档:[struct](https://docs.python.org/3.5/library/struct.html#module-struct) + + +## 格式字符串 + +格式字符串是用来在打包和解包数据时指定预期布局的机制。 其使用指定被打包/解包数据类型的格式字符进行构建。 此外,还有一些特殊字符用来控制字节顺序,大小和对齐方式。 + + +### **字节顺序,大小和对齐方式** + +默认情况下,C类型以机器的本机格式和字节顺序表示,并在必要时通过跳过填充字节来正确对齐(根据C编译器使用的规则)。根据下表,格式字符串的第一个字符可用于指示打包数据的字节顺序,大小和对齐方式: + +| Character | Byte order | Size | Alignment | +| --------- | ---------------------- | -------- | --------- | +| `@` | native | native | native | +| `=` | native | standard | none | +| `<` | little-endian | standard | none | +| `>` | big-endian | standard | none | +| `!` | network (= big-endian) | standard | none | + +> 如果第一个字符不是其中之一,则假定为 '@' 。 + + +### **格式化字符表** + +| Format | C Type | Python type | Standard size | +| ------ | -------------------- | ----------- | ------------- | +| `b` | `signed char` | integer | 1 | +| `B` | `unsigned char` | integer | 1 | +| `h` | `short` | integer | 2 | +| `H` | `unsigned short` | integer | 2 | +| `i` | `int` | integer | 4 | +| `I` | `unsigned int` | integer | 4 | +| `l` | `long` | integer | 4 | +| `L` | `unsigned long` | integer | 4 | +| `q` | `long long` | integer | 8 | +| `Q` | `unsigned long long` | integer | 8 | +| `f` | `float` | float | 4 | +| `d` | `double` | float | 8 | +| `P` | `void *` | integer | 4 | + + +## `ustruct`方法 + +### `ustruct.calcsize` + +```python +ustruct.calcsize(fmt) +``` + +返回存放 `fmt` 需要的字节数。 + +**参数描述:** + +- `fmt` - 格式字符的类型,详情见上文格化式字符表 + +**示例:** + +```python +>>> import ustruct +>>> ustruct.calcsize('i') +4 +>>> ustruct.calcsize('f') +4 +>>> ustruct.calcsize('d') +8 +``` + + + +### `ustruct.pack` + +```python +ustruct.pack(fmt, v1, v2, ...) +``` + +按照格式字符串 `fmt` 压缩参数v1、 v2、…。 + +**参数描述:** + +- `fmt` - 格式字符的类型,详情见上文格化式字符表 +- `v1`, `v2`, `...` - 是需要进行数据转换的变量名或值 + +**返回值描述:** + +- 返回参数编码后的字节对象。 + +**示例:** + +```python +>>> import ustruct + +>>> ustruct.pack('ii', 7, 9) # 打包两个整数 +b'\x07\x00\x00\x00\t\x00\x00\x00' + +``` + +### `ustruct.unpack` + +```python +ustruct.unpack(fmt, data) +``` + +根据格式化字符串 `fmt` 对数据进行解压,返回值为一个元组。 + +**参数描述:** + +- `fmt` - 格式字符的类型,详情见上文格化式字符表 +- `data` - 要进行解压的数据 + +**返回值描述:** + +- 返回包含解压值的元组(即使只包含一个项)。 + +**示例:** + +```python +>>> import ustruct + +>>> ustruct.unpack('ii', b'\x07\x00\x00\x00\t\x00\x00\x00') # 解压之前打包的两个整数 +(7, 9) + +``` + + + +### `ustruct.pack_into` + +```python +ustruct.pack_into(fmt, buffer, offset, v1, v2, ...) +``` + +根据格式字符串`fmt`将值v1、v2、 …打包到从`offset`开始的缓冲区中。从缓冲区的末尾算起,`offset`可能为负。 + +**参数描述:** + +- `fmt` - 格式字符的类型,详情见上文格化式字符表 +- `buffer` - 可写数据缓冲区 +- `offset` - 写入的起始位置 +- `v1`, `v2`, `...` - 需要写入缓冲区的数据 + +**示例:** + +```python +>>> import ustruct + +# 定义格式字符串 +>>> fmt = "3sB" +# 定义一个字符串和一个整数 +>>> name = "Tom" +>>> age = 25 + +# 将两个值按指定格式打包,并写入bytes类型的空缓冲区中 +>>> buf = bytearray(8) # 创建容量为8字节的缓冲区 +>>> ustruct.pack_into(fmt, buf, 0, name.encode(), age) # 将"name"编码成bytes类型并写入三个字符(占3个字节),后面紧跟着一个占1个字节的整数"age" + +>>> print(buf) # 输出:bytearray(b'Tom\x19\x00\x00\x00') +bytearray(b'Tom\x19\x00\x00\x00\x00') +``` + + +### `ustruct.unpack_from` + +```python +ustruct.unpack_from(fmt, data, offset=0) +``` + +根据格式化字符串 `fmt` 解析从 `offest` 开始的数据解压,从缓冲区末尾开始计数的偏移量可能为负值。 + +**参数描述:** + +- `fmt` - 格式字符的类型,详情见上文格化式字符表 +- `data` - 数据缓冲区(缓冲区大小以字节为单位) +- `offset` - (可选)解压的起始位置,默认为零 + +**返回值描述:** + +- 返回解压值的元组(即使只包含一个项)。 + +**示例:** + +```python +>>> import ustruct + +# 定义格式字符串 +>>> fmt = "3sB" +# 定义要解包的字节序列 +>>> data = bytearray(b'Tom\x19\x00\x00\x00\x00') + +# 从字节序列的第一个字节开始解包 +>>> result = ustruct.unpack_from(fmt, data, 0) +>>> print(result) # 输出:(b'Tom', 25) +(b'Tom', 25) + +``` \ No newline at end of file diff --git a/docs/API_reference/zh/stdlib/utime.md b/docs/API_reference/zh/stdlib/utime.md new file mode 100644 index 0000000000000000000000000000000000000000..e629480d4ff8e9c7b57de74cbd34a8b2b3d02816 --- /dev/null +++ b/docs/API_reference/zh/stdlib/utime.md @@ -0,0 +1,371 @@ +# utime - 时间相关功能 + +`utime`模块用于获取当前时间、测量时间间隔和休眠。该模块实现相应CPython模块的子集。更多信息请参阅CPython文档:[time](https://docs.python.org/3.5/library/time.html#module-time) + +**示例**: + +```python +import utime +import log + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +time_log = log.getLogger("LocalTime") + +if __name__ == '__main__': + # 获取本地时间,返回元组 + tupe_t = utime.localtime() + time_log.info(tupe_t) + # 返回当前时间戳,参数为元组 + t = utime.mktime(utime.localtime()) + time_log.info(t) + # 休眠sleep示例 + for i in [0, 1, 2, 3, 4, 5]: + utime.sleep(1) # 休眠(单位 m) + time_log.info(i) + + for i in [0, 1, 2, 3, 4, 5]: + utime.sleep_ms(1000) # 休眠(单位 ms) + time_log.info(i) +``` + + + +## 当前时间相关功能 + +### `utime.localtime` + +```python +utime.localtime() +utime.localtime(secs) +``` + +如有参数,secs需为UTC时间戳,此接口将UTC时间戳转换为UTC日期时间加8时区后的日期时间格式。 + +**参数描述:** + +- 无参数。返回本地日期时间,即UTC日期时间加设备所设置的时区后的日期时间。 +- 有参数,`secs`-int类型,单位秒。返回UTC日期时间加8时区后的日期时间。 + +**返回值描述:** + +`(year, month, day, hour, minute, second, weekday, yearday)`-类型为元组,包含了年、月、日、时、分、秒、星期、一年中第几天。当提供参数`secs`时,返回转换后的时间。当参数`secs`没有提供时,则返回本地RTC的时间。返回值含义如下: + +| 元组成员 | 范围及类型 | 含义 | +| -------- | ---------------------- | ---------------- | +| year | int型 | 年份 | +| month | int型,1~12 | 月份 | +| day | int型,1~31 | 日,当月多少号 | +| hour | int型,0~23 | 小时 | +| minute | int型,0~59 | 分钟 | +| second | int型,0~59 | 秒 | +| weekday | int型,周一到周日是0~6 | 星期 | +| yearday | int型 | 一年中的第多少天 | + +**注意** + +有参数的模式下,如期望参数secs转换为设备所设置的时区的本地时间,请调用utime.localtime_ex(secs)接口。 + +**示例**: + +```python +>>> import utime +>>> utime.localtime() +(2020, 9, 29, 8, 54, 42, 1, 273) +>>> utime.localtime(646898736) +(1990, 7, 2, 14, 5, 36, 0, 183) +``` + +### utime.localtime_ex + +```python +utime.localtime_ex() +utime.localtime_ex(secs) +``` + +如有参数,secs需为UTC时间戳。 + +**参数描述:** + +- 无参数。返回当前本地时间(UTC+时区)。 +- 有参数,`secs`-int类型,单位秒。返回secs代表的UTC日期时间加设备设置的时区后的日期时间,例如,当前设备时区为3,secs转成UTC时间日期为2024-07-09 16:30:00,此函数返回时间为,2024-07-09 19:30:00 。 + +**返回值描述:** + +`(year, month, day, hour, minute, second, weekday, yearday)`-类型为元组,包含了年、月、日、时、分、秒、星期、一年中第几天。当提供参数`secs`时,返回转换后的时间。当参数`secs`没有提供时,则返回本地RTC的时间。返回值含义如下: + +| 元组成员 | 范围及类型 | 含义 | +| ------- | -------------- | -------- | +| year | int型 | 年份 | +| month | int型,1~12 | 月份 | +| day | int型,1~31 | 日,当月多少号 | +| hour | int型,0~23 | 小时 | +| minute | int型,0~59 | 分钟 | +| second | int型,0~59 | 秒 | +| weekday | int型,周一到周日是0~6 | 星期 | +| yearday | int型 | 一年中的第多少天 | + +**示例**: + +```python +>>> import utime +>>> utime.setTimeZone(3) +0 +>>> utime.getTimeZone() +3 +>>> date=utime.localtime_ex() +>>> date +(2024, 7, 9, 13, 59, 30, 1, 191) +>>> utime.mktime_ex(date) +1720522770 +>>> utime.localtime_ex(1720522770) +(2024, 7, 9, 13, 59, 30, 1, 191) +>>> +``` + +### `utime.mktime` + +```python +utime.mktime(date) +``` + +date需为UTC日期时间加8时区后的日期时间,此接口将8时区的日期时间转换为UTC时间戳。 + +**参数描述:** + +- `date`-日期格式的时间,类型为元组,格式:(year, month, mday, hour, minute, second, weekday, yearday)。 + +**返回值描述:** + +int类型。 + +**注意** + +如date不为8时区日期时间,期望按照模组的本地时间转换成UTC时间戳,请调用接口utime.mktime_ex(date)。 + +**示例**: + +```python +>>> import utime +>>> date = (2020, 9, 29, 8, 54, 42, 1, 273) +>>> utime.mktime(date) +1601340882 +``` + +### utime.mktime_ex + +```python +utime.mktime_ex(date) +``` + +date需为设备的本地时间,此接口将date转换为UTC时间戳。例如,当前时区为3,输入日期为2024-07-09 19:30:00,此函数将返回1720542600,此时间戳为UTC时间戳,UTC时间为2024-07-09 16:30:00。 + +**参数描述:** + +- `date`-日期格式的时间,类型为元组,格式:(year, month, mday, hour, minute, second, weekday, yearday)。 + +**返回值描述:** + +int类型。 +**示例**: + +```python +>>> import utime +>>> utime.setTimeZone(3) +0 +>>> utime.getTimeZone() +3 +>>> date=utime.localtime_ex() +>>> date +(2024, 7, 9, 13, 59, 30, 1, 191) +>>> utime.mktime_ex(date) +1720522770 +>>> utime.localtime_ex(1720522770) +(2024, 7, 9, 13, 59, 30, 1, 191) +>>> +``` +### `utime.time` + +```python +utime.time() +``` + +返回自设备开机以来的秒数。 + +**返回值描述:** + +int类型。 + +### `utime.getTimeZone` + +```python +utime.getTimeZone() +``` + +获取当前时区。 + +**返回值描述:** + +int类型,单位小时,范围[-12, 12],负值表示西时区,正值表示东时区,0表示零时区。 + +### `utime.setTimeZone` + +```python +utime.setTimeZone(offset) +``` + +设置时区。设置时区后,本地时间会随之变化为对应时区的时间。 + +**参数描述:** + +- int类型,单位小时,范围[-12, 12],负值表示西时区,正值表示东时区,0表示零时区。 + +**返回值描述:** + +int类型,成功返回0,失败抛异常。 + +### `utime.getTimeZoneEx` + +```python +utime.getTimeZoneEx() +``` + +获取当前时区(增强型),精度更高,可获取非整数时区。 + +**返回值描述:** + +float类型,单位小时,范围[-12.0, 12.0],负值表示西时区,正值表示东时区,0.0表示零时区。 + +> 增强型时区读取/设置接口须成对使用,如使用原有的时区接口读取非整数时区,会造成精度丢失。当前仅 EC200A 系列支持该功能。 + +### `utime.setTimeZoneEx` + +```python +utime.setTimeZoneEx(offset) +``` + +设置时区(增强型),精度更高,可设置非整数时区。设置时区后,本地时间会随之变化为对应时区的时间。 + +**参数描述:** + +- float类型,单位小时,范围[-12.0, 12.0],最大精度为0.25小时(即参数须为0.25的整数倍)负值表示西时区,正值表示东时区,0.0表示零时区。 + +**返回值描述:** + +int类型,成功返回0,失败抛异常。 + +> 增强型时区读取/设置接口须成对使用,如使用原有的时区接口读取非整数时区,会造成精度丢失。当前仅 EC200A 系列支持该功能。 + +## 测量时间间隔相关功能 + +### `utime.ticks_ms` + +```python +utime.ticks_ms() +``` + +返回不断递增的毫秒计数器,在超过0x3FFFFFFF值后会重新计数。 + +**返回值描述:** + +int类型,毫秒计数值,计数值本身无特定意义,只适合用在 `ticks_diff()`函数中。 + +### `utime.ticks_us` + +```python +utime.ticks_us() +``` + +返回不断递增的微秒计数器,在超过0x3FFFFFFF值后会重新计数。 + +**返回值描述:** + +int类型,微秒计数值,计数值本身无特定意义,只适合用在 `ticks_diff()`函数中。 + +### `utime.ticks_cpu` + +```python +utime.ticks_cpu() +``` + +返回不断递增的cpu计数器,单位不确定,取决于硬件平台底层的时钟。 + +**返回值描述:** + +int类型,计数值,计数值本身无特定意义,只适合用在 `ticks_diff()`函数中。 + +### `utime.ticks_diff` + +```python +utime.ticks_diff(ticks1, ticks2) +``` + +计算两次调用` ticks_ms`, `ticks_us`,或 `ticks_cpu`之间的时间间隔。因为`ticks_xxx`这些函数的计数值可能会回绕,所以不能直接相减,需要使用 `ticks_diff`函数。通常用法是在带超时的轮询事件中调用。 + +**参数描述:** + +- `ticks1`-int类型,第二次调用` ticks_ms`, `ticks_us`,或 `ticks_cpu`获取的tick值。 +- `ticks2`-int类型,第一次调用` ticks_ms`, `ticks_us`,或 `ticks_cpu`获取的tick值。 + +**返回值描述:** + +int类型,时间间隔,两次调用` ticks_ms`, `ticks_us`,或 `ticks_cpu`之间的时间间隔。单位和传入的`ticks2`和`ticks1`的单位一致。 + + + +> `ticks2`和`ticks1`的顺序不能颠倒,否则结果无法确定。且这个函数不要用在计算很长的时间间隔,具体限制为`ticks2`和`ticks1`的tick差值不能超过0x1FFFFFFF,否则结果无法确定。 + + + +**示例**: + +```python +import utime +start = utime.ticks_us() +while True: + if utime.ticks_diff(utime.ticks_us(), start) > 500: + print('Timeout') + break +``` + +## 休眠相关功能 + +### `utime.sleep` + +```python +utime.sleep(seconds) +``` + +休眠给定秒数的时间。 + +**参数描述:** + +- `seconds`-int类型,休眠的时长,单位秒。 + +### `utime.sleep_ms` + +```python +utime.sleep_ms(ms) +``` + +休眠给定毫秒数的时间。 + +**参数描述:** + +- `ms`-int类型,休眠的时长,单位毫秒。 + +### `utime.sleep_us` + +```python +utime.sleep_us(us) +``` + +休眠给定微秒数的时间。 + +**参数描述:** + +- `us`-int类型,休眠的时长,单位微秒。 + + + +> `utime.sleep`、`utime.sleep_ms`及`utime.sleep_us`函数的调用会导致程序休眠阻塞。 \ No newline at end of file diff --git a/docs/API_reference/zh/stdlib/uzlib.md b/docs/API_reference/zh/stdlib/uzlib.md new file mode 100644 index 0000000000000000000000000000000000000000..c001c501178dd5f13d39040153c93736bdf4cc5f --- /dev/null +++ b/docs/API_reference/zh/stdlib/uzlib.md @@ -0,0 +1,34 @@ +# uzlib - zlib解压缩 + + +该模块解压缩用[DEFLATE算法](https://en.wikipedia.org/wiki/DEFLATE)压缩二进制数据 (通常在zlib库和gzip存档器中使用)。该模块实现相应CPython模块的子集,更多信息请参阅CPython文档:[zlib](https://docs.python.org/3.5/library/zlib.html#module-zlib) + + +> 1.压缩尚未实现。 +> 2.解压缩前,应检查模块内可使用的空间,确保有足够空间解压文件。 + + +## 构造函数 + +### `uzlib.decompress` + +```python +uzlib.decompress(data, wbits=0, bufsize=0) +``` + +返回解压后的 bytes 对象。 + +**参数描述:** +- `data` - 需要解压的数据。 +- `wbits` - 解压时使用的DEFLATE字典窗口大小(8-15,字典大小是`wbits`值的2的幂)。如果该值为正,则假定`data`为zlib流(带有zlib标头),如果为负,则假定为原始的DEFLATE流。 +- `bufsize` - 为了与CPython兼容,将被忽略。 + + +### `uzlib.DecompIO` + +```python +uzlib.DecompIO(stream, wbits=0, 1) +``` + +创建一个`stream`装饰器,该装饰器允许在另一个流中透明地压缩数据。这允许处理数据大于可用堆大小的压缩流。wbits的值除了上面所述的值以外,还可以取值24..31(16 + 8..15),这表示输入流具有gzip标头。 + diff --git a/docs/API_reference/zh/syslib/Queue.md b/docs/API_reference/zh/syslib/Queue.md new file mode 100644 index 0000000000000000000000000000000000000000..576a4290cedd53c74e0b211de5fc7107b89c05a1 --- /dev/null +++ b/docs/API_reference/zh/syslib/Queue.md @@ -0,0 +1,119 @@ +# Queue - 消息队列 + +用于线程间通信 + + +## 构造函数 + +### `queue.Queue` + +```python +class queue.Queue(maxsize=100) +``` + +**参数描述:** + +`maxsize`-队列最大长度, int类型, 默认长度是100 + +**示例:** + +```python +>>> from queue import Queue +>>> q = Queue(100) +``` + + + +## 往队列放入数据 + +### `Queue.put` + +往队列中塞入数据 + +```python +Queue.put(data=None) +``` + +**参数描述:** + +* `data`-数据或信号, 任意类型, 插入的数据, 可以为空不传参, 不传的默认会传个None信号 + +**返回值描述:** + +True 为成功, False 为失败 + + + +## 获取数据 + +### `Queue.get` + +从队列中获取数据, 这里需要注意一下获取数据这块的是阻塞获取 + +```python +Queue.get() +``` + +**返回值描述:** + +为队列中的数据, 如果是空信号则会获取为None + + + +## 查看队列是否为空 + +### `Queue.empty` + +```python +Queue.empty() +``` + +**返回值描述:** + +True则为空, False则不为空 + + + +## 查看队列中存在的数据个数 + +### `Queue.size` + +```python +Queue.size() +``` + +**返回值描述:** + +int类型的当前数据长度 + + + +**示例:** + +```python +import _thread +from queue import Queue + +# 初始化队列 默认长度100 +q = Queue() + + +def get(): + while True: + # 阻塞获取 + data = q.get() + print("data = {}".format(data)) + +# 线程去阻塞 +_thread.start_new_thread(get, ()) + +# put数据 +text = "hello world" +q.put(text) + +# 获取size +q.size() + +# 判断队列是否已空 +q.empty() +``` \ No newline at end of file diff --git a/docs/API_reference/zh/syslib/README.md b/docs/API_reference/zh/syslib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..59f6f342f8192641ac6370ee445ae8a97072e641 --- /dev/null +++ b/docs/API_reference/zh/syslib/README.md @@ -0,0 +1,21 @@ +# QuecPython 系统功能 + +> QuecPython 系统功能库包括QuecPython模组系统功能相关组件 + +本文描述了 QuecPython 系统功能库中的模块。 + +## QuecPython 系统功能库列表 + +- [modem - 设备相关](./modem.md) +- [example - 执行Python脚本](./example.md) +- [log -日志输出](./log.md) +- [atcmd - 发送AT指令](./atcmd.md) +- [system - 环境配置](./system.md) +- [Queue - 消息队列](./Queue.md) +- [sys_bus - 会话总线](./sys_bus.md) +- [osTimer - os定时器](./osTimer.md) +- [fota - 固件升级相关功能](./fota.md) +- [app_fota - 用户文件升级相关功能](./app_fota.md) +- [ql_fs - 高级文件操作](./ql_fs.md) +- [securedata - 安全数据区相关功能](./securedata.md) +- [pm - 低功耗相关功能](./pm.md) \ No newline at end of file diff --git a/docs/API_reference/zh/syslib/app_fota.md b/docs/API_reference/zh/syslib/app_fota.md new file mode 100644 index 0000000000000000000000000000000000000000..31c9e333cfb392b91b62f8a297bfdbedf5c92f36 --- /dev/null +++ b/docs/API_reference/zh/syslib/app_fota.md @@ -0,0 +1,92 @@ +# app_fota - 用户文件升级相关功能 + +`app_fota`模块用于用户文件升级。 + +**示例**: + +```python +import app_fota +from misc import Power + +fota = app_fota.new() +download_list = [{'url': 'http://www.example.com/app.py', 'file_name': '/usr/app.py'}, {'url': 'http://www.example.com/test.txt', 'file_name': '/usr/text.txt'}] +fota.bulk_download(download_list) # 下载 +fota.set_update_flag() # 设置升级标志 +Power.powerRestart() # 重启 +``` + +## 初始化相关功能 + +### `app_fota.new` + +```python +app_fota.new() +``` + +创建app_fota对象。 + +**返回值描述:** + +app_fota对象。 + +**示例**: + +```python +import app_fota +fota = app_fota.new() +``` + +## 下载相关功能 + +### `fota.download` + +```python +fota.download(url, file_name) +``` + +下载单个文件。 + +**参数描述:** + +- `url`-待下载文件的url,类型为str。 +- `file_name`-本地待升级文件的绝对路径,类型str。 + +**返回值描述**: + +成功返回0,否则返回-1。 + +### `fota.bulk_download` + +```python +fota.bulk_download(info=[]) +``` + +下载批量文件。 + +**参数描述:** + +- `info`-批量下载列表,列表的元素均为包含了`url`和`file_name`的字典,类型为list。 + +**返回值描述**: + +下载失败时返回下载失败的列表,类型为list。下载成功时返回空。 + +**示例**: + +```python +download_list = [{'url': 'http://www.example.com/app.py', 'file_name': '/usr/app.py'}, {'url': 'http://www.example.com/test.txt', 'file_name': '/usr/text.txt'}] +fota.bulk_download(download_list) +``` + +该示例中,假设`http://www.example.com/test.txt`下载失败,则该方法返回值为`[{url: 'http://www.example.com/test.txt', file_name: '/usr/text.txt'}]`。 + +## 设置升级标志相关功能 + +### `fota.set_update_flag` + +```python +fota.set_update_flag() +``` + +设置升级标志。设置完成升级标志后,调用重启接口,重启后即可启动升级工作。升级完成后会直接进入应用程序。 + diff --git a/docs/API_reference/zh/syslib/atcmd.md b/docs/API_reference/zh/syslib/atcmd.md new file mode 100644 index 0000000000000000000000000000000000000000..3c8b02ff80336452cf3ad24d3522b1b65ce84724 --- /dev/null +++ b/docs/API_reference/zh/syslib/atcmd.md @@ -0,0 +1,50 @@ +# atcmd - 发送AT指令功能 + +该模块提供发送AT指令的方法,使模组能够通过Python代码发送AT指令。 + + + +## 发送AT指令 + +### `atcmd.sendSync` + +``` +atcmd.sendSync(atcmd,resp,expect,timeout) +``` + +该方法用于向模组发送AT指令。 + +**参数描述:** + +* `atcmd` - 需要发送的AT指令,字符串类型,必须包含'\r\n'。 +* `resp` - AT指令返回的字符串内容,字符串类型。 +* `expect` - 期望指令返回的结果中所包含的字符串,字符串类型,具体作用见下表: + +| 值 | 含义 | +| ---------- | ------------------------------------------------------------ | +| `空字符串` | 获取AT指令返回的所有数据(不包含‘OK’等结果性的字符数据)放入`resp`参数中; | +| `不为空` | 筛选包含该字符串的数据放入`resp`参数中。 | + +* `timeout` - 超时时间,整型值,单位/秒。 + +**返回值描述:** + +返回一个整型值,`0`表示成功,`非0`表示失败。 + +**示例:** + +```python +>>> import atcmd +>>> resp=bytearray(50) +>>> atcmd.sendSync('at+cpin?\r\n',resp,'',20) +0 +>>> print(resp) +bytearray(b'\r\n+CPIN: READY\r\n\n\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') + +atcmd.sendSync('at+cpin\r\n',resp,'',20) +1 +>>> print(resp) +bytearray(b'\r\nERROR\r\n\n +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +``` diff --git a/docs/API_reference/zh/syslib/example.md b/docs/API_reference/zh/syslib/example.md new file mode 100644 index 0000000000000000000000000000000000000000..787e9648b6625aeb1ac7b23f8e992653f8899fc2 --- /dev/null +++ b/docs/API_reference/zh/syslib/example.md @@ -0,0 +1,47 @@ +# example - 执行python脚本 + +提供方法让用户可以在命令行或者代码中执行python脚本。 + +### `example.exec` + +```python +example.exec(filePath) +``` + +执行指定的python脚本文件。 + +**参数描述** + +* `filePath`,string类型, 要执行python脚本文件的绝对路径 + +**示例** + +```python +# 假设有文件test.py,内容如下 + +def myprint(): + count = 10 + while count > 0: + count -= 1 + print('##### test #####') + +myprint() + +#将test.py文件上传到模块中,进入命令行执行如下代码 +>>> uos.listdir('/usr/') +['apn_cfg.json', 'test.py'] +>>> import example +>>> example.exec('/usr/test.py') +# 执行结果如下 + +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +##### test ##### +``` diff --git a/docs/API_reference/zh/syslib/fota.md b/docs/API_reference/zh/syslib/fota.md new file mode 100644 index 0000000000000000000000000000000000000000..8e1aef4b33c1aeee9baa19e55c2683098ee51144 --- /dev/null +++ b/docs/API_reference/zh/syslib/fota.md @@ -0,0 +1,334 @@ +# fota - 固件升级相关功能 + +`fota`模块用于固件升级。 + +**示例**: + +```python +#远程升级 + +import fota +import utime +import log +import checkNet + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +fota_log = log.getLogger("Fota") + +PROJECT_NAME = "QuecPython_fota_example" +PROJECT_VERSION = "1.0.0" + +checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION) + +def result(args): + print('download status:',args[0],'download process:',args[1]) + +def run(): + stagecode, subcode = checknet.wait_network_connected(30) + if stagecode == 3 and subcode == 1: + fota_obj = fota() # 创建Fota对象 + fota_log.info("httpDownload...") + #差分升级方式 + res = fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) + #mini fota方式 + #res = fota_obj.httpDownload(url1="http://www.example.com/fota1.bin",url2="http://www.example.com/fota2.bin") + #差分升级FTP方式 + #res = fota_obj.httpDownload(url1="ftp://user:password@ip:port/fota.bin",callback=result) #其中user,password,ip,port需要填写具体使用的FTP服务器信息 + if res != 0: + fota_log.error("httpDownload error") + return + fota_log.info("wait httpDownload update...") + utime.sleep(2) + else: + socket_log.info('Network connection failed! stagecode = {}, subcode = {}'.format(stagecode, subcode)) + +if __name__ == '__main__': + fota_log.info("run start...") + run() +``` + +```python +#本地升级 + +import fota +import utime +import log +from misc import Power +import uos + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +fota_log = log.getLogger("Fota") + +# 此示例需要升级包文件(差分包等.bin文件),且存放到文件系统中 + +def run(): + fota_obj = fota() # 创建Fota对象 + file_size = uos.stat("/usr/FotaFile.bin")[6] # 获取文件总字节数 + print(file_size) + with open("/usr/FotaFile.bin", "rb")as f: # rb模式打开.bin文件(需要制作升级包文件) + while 1: + c = f.read(1024) # read + if not c: + break + fota_obj.write(c, file_size) # 写入.bin文件数据与文件总字节数 + + fota_log.info("fota image flush...") + res = fota_obj.flush() # 刷新 + if res != 0: + fota_log.error("flush error") + return + fota_log.info("fota image verify...") + res = fota_obj.verify() # 校验 + if res != 0: + fota_log.error("verify error") + return + fota_log.info("power_reset...") + utime.sleep(2) + Power.powerRestart() # 重启模块 + + +if __name__ == '__main__': + fota_log.info("run start...") + run() +``` + + + +## 初始化相关功能 + +### `fota` + +```python +fota(reset_disable=) +``` + +创建fota对象。 + +**参数描述:** + +- `reset_disable`-可选参数,是否关闭下载完升级包后自动重启功能。传入1关闭自动重启功能,不传入该参数或传入0则保留自动重启功能。 + +**返回值描述:** + +- fota对象。 + + + +> EC600N/EC800N/EG912N/EG915N/EC600M/EC800M/EG810M型号不支持关闭下载完升级包后自动重启功能。 + + + +**示例**: + +```python +import fota +fota_obj = fota() #下载完自动重启 +# fota_obj = fota(reset_disable=1) #下载完不自动重启 +``` + +## 远程升级相关功能 + +一个接口实现升级包下载和升级整个过程。 + +### `fota_obj.httpDownload` + +```python +fota_obj.httpDownload(url1=, url2=, callback=, ssl_params=) +``` + +升级包下载、写入、校验及重启升级,下载协议为HTTP。 + +**参数描述:** + +- `url1`-可选参数,升级包的url,类型为str。 +- `url2`-可选参数,mini fota第二阶段升级包的url,类型为str。注:仅mini fota方式需要传入该参数,差分升级方式该参数禁止传入。mini fota方式为小存储平台特殊的固件升级方式,分为2个阶段。而差分升级方式只有一个阶段,仅EC600N/EC800N/EG912N/EC600M/EC800M/EG810M型号支持mini fota方式。 +- `callback`-可选参数,回调函数,显示下载进度和状态,类型为function。注:mini fota方式不支持回调函数。回调函数参数含义如下。 + +| callback参数 | 参数类型 | 参数说明 | +| ------------ | :------- | ------------------------------------------------------------ | +| args[0] | int | 表示下载状态,下载成功返回整型值:0或1或2,下载失败返回整型值:非0、1、2,表示错误码。 | +| args[1] | int | 表示下载进度(注:EC600N/EC800N/EG912N平台当下载状态是成功时表示百分比,下载状态是失败时表示错误码)。 | + +- `ssl_params`-可选参数,SSL认证时传入证书、密钥、SSL版本和身份验证模式,类型为字典。格式为{"ca_cert": ca_certificate_content, "client_cert": client_certificate_content, "client_key": client_key_content, "ssl_version": 1, "sec_level": 2}。参数含义如下。 + +| key | value类型 | value含义 | +| ------------- | --------- | ------------------------------------------------------------ | +| "ca_cert" | str | 受信任CA证书 | +| "client_cert" | str | 客户端证书 | +| "client_key" | str | 客户端密钥 | +| "ssl_version" | int | SSL版本:0-SSL 3.0,1-TLS 1.0,2-TLS 1.1,3-TLS 1.2,4-全部 | +| "sec_level" | int | 身份验证模式:0-无身份验证模式,1-进行服务器身份验证,2-进行服务器和客户端身份验证 | + +> SSL认证功能支持的型号:EC200A/UC200A。 + +**返回值描述:** + +执行成功返回整形值0,执行失败返回整形值-1。注:EC600N/EC800N/EG912N/EC600M/EC800M/EG810M/BC25PA型号,返回值只代表接口执行成功或失败,升级状态和结果需通过回调反馈。其他型号返回0表示下载和校验成功,返回-1表示下载或校验失败。 + +**示例**: + +```python +def result(args): + print('download status:',args[0],'download process:',args[1]) + +#差分升级HTTP方式 +fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) +#差分升级HTTPS双向认证方式 +fota_obj.httpDownload(url1="https://www.example.com/fota.bin",callback=result,ssl_params={"ca_cert": ca_certificate_content, "client_cert": client_certificate_content, "client_key": client_key_content, "ssl_version": 1, "sec_level": 2}) +#mini fota方式 +fota_obj.httpDownload(url1="http://www.example.com/fota1.bin",url2="http://www.example.com/fota2.bin") +``` + +### `fota_obj.ftpDownload` + +```python +fota_obj.ftpDownload(url=, callback=) +``` + +升级包下载、写入、校验及重启升级,下载协议为FTP。 + +**参数描述:** + +- `url`-必选参数,升级包的url,类型为str。 +- `callback`-可选参数,回调函数,显示下载进度和状态,类型为function。回调函数参数含义如下。 + +| callback参数 | 参数类型 | 参数说明 | +| ------------ | :------- | ------------------------------------------------------------ | +| args[0] | int | 表示下载状态,下载成功返回整型值:0,下载失败返回整型值:非0,表示错误码。 | +| args[1] | int | 表示下载进度。 | + +**返回值描述:** + +执行成功返回整形值0,执行失败返回整形值-1。 + +**示例**: + +```python +def result(args): + print('download status:',args[0],'download process:',args[1]) + +fota_obj.ftpDownload(url="ftp://user:password@ip:port/fota.bin",callback=result) #其中user,password,ip,port需要填写具体使用的FTP服务器信息 +``` + +> FTP下载接口支持型号:EC200A/UC200A/BG95/BG600L/EC600U/EC200U/EG915U。 + +### `fota_obj.apn_set` + +```python +fota_obj.apn_set(fota_apn=,ip_type=,fota_user=,fota_password=) +``` + +设置FOTA下载使用的APN信息。 + +**参数描述:** + +- `fota_apn`-可选参数,APN,类型为str。 +- `ip_type`-可选参数,IP类型:0-IPV4,1-IPV6,类型为int。 +- `fota_user`-可选参数,用户名,类型为str。 +- `fota_password`-可选参数,密码,类型为str。 + +**返回值描述:** + +写入成功返回整型值0,写入失败返回整型值-1。 + +**示例**: + +```python +fota_obj.apn_set(fota_apn="CMNET",ip_type=0,fota_user="abc",fota_password="123") +``` + + + +> 该接口目前支持型号:BG95。 + + + +### `fota_obj.download_cancel` + +```python +fota_obj.download_cancel() +``` + +取消正在进行的FOTA下载。 + +**返回值描述:** + +取消成功返回整型值0,取消失败返回整型值-1。 + +**示例**: + +```python +import fota +import _thread +import utime + +def th_func(): + utime.sleep(40) #时间根据升级包的大小来定,确保在下载完之前取消 + fota_obj.download_cancel() + +def result(args): + print('download status:',args[0],'download process:',args[1]) + +fota_obj = fota() +_thread.start_new_thread(th_func, ()) +fota_obj.httpDownload(url1="http://www.example.com/fota.bin",callback=result) +``` + + + +> 该接口目前支持型号:BG95。 + + + +## 本地升级相关功能 + +已经获取到升级包内容,调用如下接口实现升级包内容写入flash、校验及重启升级。 + +### `fota_obj.write` + +```python +fota_obj.write(bytesData, file_size) +``` + +写入升级包数据流。 + +**参数描述:** + +- `bytesData`-升级包内容数据,类型为bytes。 +- `file_size`-升级包文件总大小(单位:字节),类型为int。 + +**返回值描述:** + +写入成功返回整型值0,写入失败返回整型值-1。 + +### `fota_obj.flush` + +```python +fota_obj.flush() +``` + +刷新RAM缓存数据到flash。由于升级包文件的大小和代码中的RAM缓存大小不一定是整数倍的关系,所以最后一次调用`fota_obj.write`之后需要调用`fota_obj.flush`将RAM缓存中的数据写入flash。 + +**返回值描述:** + +刷新成功返回整型值0,刷新失败返回整型值-1。 + +### `fota_obj.verify` + +```python +fota_obj.verify() +``` + +升级包校验。 + +**返回值描述:** + +升级包校验成功返回整型值0,校验失败返回整型值-1。 + + + +> 本地升级相关功能,目前支持型号:EC600NCNLC/EC600NCNLF/EG912N/EC600U/EC200U/EG915U/EG912U/EC800G/EC600E/EC800E。 +> + diff --git a/docs/API_reference/zh/syslib/log.md b/docs/API_reference/zh/syslib/log.md new file mode 100644 index 0000000000000000000000000000000000000000..6d12317abc19a1bc1aaa2c21c05e1d81bdc511f5 --- /dev/null +++ b/docs/API_reference/zh/syslib/log.md @@ -0,0 +1,189 @@ +# log -日志输出 + +在程序开发中,日志(log)是一种用于记录应用程序在运行时状态的工具。它可以记录应用程序的运行情况,以及帮助开发人员诊断和解决问题。通过记录日志,开发人员可以更快地找到问题的根本原因,也可以更好地了解应用程序的行为和性能。`log` 模块可以输出不同级别的日志,包括调试信息、警告信息、错误信息等。 + + + +## 日志级别 + +### `log.DEBUG` + +常量,用来标识LOG等级,最详细的日志信息,通常只在开发和调试时使用。 + +### `log.INFO` + +常量,用来标识LOG等级,确认一切按预期运行。 + +### `log.WARNING` + +常量,用来标识LOG等级,表明发生了一些意外,或者指示可能出现问题的情况,但仍然可以继续执行。 + +### `log.ERROR` + +常量,用来标识LOG等级,由于更严重的问题,应用程序已不能执行某些功能。 + +### `log.CRITICAL` + +常量,用来标识LOG等级,指出应用程序中的严重错误,可能导致应用程序停止运行。 + +## 日志设置 + +### `log.basicConfig` + +设置日志输出级别,默认为log.INFO,系统只会输出 level 数值大于或等于该 level 的的日志结果。 + +```python +log.basicConfig(level) +``` + +**参数描述:** + +* `level`-日志等级 + +**返回值描述:** + +无 + +**示例:** + +```python +import log +log.basicConfig(level=log.INFO) +``` + +### `log.set_output` + +设置日志输出的位置,目前只支持uart和usys.stdout + +```python +log.set_output(out) +``` + +**参数描述:** + +* `out` - 日志输出位置,输出到指定串口或者交互口,默认为交互口输出,类型参考示例 + +**返回值描述:** + +无 + +**示例:** + +```python +import log +log.basicConfig(level=log.INFO) +Testlog = log.getLogger("TestLog") + +# 设置输出到debug口 +from machine import UART +uart = UART(UART.UART0, 115200, 8, 0, 1, 0) + +log.set_output(uart) + +Testlog.info("this is a Test log") # 会输出到对应的uart口 + +# 从uart口切换成交互口输出 +import usys +log.set_output(usys.stdout) + +Testlog.info("this is a Test log") # 会输出到交互口 +``` + +## 日志输出 + +### `log.getLogger` + +获取log对象,对象支持输出不同等级的log信息。 + +```python +Testlog = log.getLogger(name) +``` + +**参数描述:** + +* `name` - 当前log对象的主题信息,字符串类型 + +**返回值描述:** + +* log操作句柄,也可理解成log对象,拥有log输出的方法。 + +### `log.debug` + +输出DEBUG级别的日志。 + +```python +Testlog.debug(msg) +``` + +**参数描述:** + +* `msg` - 日志内容,字符串类型 + +### `log.info` + +输出INFO级别的日志。 + +```python +Testlog.info(msg) +``` + +**参数描述:** + +* `msg` - 日志内容,字符串类型 + +### `log.warning` + +输出WARNING级别的日志。 + +```python +Testlog.warning(msg) +``` + +**参数描述:** + +* `msg` - 日志内容,字符串类型 + +### `log.error` + +输出ERROR级别的日志。 + +```python +Testlog.error(msg) +``` + +**参数描述:** + +* `msg` - 日志内容,字符串类型 + +### `log.critical` + +输出CRITICAL级别的日志。 + +```python +Testlog.critical(msg) +``` + +**参数描述:** + +* `msg` - 日志内容,字符串类型 + + +**示例:** + +```python +import log + +# 设置日志输出级别 +log.basicConfig(level=log.INFO) +# 获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象 +Testlog = log.getLogger("Quec") + +Testlog.error("Test error message!!") +Testlog.debug("Test debug message!!") +Testlog.critical("Test critical message!!") +Testlog.info("Test info message!!") +Testlog.warning("Test warning message!!") +``` + + + diff --git a/docs/API_reference/zh/syslib/modem.md b/docs/API_reference/zh/syslib/modem.md new file mode 100644 index 0000000000000000000000000000000000000000..ec3b4f3abe7aebd70b1faf9772087ea50f99cbde --- /dev/null +++ b/docs/API_reference/zh/syslib/modem.md @@ -0,0 +1,131 @@ +# modem - 设备相关 + +modem模块提供读取设备信息的方法 + +## 获取设备的IMEI +> FCM360W不支持该方法 +### `modem.getDevImei` + +```python +modem.getDevImei() +``` + +获取设备的IMEI。 + +**返回值描述** + +成功返回string类型设备的IMEI,失败返回整型值 `-1`。 + +**示例** + +```python +>>> import modem +>>> modem.getDevImei() +'866327040830317' +``` + +## 获取设备型号 + +### `modem.getDevModel` + +```python +modem.getDevModel() +``` + +获取设备型号。 + +**返回值描述** + + 成功返回string类型设备型号,失败返回整型值 `-1`。 + +**示例** + +```python +>>> modem.getDevModel() +'EC100Y' +``` + +## 获取设备序列号 +> FCM360W不支持该方法 +### `modem.getDevSN` + +```python +modem.getDevSN() +``` + +获取设备序列号。 + +**返回值描述** + + 成功返回string类型设备序列号,失败返回整型值 `-1`。 + +**示例** + +```python +>>> modem.getDevSN() +'D1Q20GM050038341P' +``` + +## 获取固件版本号 + +### `modem.getDevFwVersion` + +```python +modem.getDevFwVersion() +``` + +获取设备固件版本号。 + +**返回值描述** + + 成功返回string类型固件版本号,失败返回整型值 `-1`。 + +**示例** + +```python +>>> modem.getDevFwVersion() +'EC100YCNAAR01A01M16_OCPU_PY' +``` + +## 获取设备制造商ID + +### `modem.getDevProductId` + +```python +modem.getDevProductId() +``` + +获取设备的制造商ID。 + +**返回值描述** + + 成功返回设备制造商ID,失败返回整型值`-1`。 + +**示例** + +```python +>>> modem.getDevProductId() +'Quectel' +``` + +## 获取设备MAC +>仅FCM360W支持该方法 + +### `modem.getDevMAC` + +```python +modem.getDevMAC() +``` + +获取设备的MAC。 + +**返回值描述** + + 成功返回设备MAC,失败返回整型值`-1`。 + +**示例** + +```python +>>> modem.getDevMAC() +'e8:24:4:d8:a2:4b' +``` diff --git a/docs/API_reference/zh/syslib/osTimer.md b/docs/API_reference/zh/syslib/osTimer.md new file mode 100644 index 0000000000000000000000000000000000000000..95e18de62f57db1a71a73a0c938dcad3821193f2 --- /dev/null +++ b/docs/API_reference/zh/syslib/osTimer.md @@ -0,0 +1,62 @@ +# osTimer - os定时器 + +模组提供底层os的定时器接口,os定时器超时会触发其绑定的回调函数。 + +**示例** + +```python +import osTimer + +def test_cb(arg): + print("osTimer Expired!!") +# 创建os定时器 +timer = osTimer() +# 启动定时器,参数依次为时间、是否循环、回调函数 +timer.start(10000,1,test_cb) +# 停止定时器 +timer.stop() +``` + + +## 创建定时器 + +### `osTimer` + +```python +osTimer() +``` + +创建osTimer定时器对象 + +> 相比[machine.Timer](./machine.Timer.md),此定时器不存在创建个数的限制 + +## 启动定时器 + +### `osTimer.start` + +```python +osTimer.start(initialTime, cyclialEn, callback) +``` + +**参数描述** + +* `initialTime`,定时器超时的时间(单位ms),int类型 +* `cyclialEn`,是否循环,0为单次,1为循环,int类型 +* `callback`,定时器超时触发的回调,function类型,原型为callback(arg),`arg`未实际使用,可直接传入`None` + +**返回值描述** + +int类型,0为成功,其余为失败 + +## 停止定时器 + +### `osTimer.stop` + +```python +osTimer.stop() +``` +停止定时器 + +**返回值描述** + +int类型,0为成功,其余为失败 diff --git a/docs/API_reference/zh/syslib/pm.WakeUp.md b/docs/API_reference/zh/syslib/pm.WakeUp.md new file mode 100644 index 0000000000000000000000000000000000000000..44992e6d2cae8a813396f8cad8c1294adbd2c130 --- /dev/null +++ b/docs/API_reference/zh/syslib/pm.WakeUp.md @@ -0,0 +1,120 @@ +# class WakeUp - 唤醒中断 + +EC600/EC800E/EC800Z系列的普通GPIO不支持双边沿触发中断,且不支持休眠下中断唤醒。WakeUp则没有上下拉的限制,默认支持双边沿触发中断以及在休眠状态下唤醒模组。使用方法如下: + +## **构造函数** + +```python +class pm.WakeUp(WakeupID, pull,[edge]) +``` + +**参数说明:** + +- `WakeupID` - 需要控制的wakeup号,点此查看
+- `pull` - 上下拉模式,int类型,说明如下:
`PULL_DISABLE`– 浮空模式0
`PULL_PU` – 上拉模式1
`PULL_PD` – 下拉模式2
+ +- `[edge_enable]` - 触发边沿设置, int类型,缺省值为双边沿触发,说明如下:
`IRQ_RISING`-仅使能上升沿触发
+ + `IRQ_FALLING`-仅使能下降沿触发
`IRQ_RISING_FALLING`-使能双边沿触发 + +> `[edge_enable]`仅EC800Z支持设置。 + +**初始化示例:** + +```python +WakeUp(WakeUp.WAKEUP5,WakeUp.PULL_PD,WakeUp.IRQ_RISING)#EC800Z 配置为上升沿触发 +WakeUp(WakeUp.WAKEUP5,WakeUp.PULL_PD,WakeUp.IRQ_FALLING)#EC800Z 配置为下降沿触发 +``` + +**示例:** + +```python +from pm import WakeUp +def fun(level): + print(str(level)) + +wake=WakeUp(WakeUp.WAKEUP5,WakeUp.PULL_PD) +wake.set_callback(fun)# 设置回调,回调仅返回电平 +wake.enable()# 使能中断 + +wake.read() #读引脚电平 +``` + +## 方法 + +### `wake.enable` + +```python +wake.enable() +``` + +该方法用于使能唤醒中断,当WakeUp引脚检测到上升沿或者下降沿时,会调用callback执行。 + +**返回值:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `wake.disable` + +```python +wake.disable() +``` + +该方法用于关闭中断,禁用与WakeUp对象关联的中断 。 + +**返回值:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `wake.read` + +```python +wake.read() +``` + +该方法用于读取当前引脚电平。 + +**返回值:** + +返回引脚电平,`0`表示获取到的引脚电平为低,`1` 表示获取到的引脚电平为高。 + +### `wake.deinit` + +```python +wake.deinit() +``` + +关闭WakeUp功能。 + +**返回值:** + +成功返回整型值`0`,失败返回整型值`-1`。 + +### `wake.set_callback` + +```python +wake.set_callback(fun) +``` + +该方法用于设置回调,触发中断后,会执行该回调,回调返回电平。 + +**参数描述:** + +- `fun` - 回调函数,回调函数原型: + + ``` + fun(level) + ``` + + 回调函数参数描述: + + - level:`0`:低电平,`1`:高电平。 + +**WakeUp编号与物理引脚的映射关系:** + + +| 模组 | WakeUp对应引脚说明 | +| ------ | ------------------------------------------------------------ | +| EC800E | `WAKEUP2` - 引脚号79
`WAKEUP3` - 引脚号109(EC800ECN_LE&LQ&LC不可用)
`WAKEUP4` - 引脚号108(EC800ECN_LE&LQ&LC不可用)
`WAKEUP5` - 引脚号19 | +| EC600E | `WAKEUP2` - 引脚号9
`WAKEUP3` - 引脚号51
`WAKEUP4` - 引脚号50
`WAKEUP5` - 引脚号39 | +| EC800Z | `WAKEUP0` - 引脚号87(低压模组是107脚)
`WAKEUP2` - 引脚号79
`WAKEUP3` - 引脚号109
`WAKEUP4` - 引脚号108
`WAKEUP5` - 引脚号19 | \ No newline at end of file diff --git a/docs/API_reference/zh/syslib/pm.md b/docs/API_reference/zh/syslib/pm.md new file mode 100644 index 0000000000000000000000000000000000000000..35d915a79cd036800340e65fd6915507fadb9b8d --- /dev/null +++ b/docs/API_reference/zh/syslib/pm.md @@ -0,0 +1,243 @@ +# pm - 低功耗 + +在无业务处理时使系统进入休眠状态,进入低功耗模式。 + +**使用示例** + +模拟测试,实际开发请根据业务场景选择使用! + +```python +import pm +import utime + +# 创建wakelock锁 +lpm_fd = pm.create_wakelock("test_lock", len("test_lock")) +# 设置自动休眠模式 +pm.autosleep(1) + +# 模拟测试,实际开发请根据业务场景选择使用 +while 1: + utime.sleep(20) # 休眠 + res = pm.wakelock_lock(lpm_fd) + print("ql_lpm_idlelock_lock, g_c1_axi_fd = %d" %lpm_fd) + print("unlock sleep") + utime.sleep(20) + res = pm.wakelock_unlock(lpm_fd) + print(res) + print("ql_lpm_idlelock_unlock, g_c1_axi_fd = %d" % lpm_fd) + num = pm.get_wakelock_num() # 获取已创建锁的数量 + print(num) +``` + +## 创建wake_lock锁 + +### `pm.create_wakelock` + +```python +pm.create_wakelock(lock_name, name_size) +``` + +创建wake_lock锁。 + +**参数描述** + +* `lock_name`,自定义lock名,string类型。 +* `name_size`, 可选参数,lock_name的长度, int类型。 + +**返回值描述** + +成功返回wakelock的标识号,否则返回 `-1`。 + +> BC25PA平台不支持此方法。 + +## 删除wake_lock锁 + +### `pm.delete_wakelock` + +```python +pm.delete_wakelock(lpm_fd) +``` + +删除wake_lock锁。 + +**参数描述** + +* `lpm_fd`,需要删除的锁对应标识id,int类型。 + +**返回值描述** + +成功返回 `0`。 + +> BC25PA平台不支持此方法。 + +## 加锁 + +### `pm.wakelock_lock` + +```python +pm.wakelock_lock(lpm_fd) +``` + +将指定的wakelock置于锁定状态,存在锁定状态的锁时,模组不会进入低功耗状态 + +**参数描述** + +* `lpm_fd`,需要执行加锁操作的wakelock标识id,int类型。 + +**返回值描述** + +成功返回 `0`,否则返回 `-1`。 + +> BC25PA平台不支持此方法。 + +## 释放锁 + +### `pm.wakelock_unlock` + +```python +pm.wakelock_unlock(lpm_fd) +``` + +释放锁,所有wakelock被释放时,模组才允许进入低功耗 + +**参数描述** + +* `lpm_fd`,需要执行释放锁操作的wakelock标识id,int类型。 + +**返回值描述** + +成功返回 `0`,否则返回 `-1`。 + +> BC25PA平台不支持此方法。 + +## 自动休眠模式控制 + +### `pm.autosleep` + +```python +pm.autosleep(sleep_flag) +``` + +自动休眠模式控制 + +**参数描述** + +* `sleep_flag`,`0`关闭自动休眠, `1`开启自动休眠,int类型。 + +**返回值描述** + +成功返回 `0`,失败返回 `-1` + +## 获取已创建的锁数量 + +### `pm.get_wakelock_num` + +```python +pm.get_wakelock_num() +``` + +获取已创建的锁数量 + +**返回值描述** + +int类型,返回已创建wakelock锁的数量。 + +> BC25PA平台不支持此方法。 + +## 设置PSM模式的控制时间 + +### `pm.set_psm_time` + +```python +pm.set_psm_time(tau_uint,tau_time,act_uint,act_time) # 设置并启用PSM <模式1> + +pm.set_psm_time(mode)# 单独设置启用或禁用 <模式2> +``` + +**参数描述** + +* `mode`,是否启用PSM,int类型: + `0 `禁用PSM + `1 `启用PSM + `2 `(仅BC25平台)禁用PSM并删除PSM的所有参数,如有默认值,则重置默认值。(注意此种模式禁用的情况下,如果要启用PSM必须用**模式1**,用**模式2**没有任何的意义,因为设置的TAU和ACT时间全部清零了。) +* `tau_uint`,tau(T3412)定时器单位,int类型。 + +| tau定时器单位值 | 类型 | 单位值说明 | +| --------------- | ---- | ------------ | +| 0 | int | 10 分钟 | +| 1 | int | 1 小时 | +| 2 | int | 10 小时 | +| 3 | int | 2 秒 | +| 4 | int | 30 秒 | +| 5 | int | 1 分钟 | +| 6 | int | 320 小时 | +| 7 | int | 定时器被停用 | + +* `tau_time`,tau(T3412)定时器时间周期值,int类型。 +* `act_uint`,act(T3324)定时器单位,int类型。 + +| act定时器单位值 | 类型 | 单位值说明 | +| --------------- | ---- | ------------ | +| 0 | int | 2 秒 | +| 1 | int | 1 分钟 | +| 2 | int | 6 分钟 | +| 7 | int | 定时器被停用 | + +* `act_time`,act(T3324)定时器时间周期值,int类型。 + +> 实际设置的tau和act,为单位值和周期值的积 + +**返回值描述** + +`True: ` 成功 +`False:` 失败 + +**示例** + +```python +>>> import pm +>>> pm.set_psm_time(1,2,1,4) #设置tau定时器周期为 1小时 * 2 = 2小时, act定时器周期值为 1分钟 * 4 = 4分钟。 +True +>>> +``` + +> 仅BC25/ECX00U/ECX00E支持 + +## 获取PSM模式的控制时间 + +### `pm.get_psm_time` + +```python +pm.get_psm_time() +``` + +**返回值描述** + +成功:返回值为list类型,说明如下: + +| 参数 | 类型 | 单位值说明 | +| ------- | ---- | ------------------------------------------------------------------------------------------------------------------------- | +| list[0] | int | mode说明:
0-禁用PSM.
1-启用PSM.
2-(仅BC25平台)禁用 PSM 并删除 PSM 的所有参数,若有默认值,则重置为默认值。 | +| list[1] | int | tau定时器单位 | +| list[2] | int | tau定时器时间周期值 | +| list[3] | int | act定时器单位 | +| list[4] | int | act定时器时间周期值 | + +失败:返回 `None`。 + +**示例** + +```python +>>> pm.get_psm_time() + +[1, 1, 1, 1, 2] + + +``` + +> 仅BC25/ECX00U/ECX00E平台支持 + +## Classes + +- [class WakeUp – 唤醒中断](./pm.WakeUp.md) + diff --git a/docs/API_reference/zh/syslib/ql_fs.md b/docs/API_reference/zh/syslib/ql_fs.md new file mode 100644 index 0000000000000000000000000000000000000000..c66e7f1475f3e7f8acce83a0381d579a173c870c --- /dev/null +++ b/docs/API_reference/zh/syslib/ql_fs.md @@ -0,0 +1,220 @@ +# ql_fs - 高级文件操作 + +模块功能: 用于文件的高级操作 + + + +## 查看文件或文件夹是否存在 + +### `ql_fs.path_exists` + +```python +ql_fs.path_exists(file_path) +``` + +**参数描述:** + +* `file_path`-文件路径, string类型, 文件或文件夹的绝对路径 + +**返回值描述:** + +存在返回 True, 不存在返回False + +**示例:** + +```python +>>> import ql_fs +>>> ret = ql_fs.path_exists("/usr/xxx.py") +>>> print(ret) + +# 存在打印True 不存在 FalseCopy to clipboardErrorCopied +``` + + + +## 获取文件所在文件夹路径 + +### `ql_fs.path_dirname` + +```python +ql_fs.path_dirname(file_path) +``` + +**参数描述:** + +* `file_path`-文件路径, string类型, 文件或文件夹的绝对路径 + +**返回值描述:** + +string类型的路径地址 + +**示例:** + +```python +>>> import ql_fs +>> ret = ql_fs.path_dirname("/usr/bin") +>>> print(ret) + +# 打印结果如下 +# /usr +``` + + + +## 创建文件夹 + +### `ql_fs.mkdirs` + +```python +ql_fs.mkdirs(dir_path) +``` + +该方法递归式创建文件夹, 传入文件夹路径 + +**参数描述:** + +* `dir_path`-文件路径, string类型, 所要创建的文件夹绝对路径 + +**示例:** + +```python +>>> import ql_fs +>>> ql_fs.mkdirs("usr/a/b") +``` + + + + + +## 删除文件夹 + +### `ql_fs.rmdirs` + +```python +ql_fs.rmdirs(dir_path) +``` + +**参数描述:** + +* `dir_path`-文件路径, string类型, 所要删除的文件夹绝对路径 + +**示例:** + +```python +>>> import ql_fs + +>>> ql_fs.rmdirs("usr/a/b") +``` + + + +## 获取文件大小 + +### `ql_fs.path_getsize` + +```python +ql_fs.path_getsize(file_path) +``` + +**参数:** + +* `file_path`-文件路径, string类型, 文件或文件夹的绝对路径 + +**返回值** + +int类型的数字, 单位是字节 + +**示例** + +```python +import ql_fs + +ql_fs.path_getsize('usr/system_config.json') +``` + + + +## 创建文件 + +### `ql_fs.touch` + +```python +ql_fs.touch(file, data) +``` + +创建文件或者更新文件数据, 创建指定文件也可传入文本文件更新, 会自动创建文件夹然后创建或更新文件的内容 + +**参数描述:** + +* `file`-文件路径, string类型, 文件的绝对路径 + +* `data`-数据, dict类型, 所要写入的数据,目前只支持json文件 + +**返回值描述:** + +int类型, 0为成功, -1则失败 + +**示例**: + +```python +>>> import ql_fs +>>> data = {"test":1} +>>> ql_fs.touch("/usr/bin/config.json", data) +``` + + + +## 读取json文件 + +### `ql_fs.read_json` + +```python +ql_fs.read_json(file) +``` + +json文件类型的直接读取json文件并返回, 非json文件类型返回为读取的字符串数据类型 + +**参数描述:** + +* `file`-文件路径, string类型, 文件或文件夹的绝对路径 + +**返回值描述:** + +读取成功, 返回dict类型 + +失败, 返回None + +**示例**: + +```python +>>> import ql_fs +>>> data = ql_fs.read_json("/usr/system_config.json") +``` + + + +## 文件拷贝 + +### `ql_fs.file_copy` + +```python +ql_fs.file_copy(dst, src) +``` + +将文件从原路径拷贝到目标路径 + +**参数描述:** + +* `dst`-目标文件, string类型, 目标路径路径 +*`src`-源文件, string类型, 源文件路径 + +**返回值描述:** + +True代表拷贝成功 + +**示例:**: + +```python +>>> import ql_fs +>>> ql_fs.file_copy("usr/a.json", "usr/system_config.json") +``` \ No newline at end of file diff --git a/docs/API_reference/zh/syslib/securedata.md b/docs/API_reference/zh/syslib/securedata.md new file mode 100644 index 0000000000000000000000000000000000000000..a63da61fb3ae38749a92086076885d985f973745 --- /dev/null +++ b/docs/API_reference/zh/syslib/securedata.md @@ -0,0 +1,79 @@ +# SecureData - 安全数据区 + +模组提供一块裸flash区域及专门的读写接口供客户存贮重要信息,且信息在烧录固件后不丢失(烧录不包含此功能的固件无法保证不丢失)。提供一个存储和读取接口,不提供删除接口。 + + +> 目前除BC25/BG95/EC200A系列外,其余系列均支持本功能 + +**示例** + +```python +import SecureData +# 即将存储的数据buf +databuf = '\x31\x32\x33\x34\x35\x36\x37\x38' +# 在index为1的存储区域中存储长度为8的数据databuf +SecureData.Store(1, databuf, 8) +# 定义一个长度为20的数组用于读取存储的数据 +buf = bytearray(20) +# 读取index为1的存储区域中的数据至buf中,将读取到数据的长度存储在变量length中 +length = SecureData.Read(1, buf, 20) +# 输出读到的数据 +print(buf[:length]) +``` + + +## 数据存储 + +### `SecureData.Store` + +```python +SecureData.Store(index,databuf,len) +``` + +**参数描述** + +* `index`,int类型 + +| index序号 | 最大存储量 | +| --------- | ---------- | +| 1 - 8 | 52字节 | +| 9 - 12 | 100字节 | +| 13 - 14 | 500字节 | +| 15 - 16 | 1000字节 | +* FCM362K型号专用: + +| index序号 | 最大存储量 | +| --------- | ---------- | +| 1 - 6 | 248字节 | +| 7 - 8 | 1016字节 | +* `databuf`,待存储的数据数组,bytearray类型 +* `len`,要写入数据的长度,int类型 + +> 存储时按照databuf和len两者中长度较小的进行存储 + +**返回值描述** + +`-1`: 参数有误 +`0`: 执行正常 + +## 数据读取 + +### `SecureData.Read` + +```python +SecureData.Read(index,databuf,len) +``` + +**参数描述** + +* `index`,index范围为1-16:待读取数据对应的索引号,int类型 +* `databuf`,存储读取到的数据,bytearray类型 +* `len`,要读取数据的长度,int类型 + +> 若存储的数据没有传入的len大,则返回实际存储的数据长度 + +**返回值描述** + +`-2`存储数据不存在且备份数据也不存在 +`-1`参数有误 +`其他`实际读取到的数据长度 diff --git a/docs/API_reference/zh/syslib/sys_bus.md b/docs/API_reference/zh/syslib/sys_bus.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac5f854e4931e9ca6fd00c635291f52bc865f6b --- /dev/null +++ b/docs/API_reference/zh/syslib/sys_bus.md @@ -0,0 +1,102 @@ +# sys_bus - 会话总线 + +用于消息的订阅和发布广播, 多线程处理等,用于一对多的广播, 类似于内部的mqtt + + + +## 订阅topic + +### `sys_bus.subscribe` + +```python +sys_bus.subscribe(topic, handler) +``` + +**参数描述:** + +* `topic`-主题, string/int类型, 所需要订阅的topic +* `handler`-处理函数, func函数类型, 处理函数, 当有对应topic过来时, 会对应调用其中的处理函数去处理 handler 需要有两个参数(topic, msg) + + + +## 发布topic消息 + +### `sys_bus.publish` + +```python +sys_bus.publish(topic , msg) +``` + +发布消息, 对应订阅的topic将收到并多线程对此消息处理 + +**参数描述:** + +* `topic`-主题, string/int类型, 所需要订阅的topic +* `msg`-消息, 任意类型, 发布的消息 + + + +## 查看会话总线注册表 + +### `sys_bus.sub_table` + +```python +sys_bus.sub_table(topic=None) +``` + +查看订阅注册表, 注册表中有所有topic和订阅的函数 + +**参数描述:** +* `topic`-主题, string/int类型, 传参表示查看此topic的注册表, 不传参表示查看所有的topic的注册表 + +**返回值描述:** + +dict / list类型的订阅函数列表或注册表 + + + +## 解除订阅 + +### `sys_bus.unsubscribe` + +```python +sys_bus.unsubscribe(topic , cb=None) +``` + +解除已订阅的topic, 或者对应topic下的某个函数, 当只传入topic参数时, 会删除topic和从topic下所有的订阅函数, 如果传了cb则删除订阅topic下面订阅列表中的对应的cb函数 + + + +**参数描述:** + +* `topic`-主题, string/int类型, 订阅的topic事件 +* `cb`-回调函数, func函数类型, 要删除的订阅函数, 不传则删除topic + +**返回值描述:** + +True 删除成功, False删除失败 + + + +**示例:** + +```python +import sys_bus + + +def test(topic, msg): + print("test ... topic = {} msg = {}".format(topic, msg)) + +# 订阅 +sys_bus.subscribe("test", test) +# 发布 +sys_bus.publish("test", "this is a test msg") + +# test ... topic = test msg = this is a test msg + +# 解绑对应test topic下的订阅的test函数 +sys_bus.unsubscribe("test", test) + +# 解绑对应test topic下的所有订阅函数 +sys_bus.unsubscribe("test") +``` \ No newline at end of file diff --git a/docs/API_reference/zh/syslib/system.md b/docs/API_reference/zh/syslib/system.md new file mode 100644 index 0000000000000000000000000000000000000000..1c2e68ca32411801bc83b7f3baf9dfc76e759eaf --- /dev/null +++ b/docs/API_reference/zh/syslib/system.md @@ -0,0 +1,119 @@ +# system - 环境配置 + +模块功能:用于配置系统环境的参数以及功能 + +> 适配版本:EC100Y(V0009)及以上;EC600S(V0002)及以上。 + + +### `system.replSetEnable` + +```python +system.replSetEnable(flag,**kw_args) +``` + +开启/关闭交互保护,交互保护设置,参数设置如下 + +1、只有一个参数flag时: + +0表示关闭,1表示开启,2表示查询当前加密状态;设置开启交互保护后所有外部指令以及代码都无法执行,为不可逆操作,请确认后开启,默认不开启。 + +2、有两个参数时: + +表示交互保护可通过密码开启和关闭(少数平台不支持密码保护功能,所以当遇到不支持的平台,输入密码会直接报错。如:BC25,600M) + +**参数描述:** + +* `flag` - int类型, 0 : 不开启(默认);1 :开启;2:查询加密状态 +* `kw_args` - password,可为空 ,字符串类型 + +**返回值描述:** + +* 成功返回整型值0; + +* 失败返回整型值-1或者是errorlist + +如果是查询加密状态,返回值: +-1:查询失败 +1:repl enable +2:repl enable but The password has already been set +3:repl refuse +4:repl-protection by password + + +### `system.replChangPswd` + +```python +system.replChangPswd(old_password,new_password) +``` + +更改交互保护密码 + +**参数描述:** + +* `old_password` - 旧密码 长度限制:6-12字节,字符串类型 +* `new_password` - 新密码 长度限制:6-12字节,字符串类型 + +**返回值描述:** + +* 成功返回整型值0; + +* 失败返回整型值-1或者是errorlist + +**示例:** + +```python +>>>import system + +>>> system.replSetEnable(1,password='miamia123')//开机首次设置密码并开启交互保护,可设置任意长度在6-12位之间的密码内容 +0 +>>> //设置成功,交互口被锁,需要输入密码才能正常使用 +Please enter password: +>>> ****** //密码错误 +Incorrect password, please try again: +>>> ******** //密码错误 +Incorrect password, please try again: +>>> ********* //密码正确,可正常交互 +REPL enable +>>> system.replSetEnable(2) +2 +>>> + +>>> system.replSetEnable(1,password='miamia') //已经设置过密码,如果需要重新锁住交互口,需要输入正确密码 +Incorrect password! +-1 +>>> system.replSetEnable(1,password='miamia123') +0 +>>> +Please enter password: //交互口重新锁住 +>>> miamia123 +********* +REPL enable +>>> system.replSetEnable(2) +2 + + +>>> system.replChangPswd(old_password='miamia123',new_password='123456') //change password +0 +>>> system.replSetEnable(1,password='miamia123') //更改密码成功之后,继续用老密码锁交互口,提示密码不正确 +Incorrect password! +-1 +>>> system.replSetEnable(1,password='123456') //新密码重新加锁交互口,成功 +0 +>>> +Please enter password: +>>> ****** +REPL enable + +>>> system.replSetEnable(0,password='123456') //取消密码保护(取消加密保护之后可使用任意新密码重新加锁交互口) + +0 +>>> +>>> system.replSetEnable(2) //查询状态为repl enable +1 +>>> system.replSetEnable(0) //默认就已经是0 +0 +>>>system.replSetEnable(1) //开启交互保护 +>>> +REPL refuse +>>> +``` diff --git a/docs/API_reference/zh/wifilib/README.md b/docs/API_reference/zh/wifilib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b763260646b3e4c2b52499d497b08e381242f85 --- /dev/null +++ b/docs/API_reference/zh/wifilib/README.md @@ -0,0 +1,11 @@ +# QuecPython Wi-Fi通信 + +> QuecPython Wi-Fi通信库包括无线局域网相关的功能组件 + +本文描述了 QuecPython Wi-Fi通信库中的模块。 + +## QuecPython Wi-Fi通信库列表 + +- [WLAN - 无线网络控制](./WLAN.md) +- [ESP8266 - ESP8266驱动](./WLAN.ESP8266.md) +- [ASR5803W - ASR5803驱动](./WLAN.ASR5803W.md) \ No newline at end of file diff --git a/docs/API_reference/zh/wifilib/WLAN.ASR5803W.md b/docs/API_reference/zh/wifilib/WLAN.ASR5803W.md new file mode 100644 index 0000000000000000000000000000000000000000..4af04575c0e8bd2a98514a5416613688691cf93a --- /dev/null +++ b/docs/API_reference/zh/wifilib/WLAN.ASR5803W.md @@ -0,0 +1,123 @@ + +# class ASR5803W - ASR5803W驱动 + +该类用于控制`ASR5803W`型号无线网卡设备。 + +> 支持模组型号:EC200A系列 + +## 构造函数 + +### `network.ASR5803W` + +```python +class network.ASR5803W(mode, wlan_ldo_en_pin, wlan_reset_pin, host_wake_wlan_pin, wlan_wake_host_pin) +``` + +初始化WiFi网卡信息,并返回WiFi网卡对象。 + +**参数描述:** +- `mode` - int类型,无线网卡工作模式,0 为 ap 模式,1 为 sta 模式(目前仅支持 ap 模式)。 +- `wlan_ldo_en_pin` - int类型,WiFi ldo 使能脚。 +- `wlan_reset_pin` - int类型,WiFi reset 脚。 +- `host_wake_wlan_pin` - int类型,模组唤醒 WiFi 脚。 +- `wlan_wake_host_pin` - int类型,WiFi 唤醒模组脚。 + +**示例:** + +```python +import network +from machine import Pin + +nic = network.ASR5803W(0, Pin.GPIO7, Pin.GPIO36, Pin.GPIO34, Pin.GPIO6) +``` + +## 方法 + +### `ASR5803W.active` + +```python +ASR5803W.active([is_active]) +``` + +网卡激活状态配置/查询。 + +若传参则表示进行网卡状态配置。 +若不传参则表示查询网卡状态,返回值True/False表示网卡开启/关闭。 + +**可选参数描述:** + +- `is_active` - bool类型,填True时表示启动网卡并激活config中网卡的配置,为False则代表停用网卡。返回0表示成功,返回其他值表示失败 + + +### `ASR5803W.isconnected` + +```python +ASR5803W.isconnected() +``` + +查询是否连接 + +**返回值描述:** + +- 返回值表示是否有客户端连接,True/False分别表示有连接/无连接。 + + +### `ASR5803W.status` + +```python +ASR5803W.status([param]) +``` + +查询网卡状态。当param不填写时返回当前连接状态,填入对应的状态信息名称时返回该状态的信息。 + +**可选参数描述:** + +- `stations/node` - 获取当前连接客户端设备列表。 +- `speed` - 获取当前网卡网络速率。 + +**返回值描述:** +无传参: +- `True` - 网卡已被连接。 +- `False` - 网卡未被连接。 + +有传参: +- `stations/node` - 返回list类型,当前连接客户端设备列表。若无设备连接返回0;若有设备连接返回一个包含两个元素的列表,元素 1 为当前连接设备数量(int 类型),元素 2 为当前连接设备的信息元组,元组中的信息分别是设备 mac 地址(byte 类型)、设备 IP 地址(string 类型)、设备连接时长(int 类型,单位秒)。 +- `speed` - 返回tuple类型,当前网卡网络速率,元素 1 是下行速率(int 类型),元素 2 是上传速率(int 类型),单位为 bps。 + + +### `ASR5803W.config` + +```python +ASR5803W.config('param') +ASR5803W.config(param=value) +``` + +网络参数查询/配置。 + +当只传参关键字时,接口查询,每次只能查询一个值。 +当传参赋值时,接口设置,返回True/False表示成功/失败,可以同时设置多个值。 + +**可选参数描述:** + +| 参数 | 类型 | 说明 | +| ---- | ---- |---------- | +| `ssid` | `str` | 无线接入点名称 | +| `authmode`| `enum` | 鉴权类型 | +| `security` | `enum` | 加密方式 | +| `password` | `str` | 密码 | +| `protocol` | `enum` | 网络协议 | +| `channel` | `enum` | 无线信道号 | +| `b40acs` | `bool` | LTE band 40 下信道自适应 | +| `mac` | `str` | MAC地址 | + +**示例:** +配置信息查询: +```python +# 查询ssid名称配置 +ASR5803W.config('ssid') +``` +配置信息设置: +```python +# 设置无线名称及信号 +ASR5803W.config(ssid='ssid', channel=1) +``` diff --git a/docs/API_reference/zh/wifilib/WLAN.ESP8266.md b/docs/API_reference/zh/wifilib/WLAN.ESP8266.md new file mode 100644 index 0000000000000000000000000000000000000000..4a4e2423e3435155e9b11a5e9e979efa095f545b --- /dev/null +++ b/docs/API_reference/zh/wifilib/WLAN.ESP8266.md @@ -0,0 +1,287 @@ + +# class ESP8266 - 乐鑫ESP8266驱动 + +该类用于控制`ESP8266`型号无线网卡设备。 + +见github:https://github.com/QuecPython/examples/tree/main/network-comm/nic/wifi + +> 支持模组型号:EC600M/EC600N/EC600U/EC600E/EC800E/EC800M/EC200A系列 + +## 构造函数 + +### `ESP8266` + +```python +class ESP8266(uart=UART.UART1, mod=ESP8266.STA, callback=None) +``` + +加载ESP8266驱动,初始化虚拟网卡,并返回ESP8266对象。 + +**参数描述:** +- `uart` - 整型值,模组UART口选择,表示模组与ESP8266所连接的`串口号`,默认使用`UART1`。 +- `mode` - 整型值,无线网卡工作模式配置,用来指定ESP8266的`工作模式`,STA客户端模式为ESP8266.STA,AP接入点模式为ESP8266.AP,默认使用`STA客户端`模式。 +- `callback` - 回调函数名。设置回调函数,用于`网络变化`以及`ota升级`通知,默认为未开启。 + +**callback参数描述:** +- `content` - 字符串类型,用户回调,表示上报消息内容 + +**上报消息内容描述:** + +开启用户回调后,模组会在ota升级和sta模式连接变化时进行消息上报,以下是上报信息描述。 + +`ota`信息上报: +- `ota,begin` - ota升级开始 +- `ota,downloading,xx` - ota升级下载百分比 +- `ota,restart` - ota升级下载完成进行重启 +- `ota,err_code,x` - ota升级错误码,以下是对错误码(x)的描述: + - `1` - url解析失败 + - `2` - 连接http服务器失败 + - `3` - 为GET请求分配内存失败 + - `4` - 发送GET请求到服务器失败 + - `5` - 升级开始时错误 + - `6` - 接收数据失败 + - `7` - ota文件写入失败 + - `8` - 升级结束时错误 + - `9` - 设置boot分区失败 + +`station`模式网络连接变化上报: +- `station, connected` - wifi已连接 +- `station, disconnected` - wifi断开连接 + +**示例:** + +```python +# callback使用示例 +from usr.WLAN import ESP8266 +from machine import UART + +def cb(args): + content = args + print('wifi content:{}'.format(content)) + +ESP8266 = ESP8266(UART.UART2, ESP8266.STA, cb) + +``` + + +## 方法 + +### `ESP8266.status` + +```python +ESP8266.status() +``` + +获取无线网卡状态信息,用以判断无线网卡当前工作模式。 + +**返回值描述:** + +返回整型值,具体说明如下: +- `0` - esp8266 设备不存在 +- `1` - esp8266 station模式已连接 +- `2` - esp8266 station模式未连接 +- `3` - esp8266 web配网模式 +- `4` - esp8266 ap模式 +- `5` - esp8266 ota升级中 + + + + +### `ESP8266.version` + +```python +ESP8266.version() +``` + +获取无线网卡当前固件版本信息 + +**返回值描述:** + +返回字符串类型,格式为(sdk, model, version, time),具体说明如下: +- `sdk` - sdk信息 +- `model` - 无线网卡型号 +- `version` - 版本号 +- `time` - 版本时间 + + + +### `ESP8266.ipconfig` + +```python +ESP8266.ipconfig() +``` + +获取网卡当前网络配置信息(IP地址、DNS服务器等信息) + +**返回值描述:** + + 返回元组类型,格式为 (ip, subnet, gateway, mtu, primary_dns, secondary_dns),具体说明如下: + +- `ip` - 字符串类型,ip地址 +- `subnet` - 字符串类型,子网掩码 +- `gateway` - 字符串类型,网关 +- `mtu` - 整型值,最大传输单元 +- `primary_dns` - 字符串类型,DNS服务器主地址 +- `secondary_dns` - 字符串类型,DNS服务器辅地址 + + + +### `ESP8266.station` + +```python +ESP8266.station(username,password) +``` + +使无线网卡以`station`工作模式启动,连接指定wifi。 + +**参数描述:** + +- `username` - 字符串类型,填写所要连接的 `WiFi` 的名称(1~32 个字符) +- `password` - 字符串类型,填写所要连接的 `WiFi` 的密码(8~64 个字符) + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 + + + +### `ESP8266.ap` + +```python +ESP8266.ap(username,password) +``` + +使无线网卡以`ap`工作模式启动,作为无线热点。 + +> ap模式理论最多支持`10`个终端设备接入。 + +**参数描述:** + +- `username` - 字符串类型,配置 `WiFi热点` 的名称(1~32 个字符) +- `password` - 字符串类型,配置 `WiFi热点` 的密码(8~64 个字符) + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 + + + +### `ESP8266.web_config` + +```python +ESP8266.web_config(username,password) +``` + +使无线网卡以`web 配网`工作模式启动,用户可通过web页面进行网络配置。 + +> 启用配网功能后,需使用手机/电脑等终端设备通过无线网络连接至无线网卡(用户自定义名称和密码),然后通过浏览器输入192.168.4.1进入配网页面。 + +**参数描述:** + +- `username` - 字符串类型,配置 `配网热点` 的名称(1~32 个字符) +- `password` - 字符串类型,配置 `配网热点` 的密码(8~64 个字符) + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 + + + +### `ESP8266.ota` + +```python +ESP8266.ota(url) +``` + +开启`ota`后,网卡将更新新版本固件 + +> 当前仅支持sta模式下进行ota升级;且升级过程中只可查询当前状态,不可进行其他操作。 + +**参数描述:** + +- `url` - 字符串类型,填写网址地址,表示固件下载地址,当前仅支持 http 协议,最长 256 字节。 + +**返回值描述:** + +- 执行成功返回`0`,执行失败返回其他值。 + + +**示例:** + +```python + +url='http://www.example.com/fota.bin' + +ESP8266.ota(url) + +``` + + + +### `ESP8266.stop` + +```python +ESP8266.stop() +``` + +释放掉为无线网卡所配置的虚拟网卡 + +**返回值描述:** + +- 释放成功返回`0`,释放失败返回其他值。 + + + +### `ESP8266.set_default_NIC` + +```python +ESP8266.set_default_NIC(ip_str) +``` + +指定网卡进行网络转发 + +**参数描述:** + +- `ip_str` - 字符串类型,所要设置默认转发网卡的网卡 ip 地址,如:'192.168.1.100' + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 + + + +### `ESP8266.set_dns` + +```python +ESP8266.set_dns(pri_dns, sec_dns) +``` + +指定无线网卡的`dns`服务器进行地址解析 + +**参数描述:** + +- `pri_dns` - 字符串类型,设置无线网卡的`首选 dns` 服务器,默认为 `8.8.8.8` +- `sec_dns` - 字符串类型,设置无线网卡的`备选 dns` 服务器,默认为 `114.114.114.114` + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 + + + +### `ESP8266.router_add` + +```python +ESP8266.router_add(ip, mask) +``` + +设置无线网卡路由转发规则 + +**参数描述:** + +- `ip` - 字符串类型,设置 `ap` 模式的网段,默认为 192.168.4.1 +- `mask` - 字符串类型,设置子网掩码,默认为 255.255.255.0 + +**返回值描述:** + +- 配置成功返回`0`,配置失败返回其他值。 diff --git a/docs/API_reference/zh/wifilib/WLAN.md b/docs/API_reference/zh/wifilib/WLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..4d1a7fe60afca5444ebedf5e5559f02c06a53825 --- /dev/null +++ b/docs/API_reference/zh/wifilib/WLAN.md @@ -0,0 +1,731 @@ +# WLAN - 无线网络控制 + +该类主要用于内置 Wi-Fi 网卡控制。 + +> 支持模组型号:FCM360W + +**示例:** + +```python +# 本例程演示了 Wi-Fi 网卡连接热点并进行网络通信的功能。 +import network +import utime +nic = network.WLAN(network.STA_MODE) +while nic.status("station_if") != 1011: + print("Waiting for connection...") + nic.connect(ssid="your_ssid", password="your_password") + utime.sleep(1) +print(nic.ifconfig()) + +# now use socket as usual +import usocket +addr = usocket.getaddrinfo("python.quectel.com", 80)[0][-1] +s = usocket.socket() +s.connect(addr) +s.send(b"GET / HTTP/1.1\r\nHost: python.quectel.com\r\n\r\n") +data = s.recv(1000) +print(data) +s.close() +``` + +## 构造函数 + +### `network.WLAN` + +```python +class network.WLAN(mode) +``` + +初始化 Wi-Fi 网卡信息,并返回 Wi-Fi 网卡对象。 + +**参数描述:** + +- `mode` - 无线网卡工作模式,int类型。 + - `network.NONE_MODE` : `0` - 空闲模式。 + - `network.AP_MODE` : `1` - AP模式,只支持无线客户端接入。 + - `network.STA_MODE` : `2` - Station模式,只接入无线网络,比如路由器、手机热点。 + - `network.AP_STA_MODE` : `3` - AP+Station模式,既支持无线客户端接入,同时也支持接入无线网络。 + +> 注意: +> +> 1. WLAN网卡对象只能创建一个,如果重复创建将会抛出异常:`ERR_WLAN_NETIF_IS_BUSY`。 +> 2. WLAN网卡总共有以上四种工作模式,这四种工作模式实际上都是在对两个网络接口进行操作:`softap网口`和 `station网口`。当模式为 `AP_STA_MODE`时,此时 `softap`和 `station`两种网口并存,所以在调用一些有网口指向性的接口时需要指定 `interface`参数,否则我们无法知道您预期操作的网口。 + +**示例:** + +```python +# 创建Station模式,并且连接指定AP +import network +nic = network.WLAN(network.STA_MODE) +nic.connect(ssid='your-ssid', password='your-password') +nic.status("station_if") +``` + +## 方法 + +### `WLAN.mode` + +```python +WLAN.mode([mode]) +``` + +设置或查询无线网卡工作模式。 + +- 查询无线网卡工作模式 + + 不传参时,为查询无线网卡工作模式。 +- 设置无线网卡工作模式 + + 传参时,为设置无线网卡工作模式。模式切换后,无线网卡处于停止工作的状态。 + +**参数描述:** + +- `mode` - 无线网卡工作模式,`int`类型。 + - `network.NONE_MODE` : `0` - 空闲模式。 + - `network.AP_MODE` : `1` - AP模式,只支持无线客户端接入。 + - `network.STA_MODE` : `2` - Station模式,只接入无线网络,比如路由器、手机热点。 + - `network.AP_STA_MODE` : `3` - AP+Station模式,既支持无线客户端接入,同时也支持接入无线网络。 + +**返回值描述:** + +- 查询无线网卡工作模式 + + 返回无线网卡当前的工作模式,`int`类型。 +- 设置无线网卡工作模式 + + 返回错误码,`int`类型。 + + - `ERR_OK` : `2000` - 无错误。 + - `ERR_WIFI_BUSY` : `2003` - 已经处于该工作模式。 + - `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + - `ERR_NOT_SUPPORT` : `2004` - 不支持该模式。 + +**示例:** + +```python +# 查询当前模式 +>>> nic.mode() +2 +``` + +```python +# 设置当前模式为AP模式 +>>> nic.mode(network.AP_MODE) +2000 +``` + +### `WLAN.config` + +```python +WLAN.config('param') +WLAN.config(param=value) +``` + +设置或查询配置参数 + +- 查询配置参数 + + 输入相关的关键字进行参数查询,每次只能查询一个参数,`str`类型。 +- 设置配置参数 + + 当参数为关键字参数时,进行参数设置;可同时设置多个参数。 + +**参数描述:** + +- `ap_ssid` - softap的无线接入点名称,`str`类型,1~32 个字符,默认值:`'quecpython'`。 +- `ap_password` - softap的无线接入点密码,`str`类型,0~63 个字符,默认值:`'quecpython'`。 + + - `AUTH_OPEN` : `0`个字符 - 无需密码。 + - `AUTH_WEP` : `5`个字符 - 固定长度为5。 + - `AUTH_WPA_PSK` : `8~63`个字符。 + - `AUTH_WPA2_PSK` : `8~63`个字符。 + - `AUTH_WPA_WPA2_PSK` : `8~63`个字符。 +- `ap_auth` - softap的认证方式,`int`类型,默认值:`AUTH_WPA_WPA2_PSK`。 + + - `AUTH_OPEN` : `0` - 开放式身份认证。 + - `AUTH_WEP` : `1` - 有线等效加密身份认证。 + - `AUTH_WPA_PSK` : `2` - WPA预共享密钥身份认证。 + - `AUTH_WPA2_PSK` : `3` - WPA2预共享密钥身份认证。 + - `AUTH_WPA_WPA2_PSK` : `4` - 混合模式,结合WPA和WPA2的PSK身份认证。 +- `ap_channel` - softap的信道,`int`类型。可设置的范围为:`[1,13]`,默认值:`3`。 +- `ap_hidden` - softap的无线接入点名称是否隐藏,`bool`类型,`True`为隐藏,默认值:`False`。 +- `ap_max_clients` - softap的最大client连接数,`int`类型,默认值:`4`。 +- `ap_mac` - softap的MAC地址,`str`类型。 +- `sta_ssid` - station待连接的无线接入点名称,`str`类型,1~32 个字符。 +- `sta_password` - station待连接的无线接入点密码,`str`类型,0~63 个字符。 +- `sta_bssid` - station目标无线接入点的MAC地址,`str`类型。 +- `sta_channel` - station的信道,`int`类型。可设置的范围为:`[1,13]`。 +- `sta_mac` - station的MAC地址,`str`类型。 +- `block` - 是否为阻塞模式,`bool`类型,默认为 `True`,即阻塞模式。非阻塞模式请配合事件回调使用。 +- `timeout` - 连接超时时间,`int`类型,单位:s,默认值:`15`s。 +- `country` - 国家码,`str`类型。 +- `event_callback` - WLAN状态回调函数,当WLAN状态发生改变时会产生回调,回调函数原型: + + ``` + fun(event) + ``` + + 回调函数参数描述: + + - `event`:事件信息,`dict`类型,携带的参数如下: + - `type`:事件类型,`int`类型,详见[事件码.事件类型](#事件码)。 + - `id`:具体的事件,`int`类型,详见[事件码.事件ID](#事件码)。 + - `msg`:传递给用户的消息,详见[事件码.事件回调传递给用户的消息](#事件码)。 + +**返回值描述:** + +- 查询配置参数: + + 返回查询结果。 + 如果执行该接口失败,将返回错误码。 + + - `ERR_NO_AP_IF` : `2020` - 当前不处于 `AP`或 `AP_STA`模式,无法获取当前查询的信息。 + - `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法获取当前查询的信息。 + - `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + - `ERR_NOT_SUPPORT` : `2004` - 不支持的参数。 +- 设置配置参数: + + 返回错误码。 + + - `ERR_OK` : `2000` - 无错误。 + - `ERR_PARAM_INVALID` : `2002` - 参数错误。 + - `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + +**示例:** + +```python +# 查询AP ssid名称配置 +>>> nic.config('ap_ssid') +'quecpython' +``` + +```python +# 创建AP模式,并且使用阻塞连接 +>>> import network +>>> nic = network.WLAN(network.AP_MODE) +>>> nic.config(ap_ssid="FCM360W-TEST", ap_password="12345678", ap_channel=5, ap_auth=nic.AUTH_WPA_WPA2_PSK, block=True, timeout=15) +>>> nic.active(True) +2000 +``` + +```python +# 创建AP+STA模式,并且使用非阻塞连接 +>>> import network +>>> +>>> def fun(event): +>>> print(event) +>>> +>>> nic = network.WLAN(network.AP_STA_MODE) +>>> nic.config(ap_ssid="FCM360W-TEST", ap_password="12345678", ap_channel=5, ap_auth=nic.AUTH_WPA_WPA2_PSK, sta_ssid="Tenda_996", sta_password="12345678", country="CN", block=False, timeout=15, event_callback=fun) +>>> nic.active(True) +2015 +>>> {'msg': {'password': '12345678', 'ssid': 'Tenda_996', 'rssi': -35, 'channel': 3, 'bssid': '50:2b:73:08:55:d1', 'auth': 3, 'cipher': 4}, 'type': 3200, 'id': 3201} +{'msg': ('192.168.137.206', '255.255.255.0', '192.168.137.1', '0.0.0.0', '0.0.0.0'), 'type': 3200, 'id': 3204} +``` + +### `WLAN.active` + +```python +WLAN.active([enable]) +``` + +网卡激活状态配置/查询 + +- 网卡状态查询 + + 若不传参则表示查询网卡状态。 +- 网卡激活 + + 若传参为 `True`/`False`,则表示激活/停用网卡。 + +**参数描述:** + +- `enable` - bool类型,`True`/`False`分别表示激活/停用网卡。 + +**返回值描述:** + +- 网卡状态查询 + + 返回 `True`/`False`,表示已激活/未激活,`bool`类型。 +- 网卡激活 + + 返回错误码,`int`类型。 + + - `ERR_OK` : `2000` - 无错误。 + - `ERR_WOULDBLOCK` : `2015` - 在非阻塞模式下,符合网卡激活的条件后,接口返回 `ERR_WOULDBLOCK`,并进行异步的网卡激活。 + - `ERR_PARAM_INVALID` : `2002` - 参数错误。 + - `ERR_TIMEOUT` : `2023` - 执行超时。 + +**示例:** + +```python +# 查询网卡状态 +>>> nic.active() +False +``` + +```python +# 激活网卡 +>>> nic.active(True) +2000 +``` + +### `WLAN.connect` + +```python +WLAN.connect([ssid, password, bssid, timeout]) +``` + +连接指定无线网络。仅支持Station模式,支持阻塞/非阻塞式连接,默认阻塞式连接,超时时间15s。 +如果没有指定ssid和password,则会自动连接上一次连接成功的AP。 + +**参数描述:** + +- `ssid` - 填写所要连接的 Wi-Fi 的名称,`str`类型,1~32 个字符。 +- `password` - 填写所要连接的 Wi-Fi 的密码,`str`类型,0~63 个字符。 + - `AUTH_OPEN` : `0`个字符 - 无需密码。 + - `AUTH_WEP` : `5`个字符 - 固定长度为5。 + - `AUTH_WPA_PSK` : `8~63`个字符。 + - `AUTH_WPA2_PSK` : `8~63`个字符。 + - `AUTH_WPA_WPA2_PSK` : `8~63`个字符。 +- `bssid` - 填写所要连接的 Wi-Fi 的bssid信息,该参数是目标AP的MAC地址,`str`类型。 +- `timeout` - 连接超时时间,`int`类型,单位:s,默认 `15`s。 + +**返回值描述:** + +返回错误码,`int`类型。 + +- `ERR_OK` : `2000` - 无错误。 +- `ERR_WOULDBLOCK` : `2015` - 在非阻塞模式下,符合建立网络连接的条件后,接口返回 `ERR_WOULDBLOCK`,并进行异步的网络连接。 +- `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法连接网络。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_TIMEOUT` : `2023` - 执行超时。 + +示例: + +```python +# 连接AP,并设置超时时间为10s +>>> import network +>>> nic = network.WLAN(network.STA_MODE) +>>> nic.connect(ssid='your-ssid', password='your-password', timeout=10) +``` + +### `WLAN.disconnect` + +```python +WLAN.disconnect([interface, mac, ip]) +``` + +断开连接 + +- 处于 AP 模式时 + + 传入对应station的mac或ip可以断开与对应station的连接。 + 不传参表示断开与所有 station 的连接。 +- 处于 STA 模式时 + + 断开与热点的连接。 +- 处于 AP_STA 模式时 + + 通过 `interface`参数指定需要操作的 WLAN 网口。 + +**参数描述:** + +- `interface` - AP_STA模式必选,用于指定需要操作的WLAN网口,`int`类型。 + + - `SOFTAP_IF` : `0` - softap网口 + - `STATION_IF` : `1` - station网口。 +- `mac` - AP或者AP_STA模式下断开指定MAC的station连接,如果MAC为'FF:XX:XX:XX:XX:XX',则表示与所有station断开连接,`str`类型。 +- `ip` - AP或者AP_STA模式下断开指定IP的station连接,`str`类型。 + +> 如果同时传入了 `mac` 和 `ip` 两个参数,则位置靠后的参数生效。 + +**返回值描述:** + +返回错误码。 + +- `ERR_OK` : `2000` - 无错误。 +- `ERR_NO_AP_IF` : `2020` - 当前不处于 `AP`或 `AP_STA`模式,无法对softap网口进行操作。 +- `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法对station网口进行操作。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + +**示例:** + +```python +# AP模式下断开MAC为'7e:d0:3f:21:5d:34'的station +>>> nic.disconnect(mac="7e:d0:3f:21:5d:34") +2000 +``` + +```python +# STA模式下断开与AP的连接,关闭station网口 +>>> nic.disconnect() +2000 +``` + +```python +# AP_STA模式下断开与AP的连接,关闭station网口 +>>> nic.disconnect(interface=nic.STATION_IF) +2000 +``` + +```python +# AP_STA模式下断开IP为'10.10.10.2'的station +>>> nic.disconnect(interface=nic.SOFTAP_IF, ip="10.10.10.2") +2000 +``` + +### `WLAN.status` + +```python +WLAN.status('param') +``` + +查询网卡状态。 + +**参数描述:** + +- `stations_list` - 仅 `AP`或 `AP_STA`模式下使用,查询与当前AP连接的所有station列表。 +- `ap_list` - 仅 `STA`或 `AP_STA`模式下使用,获取当前连接的AP的信息。 +- `rf` - 获取射频状态,见[状态码](#状态码)。 +- `softap_if` - 获取当前 `softap`网口状态,见[状态码](#状态码)。 +- `station_if` - 获取当前 `station`网口状态,见[状态码](#状态码)。 +- `netcfg` - 获取当前配网状态,见[状态码](#状态码)。 + +**返回值描述:** + +- `stations_list` - 返回与当前AP连接的所有station列表,`list`类型,格式:`[(aid, ip, mac),...]`。 +- `ap_list` - 仅 `STA`或 `AP_STA`模式下生效,获取当前连接的AP的信息,`list`类型,格式:`[ssid, password, mac, rssi, channel, auth, cipher]`。 + + - `auth` - 认证方式,`int`类型。 + + - `AUTH_OPEN` : `0` - 开放式身份认证。 + - `AUTH_WEP` : `1` - 有线等效加密身份认证 + - `AUTH_WPA_PSK` : `2` - WPA预共享密钥身份认证。 + - `AUTH_WPA2_PSK` : `3` - WPA2预共享密钥身份认证。 + - `AUTH_WPA_WPA2_PSK` : `4` - 混合模式,结合WPA和WPA2的PSK身份认证。 + - `cipher` - 加密方式,`int`类型 + + - `CIPHER_NONE` : `0` - 无加密。 + - `CIPHER_WEP40` : `1` - WEP40加密。 + - `CIPHER_WEP104` : `2` - WEP104加密。 + - `CIPHER_TKIP` : `3` - TKIP加密。 + - `CIPHER_CCMP` : `4` - CCMP加密。 +- `rf` - 获取射频状态,`int`类型,见[状态码](#状态码)。 +- `softap_if` - 获取当前 `softap`网口状态,`int`类型,见[状态码](#状态码)。 +- `station_if` - 获取当前 `station`网口状态,`int`类型,见[状态码](#状态码)。 +- `netcfg` - 获取当前配网状态,`int`类型,见[状态码](#状态码)。 + +如果执行该接口失败,将返回错误码: + +- `ERR_NO_AP_IF` : `2020` - 当前不处于 `AP`或 `AP_STA`模式,无法执行与softap网口相关的操作。 +- `ERR_AP_UNSTART` : `2019` - softap未开启,无法查询stations列表。 +- `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法执行与station网口相关的操作。 +- `ERR_UNCONNECTED_AP` : `2018` - 未连接AP,无法查询AP信息。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + +**示例:** + +```python +# STA模式下获取当前连接的AP信息 +>>> nic.status("ap_list") +['Tenda_996', '12345678', '50:2b:73:08:55:d1', -38, 11, 3, 4] +``` + +### `WLAN.scan` + +```python +WLAN.scan([ssid, bssid, channel, passive, max_item, scan_time]) +``` + +无线网络扫描。 + +**参数描述:** + +- `ssid` - 指定扫描的ssid,`str`类型,默认不配置,即扫描当前区域内的所有可达的AP。 +- `bssid` - 指定扫描的bssid,`str`类型,默认不配置,即扫描当前区域内的所有可达的AP。 +- `channel` - 指定扫描的信道,`int`类型,默认不配置,即扫描所有信道。 +- `passive` - 是否为被动扫描,`bool`类型,`True`为被动扫描,默认值为 `False`。 +- `max_item` - 指定扫描的最大AP数,`int`类型,默认值为 `128`。 +- `scan_time` - 每个通道的扫描时间,单位:ms,`int`类型,默认不配置。 + +**返回值描述:** + +阻塞模式扫描成功返回扫描到的可接入点信息,`list`类型,`[(ssid, bssid, channel, rssi, auth, hidden),...]` + +| 参数 | 类型 | 说明 | +| ----------- | -------- | ----------------- | +| `ssid` | `str` | 可接入点 名称 | +| `bssid` | `str` | 可接入点 MAC | +| `channel` | `int` | 可接入点 所在信道 | +| `rssi` | `int` | 可接入点 信号强度 | +| `auth` | `int` | 可接入点 认证方式 | +| `hidden` | `bool` | 可接入点 是否隐藏 | + +非阻塞模式请配合事件回调使用,在回调中返回扫描结果。 + +扫描失败返回对应错误码,`int`类型。 + +- `ERR_OK` : `2000` - 无错误。 +- `ERR_WOULDBLOCK` : `2015` - 在非阻塞模式下,符合热点扫描的条件后,接口返回 `ERR_WOULDBLOCK`,并进行异步的热点扫描。 +- `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法使用该方法。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + +**示例:** + +```python +# STA模式下扫描ssid名为'Tenda_996'的AP +>>> nic.scan(ssid="Tenda_996") +[('Tenda_996', '50:2b:73:08:55:d1', 11, -42, 3, False)] +``` + +### `WLAN.ifconfig` + +```python +WLAN.ifconfig([interface, config]) +``` + +配置或查询网络信息。 + +**参数描述:** + +- `interface` - AP_STA 模式下必须指定需要配置/查询的网口,`int`类型。 + + - `SOFTAP_IF` : `0` - softap网口 + - `STATION_IF` : `1` - station网口。 +- `config` - ip配置,`tuple`类型,格式:`(ip, netmask, gateway, primary_dns, secondary_dns)`。 + + | 参数 | 类型 | 说明 | + | ----------------- | ------- | --------------- | + | `ip` | `str` | ip地址 | + | `netmask` | `str` | 子网掩码 | + | `gateway` | `str` | 网关 | + | `primary_dns` | `str` | DNS服务器主地址 | + | `secondary_dns` | `str` | DNS服务器辅地址 | + +**返回值描述:** + +参数查询返回对应的查询结果。 + +参数配置返回对应错误码,`int`类型。 + +- `ERR_OK` : `2000` - 无错误。 +- `ERR_NO_AP_IF` : `2020` - 当前不处于 `AP`或 `AP_STA`模式,无法使用查询softap网口参数。 +- `ERR_NO_STA_IF` : `2017` - 当前不处于 `STA`或 `AP_STA`模式,无法查询station网口参数。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 + +**示例:** + +查询station网口的ip信息: + +```python +nic.ifconfig(interface=nic.STATION_IF) +``` + +设置station网口的ip信息: + +```python +nic.ifconfig(interface=nic.STATION_IF, config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8', '114.114.114.114')) +``` + +### `WLAN.netcfg` + +```python +WLAN.netcfg(enable=True, type=nic.NETCFG_SMARTCONFIG, timeout=120) +``` + +开启或关闭配网。 + +**参数描述:** + +- `enable` - 开启/关闭配网,`bool`类型,`True`为开启,默认为 `True`。 +- `type` - 配网方式,`int`类型。 + + - `NETCFG_SMARTCONFIG` : `0` - smartconfig配网,由于该配网模式需要开启混杂模式,所以启动后会关闭已开启的AP和STA。 + - `NETCFG_WEBCONFIG` : `1` - web配网,该配网模式依赖AP,所有请先开启softap才能使用该配网模式进行配网,成功开启后,请使用浏览器访问该地址:http://`IP`:8080/setting,输入ssid和密码后即可完成配网。此处 `IP`为模组开启的softap的IP,可以通过 `nic.ifconfig(interface=nic.SOFTAP_IF)`来查询。 + - `NETCFG_BLECONFIG` : `2` - ble配网。 +- `timeout` - 配网超时时间,`int`类型,单位:s,默认120s。 + +**返回值描述:** + +返回错误码,`int`类型。 + +- `ERR_OK` : `2000` - 无错误。 +- `ERR_WOULDBLOCK` : `2015` - 在非阻塞模式下,符合配网的条件后,接口返回 `ERR_WOULDBLOCK`,并进行异步的配网流程。 +- `ERR_NETCFG_BUSY` : `2024` - 重复开启配网。 +- `ERR_AP_UNSTART` : `2019` - 使用webconfig前需开启AP,webconfig业务逻辑依赖于此AP。 +- `ERR_TIMEOUT` : `2023` - 执行超时。 +- `ERR_PARAM_INVALID` : `2002` - 参数错误。 +- `ERR_INTERNAL` : `2006` - 内部错误,底层接口运行出错。 +- `ERR_NOT_SUPPORT` : `2004` - 不支持的操作。 + +**示例:** + +```python +# 开启AP模式并开始web配网 +>>> import network +>>> nic=network.WLAN(network.AP_MODE) +>>> nic.active(True) +2000 +>>> def fun(event): +... print(event) +>>> nic.config(block=False, event_callback=fun) +2000 +>>> nic.netcfg(enable=True, type=nic.NETCFG_WEBCONFIG, timeout=120) +2015 +{'msg': None, 'type': 3400, 'id': 3401} +``` + +```python +# 关闭web配网 +>>> nic.netcfg(enable=False) +2000 +{'msg': None, 'type': 3400, 'id': 3403} +``` + +## 常量 + +### 模式 + +| 模式 | 值 | 说明 | +| ----------- | -- | -------------- | +| NONE_MODE | 0 | 空闲模式 | +| AP_MODE | 1 | AP模式 | +| STA_MODE | 2 | Station模式 | +| AP_STA_MODE | 3 | AP+Station模式 | + +### 网口 + +| 网口 | 值 | 说明 | +| ---------- | -- | ----------- | +| SOFTAP_IF | 0 | softap网口 | +| STATION_IF | 1 | station网口 | + +### 认证方式 + +| 认证方式 | 值 | 说明 | +| ----------------- | -- | ------------------------------------ | +| AUTH_OPEN | 0 | 开放式身份认证 | +| AUTH_WEP | 1 | 有线等效加密身份认证 | +| AUTH_WPA_PSK | 2 | WPA预共享密钥身份认证 | +| AUTH_WPA2_PSK | 3 | WPA2预共享密钥身份认证 | +| AUTH_WPA_WPA2_PSK | 4 | 混合模式,结合WPA和WPA2的PSK身份认证 | +| AUTH_WPA3_PSK | 5 | WPA3预共享密钥身份认证 | +| AUTH_WPA2_WPA3_PSK | 6 | 混合模式,结合WPA2和WPA3的PSK身份认证 | + +### 加密方式 + +| 加密方式 | 值 | 说明 | +| ------------- | -- | ---------- | +| CIPHER_NONE | 0 | 无加密 | +| CIPHER_WEP40 | 1 | WEP40加密 | +| CIPHER_WEP104 | 2 | WEP104加密 | +| CIPHER_TKIP | 3 | TKIP加密 | +| CIPHER_CCMP | 4 | CCMP加密 | + +### 配网方式 + +| 配网方式 | 值 | 说明 | +| ------------------ | -- | --------------- | +| NETCFG_SMARTCONFIG | 0 | smartconfig配网 | +| NETCFG_WEBCONFIG | 1 | web配网 | +| NETCFG_BLECONFIG | 2 | ble配网 | + +### 错误码 + +| 错误码 | 说明 | 值 | +| ----------------------------- | ------------------------------------- | ---- | +| ERR_OK | 无错误 | 2000 | +| ERR_NO_MEM | 内存申请失败 | 2001 | +| ERR_PARAM_INVALID | 无效参数 | 2002 | +| ERR_WIFI_BUSY | 网卡忙 | 2003 | +| ERR_NOT_SUPPORT | 不支持该功能或操作 | 2004 | +| ERR_WIFI_ALREADY_CUR_IF | 该模式已经使能 | 2005 | +| ERR_INTERNAL | 内部异常 | 2006 | +| ERR_WOULDCONNECT | 需要调用connect接口连接AP | 2007 | +| ERR_NO_AP_FOUND | 未找到热点 | 2008 | +| ERR_PWD_WRONG | 密码错误 | 2009 | +| ERR_AUTHMODE_WRONG | 身份验证错误 | 2010 | +| ERR_CHANNEL_INVALID | 信道错误 | 2011 | +| ERR_NONAUTH | WPA 收到未认证station的class-2 frame | 2012 | +| ERR_NONASSOC | WPA 收到未认证station的class-3 frame | 2013 | +| ERR_HANDSHAKE_TIMEOUT | 握手超时 | 2014 | +| ERR_WOULDBLOCK | 当前处于非阻塞模式 | 2015 | +| ERR_NOT_ACTIVE | 未处于激活状态 | 2016 | +| ERR_NO_STA_IF | 未处于STA模式 | 2017 | +| ERR_UNCONNECTED_AP | 未连接热点 | 2018 | +| ERR_AP_UNSTART | softap网口未启动 | 2019 | +| ERR_NO_AP_IF | 未处于AP模式 | 2020 | +| ERR_NO_SCAN_MODE | 未处于扫描模式 | 2021 | +| ERR_NO_AP_STA_IF | 未处于STA或AP模式 | 2022 | +| ERR_TIMEOUT | 超时 | 2023 | +| ERR_NETCFG_BUSY | 重复开启配网 | 2024 | +| ERR_NETCFG_SOFTAP_START | AP启动失败 | 2025 | +| ERR_NETCFG_SOCKET_CREATE | Socket创建失败 | 2026 | +| ERR_NETCFG_HTTP_SERVER_CREATE | http server启动失败 | 2027 | +| ERR_NETCFG_BLE_SERVER_CREATE | ble启动失败 | 2028 | +| ERR_NETCFG_GATT_SERVER_CREATE | GATT服务启动失败 | 2029 | +| ERR_NETCFG_NOT_IN_NETCFG | 未处于配网模式 | 2030 | +| ERR_NETCFG_HTTP_SERVER_CLOSE | web配网http关闭失败 | 2031 | +| ERR_NETCFG_SOCKET_CLOSE | web配网SOCKET关闭失 | 2032 | +| ERR_NETCFG_SOFTAP_CLOSE | web配网AP关闭失败 | 2033 | +| ERR_NETCFG_BLE_SERVER_CLOSE | ble配网服务关闭失败 | 2034 | +| ERR_STA_KICKED_OFFLINE_BY_AP | 被AP踢下线 | 2035 | +| ERR_SER_DISCONNECT | 用户主动断开 | 2036 | +| ERR_AUTHMODE_CHANGED | 连接策略改变 | 2037 | +| ERR_IFMODE_CHANGED | 模式改变 | 2038 | +| ERR_DHCP_LEASE_EXPIRED | DHCP租期到期 | 2039 | +| ERR_INACTIVE_TIMEOUT | 在指定的超时时间内,未进行任何交互 | 2040 | +| ERR_IP_DEL_ARTIFICIALLY | 人为删除IP地址 | 2041 | + +### 事件码 + +| 事件类型 | 事件名 | 事件ID | 事件说明 | 事件回调传递给用户的消息 | +| -------- | -------------------------------- | ------ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 3000 | EVENT_RF_WAKEUP | 3001 | 射频唤醒 | None | +| 3000 | EVENT_RF_SLEEP | 3002 | 射频休眠 | None | +| 3100 | EVENT_SCAN_DONE | 3101 | 扫描结束 | 返回扫描结果,`list`类型,格式:`[(ssid, bssid, channel, rssi, auth, hidden),...]` | +| 3200 | EVENT_AP_START_SUCCEED | 3201 | AP创建成功 | None | +| 3200 | EVENT_AP_START_FAILED | 3202 | AP创建失败 | None | +| 3200 | EVENT_STA_CONNECTED | 3203 | 与Station建立连接 | 返回Station的信息,`dict`类型。`
aid`: AP为Station分配的id。`
mac`: Station的MAC地址。 | +| 3200 | EVENT_STA_DISCONNECTED | 3204 | 与Station断开连接 | 返回Station的信息,`dict`类型。`
aid`: AP为Station分配的id。`
ip`: Station的IP地址。`
mac`: Station的MAC地址。 | +| 3200 | EVENT_STA_IP_ASSIGNED | 3205 | 已为Station分配IP | 返回Station的信息,`dict`类型。`
aid`: AP为Station分配的id。`
ip`: Station的IP地址。`
mac`: Station的MAC地址。 | +| 3200 | EVENT_AP_STOP | 3206 | 停止AP模式 | None | +| 3300 | EVENT_STA_START_CONN | 3301 | 开始连接AP | None | +| 3300 | EVENT_CONN_SUCCEED | 3302 | 连接AP成功 | 返回已连接的AP信息,`dict`类型。 `
ssid`: 无线接入点名称,`str`类型。`
password`: 无线接入点密码,`str`类型。 `
bssid`: 无线接入点MAC地址,`str`类型。 `
channel`: 当前所处信道,`int`类型。 `
rssi`: 无线接入点信号强度,`int`类型。 `
auth`: 认证方式,`int`类型。 `
cipher`: 加密方式,`int`类型。 | +| 3300 | EVENT_CONN_FAILED | 3303 | 连接AP失败 | None | +| 3300 | EVENT_CONN_LOST | 3304 | 与AP断开连接 | 返回断开连接的AP信息,`dict`类型。 `
ssid`: 无线接入点名称,`str`类型。`
bssid`: 无线接入点MAC地址,`str`类型。`
reason`: 断连原因,`int`类型(0、1:正常断开,其他:异常)。 | +| 3300 | EVENT_GOT_IP | 3305 | 获取到IP | 返回获取到的IP信息,`tuple`类型,格式:`(ip, netmask, gateway, primary_dns, secondary_dns)` | +| 3300 | EVENT_LOST_IP | 3306 | IP丢失 | None | +| 3400 | EVENT_NETCFG_START_SUCCEED | 3401 | 配网启动成功 | None | +| 3400 | EVENT_NETCFG_START_FAILED | 3402 | 配网启动失败 | None | +| 3400 | EVENT_NETCFG_STOP_SUCCEED | 3403 | 配网停止成功 | None | +| 3400 | EVENT_NETCFG_STOP_FAILED | 3404 | 配网停止失败 | None | +| 3400 | EVENT_NETCFG_STAT_CLIENT_CONNECT | 3405 | 配网有客户端连接 | None | +| 3400 | EVENT_NETCFG_GOT_KEY | 3406 | 配网获取到账号密码 | 返回获取到的账号密码,`tuple`类型,格式:`(ssid, password)` | +| 3400 | EVENT_NETCFG_TIMEOUT | 3407 | 配网超时 | None | + +### 状态码 + +| 状态码 | 值 | 说明 | +| ----------------------- | ---- | ------------------------ | +| STATUS_RF_NOT_ACTIVATED | 1000 | 射频未激活 | +| STATUS_RF_ACTIVATED | 1001 | 射频已激活 | +| STATUS_RF_SLEEP | 1002 | 射频已休眠 | +| STATUS_RF_WAKEUP | 1003 | 射频已唤醒 | +| STATUS_AP_IDLE | 1004 | softap网口空闲,未启动 | +| STATUS_AP_START | 1005 | softap网口已启动 | +| STATUS_AP_STACONNECTED | 1006 | 已有设备接入 | +| STATUS_STA_IDLE | 1007 | station网口空闲,未启动 | +| STATUS_STA_SCANNING | 1008 | 正在扫描AP | +| STATUS_STA_CONNECTING | 1009 | 正在连接AP | +| STATUS_STA_CONNECTED | 1010 | AP连接成功 | +| STATUS_STA_GOT_IP | 1011 | 已获取到IP | +| STATUS_STA_LOST_IP | 1012 | 丢失IP | +| STATUS_NETCFG_NOT_INTO | 1013 | 配网模式未启动 | +| STATUS_NETCFG_INTO | 1014 | 进入配网模式 | +| STATUS_NETCFG_GOT_KEY | 1015 | 已获取到 ssid 和 passwd | diff --git a/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/60eb6249-67ea-40d3-a59b-0612dbc9f308.png b/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Data detection.png similarity index 100% rename from docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/60eb6249-67ea-40d3-a59b-0612dbc9f308.png rename to docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Data detection.png diff --git a/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/860ce14a-e915-4207-9f29-36ac5b1a7a64.png b/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Program launch.png similarity index 100% rename from docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/860ce14a-e915-4207-9f29-36ac5b1a7a64.png rename to docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Program launch.png diff --git a/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/860ce14a-e915-4207-9f29-36ac5b1a7a64.png b/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Program startup.png similarity index 100% rename from docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/860ce14a-e915-4207-9f29-36ac5b1a7a64.png rename to docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Program startup.png diff --git a/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/f735bcd9b0c85d0aaad96173b315ca73.png b/docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Software design diagram.png similarity index 100% rename from docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/f735bcd9b0c85d0aaad96173b315ca73.png rename to docs/Application_guide/en/media/solutions/tracker_box(BG95M3)/Software design diagram.png diff --git a/docs/Application_guide/en/sidebar.yaml b/docs/Application_guide/en/sidebar.yaml index d08d2940f4f477e560469f634192b6c775a9f435..d545b7141dcdb54c09bb1f5927f0cb769347362e 100644 --- a/docs/Application_guide/en/sidebar.yaml +++ b/docs/Application_guide/en/sidebar.yaml @@ -364,7 +364,7 @@ items: file: solutions/meter-box/quick_start.md - label: software design file: solutions/meter-box/software_design.md - label: Smart Tracker Solution Based on BG95M3 + - label: Smart Tracker Solution Based on BG95M3 file: solutions/tracker_box(BG95M3)/README.md items: - label: development resources diff --git a/docs/Application_guide/en/solutions/tracker_box(BG95M3)/quick_start.md b/docs/Application_guide/en/solutions/tracker_box(BG95M3)/quick_start.md index f5ac2dbbb6b5b3244743bda81bb1dc917c6dad84..b8867a48d138e1cf663c53f3b7f50aea1034e977 100644 --- a/docs/Application_guide/en/solutions/tracker_box(BG95M3)/quick_start.md +++ b/docs/Application_guide/en/solutions/tracker_box(BG95M3)/quick_start.md @@ -64,13 +64,13 @@ Refer to [this chapter](https://developer.quectel.com/doc/quecpython/Getting_sta After executing the _main.py script, the program starts running and prints dialing information, including dialing status, IP Address, DNS server address, device number, etc. - + ### Data detection After starting to run, startup information will be printed. - + ### View device location (LBS) diff --git a/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/60eb6249-67ea-40d3-a59b-0612dbc9f308.png b/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Data detection.png similarity index 100% rename from docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/60eb6249-67ea-40d3-a59b-0612dbc9f308.png rename to docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Data detection.png diff --git a/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Program startup.png b/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Program startup.png new file mode 100644 index 0000000000000000000000000000000000000000..c084009280e911c36d4c6f5644c13eb04323d7c5 Binary files /dev/null and b/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Program startup.png differ diff --git a/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Software design diagram.png b/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Software design diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..cc9bf76734ff4e370391c3d8590b0ab8f80e1984 Binary files /dev/null and b/docs/Application_guide/zh/media/solutions/tracker_box(BG95M3)/Software design diagram.png differ diff --git a/docs/Application_guide/zh/sidebar.yaml b/docs/Application_guide/zh/sidebar.yaml index cfd3a650cf1b45e49e1fc616ebbaea821ab45588..20ef9bbec3241171f9b08e9346ea33bbeb3dfb6c 100644 --- a/docs/Application_guide/zh/sidebar.yaml +++ b/docs/Application_guide/zh/sidebar.yaml @@ -367,7 +367,7 @@ items: file: solutions/meter-box/quick_start.md - label: 软件设计讲解 file: solutions/meter-box/software_design.md - label: 基于BG95M3的Smart Tracker解决方案 + - label: 基于BG95M3的Smart Tracker解决方案 file: solutions/tracker_box(BG95M3)/README.md items: - label: 开发资源汇总 diff --git a/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/quick_start.md b/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/quick_start.md index 2f8899c752b9a2f8897c15e4461c40a5b532a31a..25a707da702ef0f04e9134ae60a4f0bdbb29b8c5 100644 --- a/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/quick_start.md +++ b/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/quick_start.md @@ -45,21 +45,21 @@ Acceleronix 开发的资产管理 SaaS 平台为特定行业提供全面解决 ## 设备开发 -- ### 开机 +### 开机 完成硬件连接工作后,当PWR,SCK1亮起或电脑设备管理器的端口列表出现包含Quectel USB字样的COM口,表示开机成功 - + -- ### 烧录固件包 +### 烧录固件包 参考[此章节](https://developer.quectel.com/doc/quecpython/Getting_started/zh/4G/flash_firmware.html),烧录[固件包](https://developer.quectel.com/wp-content/uploads/2024/09/QPY_OCPU_V0003_BG95M3_FW.zip )至开发板。 -- ### 脚本导入与运行 +### 脚本导入与运行 1.参考[此章节](https://developer.quectel.com/doc/quecpython/Getting_started/zh/4G/first_python.html#PC与模组间的文件传输),将源码目录下的code文件夹中的所有文件按原目录结构导入到模组文件系统中,如下图所示 - + 2.参考[此章节](https://developer.quectel.com/doc/quecpython/Getting_started/zh/4G/first_python.html#执行脚本文件),执行主程序文件_main.py @@ -71,13 +71,13 @@ Acceleronix 开发的资产管理 SaaS 平台为特定行业提供全面解决 执行_main.py脚本后,程序开始运行,会打印拨号信息,包括拨号状态、IP地址、DNS服务器地址,设备号等 - + ### 数据检测 开始运行后会打印启动信息 - + ### 查看设备位置(LBS) @@ -88,9 +88,12 @@ Acceleronix 开发的资产管理 SaaS 平台为特定行业提供全面解决 ### 查看和管理传感器数据 -1. 当设备在线时,在 Wonderfree 应用中点击设备进入控制面板。 -2. 查看智能追踪器的实时传感器数据和 LBS 位置数据。 -3. 如需更新传感器数据或 LBS 位置,点击控制面板右上角的刷新按钮 -4. +1.当设备在线时,在 Wonderfree 应用中点击设备进入控制面板。 + +2.查看智能追踪器的实时传感器数据和 LBS 位置数据。 + +3.如需更新传感器数据或 LBS 位置,点击控制面板右上角的刷新按钮 + + \ No newline at end of file diff --git a/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/software_design.md b/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/software_design.md index 2727d521c32a8d005fdffb8438df514c343d54a5..6b3b7535904c8a87784d61b1672ddc1d1215be3e 100644 --- a/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/software_design.md +++ b/docs/Application_guide/zh/solutions/tracker_box(BG95M3)/software_design.md @@ -4,7 +4,7 @@ ### 软件设计图 - + ## 代码讲解 diff --git a/docs/Dev_board_guide/en/README.md b/docs/Dev_board_guide/en/README.md new file mode 100644 index 0000000000000000000000000000000000000000..858f1afb68946fddcb2a2403b454588da16748fe --- /dev/null +++ b/docs/Dev_board_guide/en/README.md @@ -0,0 +1,29 @@ +# QuecPython Development Board Operation Guide + +QuecPython Development Board is an embedded iot development platform launched by Quectel, based on the QuecPython embedded operating system (a lightweight Python interpreter optimized for the Internet of Things). The development board integrates cellular communication modules (such as 4G Cat.1/NB-IoT/5G), Wi-Fi/ Bluetooth and other wireless connectivity capabilities, supporting the rapid development of iot terminal devices through Python language, greatly reducing the development threshold. + +## Core features + +- Low code development: Support for Python 3 syntax, no need for complex underlying development, suitable for rapid prototyping. + +- Multi-network system: Support 4G/NB-IoT/5G cellular networks, some models are compatible with Wi-Fi/ Bluetooth. + +- Rich hardware interface: provides GPIO, UART, I2C, SPI, ADC and other common peripheral interfaces. + +- Diverse onboard sensors: The development board is equipped with a variety of sensors by default (photosensitive, temperature and humidity, three-axis, etc.) + +- Convenient cloud docking: Built-in protocol stack supports mainstream IoT cloud platforms (such as Alibaba Cloud, Tencent Cloud, AWS IoT). + +- Low power consumption: Supports hibernation mode, suitable for battery-powered scenarios. + + +## Directory structure + +- [EC2X EVB Introduction](ec2x-evb.md) +- [BG95 EVB Introduction](bg95-evb.md) +- [EC200X EVB Introduction](ec200x-evb.md) +- [EG91X EVB Introduction](eg91x-evb.md) +- [FCM360W EVB Introduction](fcm360w-evb.md) +- [EC600U U-235 EVB Introduction](ec600u-235.md) +- [BG95/EG915U/EG912U Core EVB Introduction](bg-eg-core-evb.md) + diff --git a/docs/Dev_board_guide/en/bg-eg-core-evb.md b/docs/Dev_board_guide/en/bg-eg-core-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..c2db783147919c30a91161cd23b18580f710300a --- /dev/null +++ b/docs/Dev_board_guide/en/bg-eg-core-evb.md @@ -0,0 +1,149 @@ +# QuecPython BG&EG Core EVB Introduction + +## Quick Start + +Supported Module List + +- [BG95-M1](https://python.quectel.com/en/modules-cat/bg95-series) +- [BG95-M3](https://python.quectel.com/en/modules-cat/bg95-series) +- [BG95-M8](https://python.quectel.com/en/modules-cat/bg95-series) +- [EG915U-LA](https://python.quectel.com/en/modules-cat/eg915u-series) +- [EG915U-EU](https://python.quectel.com/en/modules-cat/eg915u-series) +- [EG912U-GL](https://python.quectel.com/en/modules-cat/eg912u-series) + +## Feature List + +### Overview + +The QuecPython BG&EG series core board (PH-7 (C4-P02)) is a core development board specifically designed for QuecPython with minimal functionality. The core board is designed with a 2.54mm pin arrangement, providing 38 PIN pins, including functional pins and enable control pins. Mainly providing support and convenience for customer development, debugging, and mass production equipment. The core board of the series is applicable to the entire BG95 series, EG915UEUAB, EG915ULAAB, EG912UGLAA and other EG series, including but not limited to the above module models. + +## Core EVB View + +![](./media/bg-eg-core-evb/PH-7_all.png) + + The main components and interface layout of the development board are shown in the following figure. + +![](./media/bg-eg-core-evb/bg95_figure.png) + +- Charging and USB: When inserting the Type-C interface to connect to USB, the charging function is enabled by default and cannot be turned off. If the charging function is not used, there is no need to pay attention. +- GNSS: The GNSS function depends on the module model. Taking BG95 as an example, the core board defaults to using active antennas and has already enabled power supply to the active antennas by default. +- SD & SIM Card Slot. +- 38 Pin. +- Antenna Interface。 + +## **Documents Download** + +- [QuecPython-PH-7C4-P02_Core_Board_Specification_and_User_Guide_V1.0.0](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/PH-7C4-P02_Core_Board_Specification_and_User_Guide_V1.0.0.pdf) +- [QuecPython-PH-7C4-P02_Core_Board_SCH](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/PH-7C4-P02_Schematic_Diagram.pdf) +- [QuecPython-PH-7C4-P02_Core_Board_Silkscreen](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/PH-7C4-P02_Silkscreen.pdf) + +## EVB Resources + +The main pin layout of the development board is shown in the following figure.![](./media/bg-eg-core-evb/bg95_pin_define.png) + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | \ No newline at end of file diff --git a/docs/Dev_board_guide/en/bg95-evb.md b/docs/Dev_board_guide/en/bg95-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..65f1edbbe80ea28cff534df59004f244dc4612c0 --- /dev/null +++ b/docs/Dev_board_guide/en/bg95-evb.md @@ -0,0 +1,332 @@ + +# BG95 EVB Introduction + +## Supported Module List + +- [BG95-M1](https://python.quectel.com/en/modules-cat/bg95-series) +- [BG95-M3](https://python.quectel.com/en/modules-cat/bg95-series) +- [BG95-M8](https://python.quectel.com/en/modules-cat/bg95-series) + + +## Feature List + +### Overview + +- The QuecPython_BG95_EVB is a compact and portable "pocket-sized" EVB specifically designed for QuecPython. + + +- The main board is equipped with a BG95 series module and a Type-C interface. You can easily develop the EVB with just a USB Type-C cable. + + +- The EVB is also equipped with an expansion board that supports light sensors, UV sensors, VOC sensors, nine-axis sensors, and temperature and humidity sensors. + + +- The EVB is compatible with Raspberry Pi Zero, and the expansion board for Raspberry Pi Zero can be directly used on the QuecPython_BG95_EVB. + + +### Description + +The main components and interface layout of the EVB are shown in the following figure. + +![img](./media/bg95/BG95_layout.png) + +## Resource Download + +- [BG95_Board_Sch](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/BG95_Board_Sch_0829.pdf) + + +## EVB Resources + +### EVB Interface + +**8 Pin Assignment** + +| **Pin Header** | **Number** | **Silkscreen** | **Pin** No. | **Function** | +| -------------- | ---------- | -------------- | ----------- | ------------ | +| JP6 | 1 | PWK_AUTO | 15 | POWERKEY | +| JP6 | 2 | PWK_AUTO | - | GND | +| JP6 | 3 | VDD_EXT | - | 1.8 V | +| JP6 | 4 | VDD_EXT | 29 | VDD_EXT | +| JP6 | 5 | MODULE_EN | - | 3.6 V | +| JP6 | 6 | MODULE_EN | - | 3.6 V | +| JP6 | 7 | GNSS_EN | - | 3.3 V | +| JP6 | 8 | GNSS_EN | 51 | GNSS_EN | + +- **1 & 2**: Automatic power-on. +- **3 & 4**: connect VDD_EXT to provide power for external circuit. For power consumption measurement, VDD_EXT needs to be disconnected. +- **5 & 6**: Turn on the DC-DC converter to provide power to the module. +- **7 & 8**: Enable active power supply for GNSS. + +**40 Pin Assignment** + +| **Pin Header** | **Number** | **Name** | **GPIO Multiplexing** | **Function** | **Pin Header** | **Number** | **Name** | **GPIO Multiplexing** | **Function** | +| -------- | -------- | -------- | ------------------------------------ | --------------------------------------------- | -------- | -------- | -------- | -------------------------------- | ------------------------------------------------- | +| JP7 | 1 | 3V3 | - | 3.3 V Output | JP8 | 2 | 5V | - | 5 V Output | +| JP7 | 3 | SDA1 | I2C1_SDA
GPIO14 | I2C1 Data
General Purpose Input/Output | JP8 | 4 | 5V | - | 5 V Output | +| JP7 | 5 | SCL1 | I2C1_SCL
GPIO13 | I2C1 Clock
General Purpose Input/Output | JP8 | 6 | GND | - | Ground | +| JP7 | 7 | P35 | GPIOX
UART4_TXD | General Purpose Input/Output
UART4 Send | JP8 | 8 | TX2 | UART2_TXD | UART2 Send | +| JP7 | 9 | GND | - | Ground | JP8 | 10 | RX2 | UART2_RXD | UART2 Recv | +| JP7 | 11 | P06 | GPIO3
PCM_DIN | General Purpose Input/Output
Digital Audio Input signal | JP8 | 12 | P37 | GPIOX
I2C_SDA | General Purpose Input/Output
I2C Data | +| JP7 | 13 | P05 | GPIO2
PCM_SYNC | General Purpose Input/Output
Digital Audio Sync signal | JP8 | 14 | GND | - | Ground | +| JP7 | 15 | P04 | GPIO1
PCM_CLK | General Purpose Input/Output
Digital Audio Clock signal | JP8 | 16 | P86 | GPIO19 | General Purpose Input/Output | +| JP7 | 17 | 3V3 | - | 3.3V Output | JP8 | 18 | P88 | GPIO21 | General Purpose Input/Output | +| JP7 | 19 | MO2 | SPI2_MOSI
GPIO8
UART0_TXD | SPI2 Master Output Slave Input
General Purpose Input/Output
UART0 Send | JP8 | 20 | GND | - | Ground | +| JP7 | 21 | MI2 | SPI2_MISO
GPIO7
UART0_RXD | SPI2 Master Input Slave Output
General Purpose Input/Output
UART0 Recv | JP8 | 22 | P20 | GPIOX | General Purpose Input/Output | +| JP7 | 23 | CLK2 | SPI2-CLK
GPIO5
I2C0_CLK | SPI2 Clock
General Purpose Input/Output
I2C0 Clock | JP8 | 24 | CS2 | SPI2_CS
GPIO6
I2C0_SDA | SPI2 Chip Select
General Purpose Input/Output
I2C0 Data | +| JP7 | 25 | GND | - | Ground | JP8 | 26 | P38 | GPIOX | General Purpose Input/Output | +| JP7 | 27 | P25 | GPIO9
SPI0_CS | General Purpose Input/Output
SPI0 Chip Select | JP8 | 28 | P26 | GPIO10
SPI0_CLK | General Purpose Input/Output
SPI0 Clock | +| JP7 | 29 | P34 | GPIOX
UART4_RXD | General Purpose Input/Output
UART4 Recv | JP8 | 30 | GND | - | Ground | +| JP7 | 31 | P87 | GPIO20 | General Purpose Input/Output | JP8 | 32 | PWM | PWM0
GPIO17 | PWM0 Output
General Purpose Input/Output | +| JP7 | 33 | P85 | GPIO18
PWM1 | General Purpose Input/Output
PWM1 Output | JP8 | 34 | GND | - | Ground | +| JP7 | 35 | P28 | GPIO12
SPI0_MISO
UART3_RXD | General Purpose Input/Output
SPI0 Master Input Slave Output
UART3 Recv | JP8 | 36 | P39 | GPIOX | General Purpose Input/Output | +| JP7 | 37 | P07 | GPIO4
PCM_DOUT | General Purpose Input/Output
Digital Audio Output signal | JP8 | 38 | P27 | GPIO11
SPI0_MOSI
UART3_TXD | General Purpose Input/Output
SPI0 Master Output Slave Input
UART3 Send | +| JP7 | 39 | GND | | Ground | JP8 | 40 | P36 | GPIOX
I2C_SCL | General Purpose Input/Output
I2C Clock | + +The main pin layout of the EVB is shown in the figure below. + +![img](./media/bg95/BG95_EVB.png) + +> **Note** +> For more information about QuecPython_BG95_EVB, please visit . + +### EVB Configuration + +The peripheral pin assignments are detailed as follows. + +| No. | Name | Model | Supported | Silkscreen | Remarks | +| --- | -------------------------| -------------| --------| ------| ----------| +| 1 | USB_TYPEC Interface | - | Yes | - | - | +| 2 | SIM Card Slot | SMN-315-ARP7 | Yes | CARD2 | Nano-SIM | +| 3 | LED Indicator (see below)| - | Yes | - | - | + +**On-board LED indicators:** + +- **SIM_CHK**: The SIM_CHK indicator lights up when a SIM card is inserted into the card slot. +- **NET**: Network indicator. +- **PSM**: Sleep mode indicator. +- **PWM**: PWM function indicator. +- **PWR**: Power indicator. + +> Refer to the silkscreen below the module in the EVB front figure (The module side) above for LED indicator locations. + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware for BG95 from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file (BG95 requires `.mbn` format for older versions). + - Set mode to "Download FW" and click **Download**. + - For BG95, enable DM serial port before burning. + + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | + +## Low Power Consumption Testing Guide + +The BG95 module supports multiple operating modes, each with distinct power consumption characteristics. The common operating modes are as follows: + +**ACTIVE**: The module is engaged in LTE data transmission, GSM calls, or executing RTOS logic. Power consumption varies significantly depending on specific tasks and network communication standards, as both CPU power usage and RF power levels differ across scenarios. + +**IDLE**: The module is in an idle state with hardware fully powered and RTOS running, but no active threads. It resumes operation immediately upon task initiation or incoming network activity. ECX00U series modules reduce clock frequency in IDLE mode, entering a light sleep state (disabling high-speed clocks while keeping the CPU active). + +**Sleep**: Sleep mode requires the module to be idle with autosleep enabled. In this mode, RTOS pauses, clock frequency slows, and peripheral controllers (UART, SPI, etc.) are powered down, retaining only essential interrupt controllers to minimize power consumption. + +**PSM**: PSM (Power Saving Mode) is a 3GPP-defined low-power mode where the module periodically wakes to perform tasks and remains in PSM sleep otherwise. During PSM sleep, behavior and power consumption resemble a powered-off state. + +**Power Off**: The module is fully powered down, with baseband chips and peripheral controllers disabled (PMIC remains active). It can be awakened via Powerkey or RTC alarm. + +| Module Model | BG95 | +| :------------------- | :------------------- | +| IDLE (LTE FDD@64ms) | 18.9 mA (catm@128ms) | +| SLEEP (LTE FDD@64ms) | 1.89 mA (catm@128ms) | +| SLEEP (CFUN0) | 0.575 mA | +| PSM | 5.10 μA | +| Power Off | 14.87 μA | + +### Test Preparation + +- **Step 1: Hardware Setup** + + Prepare the following components before starting: + + 1. **Development Board** + 2. **USB Cable** (USB-A to USB-TypeC) + 3. **PC** (Windows 10) + 4. **SIM Card** + 5. **4G Antenna** + 6. **Power Monitor Mini** + +- **Step 2: Antenna & SIM Card Installation** + + Install the provided antenna into the MAIN antenna socket and insert the SIM card into the development board's SIM slot. + +- **Step 3: Board Connection** + + Connect the development board's Type-C port to the PC using a USB Type-C cable. Attach the power monitor's positive lead to MODULE_EN's Vbat (refer to [BG95 User Guide](https://developer.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E4%BA%A7%E5%93%81%E8%A7%84%E6%A0%BC%E5%8F%8A%E7%94%A8%E6%88%B7%E6%8C%87%E5%AF%BC.pdf)) and the negative lead to the module's GND. Connection diagram: + + + + > **Important!** + > Remove all jumper caps during measurements to avoid external interference. + +### Power Consumption Measurement + +#### Power-Off Current + +With the board connected via USB Type-C, power off the module by disabling USB_VBus (set USB switch to "off" on the board's rear). Measure the current while the module is inactive (output pins pulled low/floating). Average current remains stable at microampere levels. + + Power-off current measurement + +#### Idle Current + +After power-off measurement, press and hold Powerkey to boot the module (default: IDLE mode). The module remains idle with RTOS running but no active threads, ready to resume instantly for tasks or calls. + + Idle current measurement + +#### Sleep Current + +With autosleep enabled during idle, the module enters sleep mode by deactivating non-essential IP cores (peripherals/interrupts) and reducing clock frequency. + +1. Re-enable USB_VBus. + +2. Open [QPYcom Tool](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip) and execute: + + ```python + import pm + pm.autosleep(1) # Enable autosleep + ``` + + Sleep current waveform + +3. Disable USB_VBus again (switch to "off"). + [API Reference](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#pm.autosleep) | [Details](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html) + +4. Sleep current shows periodic spikes: + Sleep current waveform + +#### PSM Current + +To enable PSM: + +1. Request PSM from the base station (via ATTACH/TA_UPDATER with timer parameters). + - Note: Base station determines final timer values. +2. Once ACT timer expires in IDLE, the module shuts down CPU/RF (partial power-off), retaining wake-up sources (ACT/TAU timers, PSM_INT). + +Steps: + +1. Enable USB_VBus. + +2. [PSM Guide](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html) | [API](https://developer.quectel.com/doc/quecpython/API_reference/en/syslib/pm.html). In QPYcom: + + ```python + pm.set_psm_time(tau_uint,tau_time,act_uint,act_time) # Configure PSM + ``` + + PSM current measurement + +3. Disable USB_VBus. + +4. PSM baseline current (µA-level, similar to power-off): + PSM current measurement + +> **Notes:** +> +> - Confirm carrier support for PSM and configure compatible network standards (this test uses catM). +> - [Additional guidance](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html). diff --git a/docs/Dev_board_guide/en/config.json b/docs/Dev_board_guide/en/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4fb9d61deba9ec6379de76d40ccd0a383a601708 --- /dev/null +++ b/docs/Dev_board_guide/en/config.json @@ -0,0 +1,4 @@ +{ + "import": "config_en", + "name": "Getting_started" +} \ No newline at end of file diff --git a/docs/Dev_board_guide/en/ec200x-evb.md b/docs/Dev_board_guide/en/ec200x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..952dbdc2cfda8569a2dffa6ddd0cdcba2ed70f02 --- /dev/null +++ b/docs/Dev_board_guide/en/ec200x-evb.md @@ -0,0 +1,346 @@ +# Introduction to EC200U/A Evaluation Board + +## Supported Module List + +- [EC200U-CN](https://python.quectel.com/en/modules-cat/ec200u-series) +- [EC200U-EU](https://python.quectel.com/en/modules-cat/ec200u-series) +- [EC200A-CN](https://python.quectel.com/en/modules-cat/ec200a-series) +- [EC200A-AU](https://python.quectel.com/en/modules-cat/ec200a-series) +- [EC200A-EU](https://python.quectel.com/en/modules-cat/ec200a-series) + +## Feature List + +### Basic Overview + +The QuecPython_EC200U/A C4-P01 evaluation board is a compact and portable board designed specifically for QuecPython. + +The main equipped modules are the EC200U/A series LTE Cat 1/LTE Cat 4 wireless communication modules. + +The evaluation board has a USB Type-C interface, making it convenient for development. Developers only need a USB Type-C cable to easily use the evaluation board. + +Additionally, the evaluation board is compatible with the expansion board of Raspberry Pi Zero, which can be directly used on the evaluation board. + + +## Evaluation Board Resources + +### Function Description + +The main component and interface placement of the evaluation board is shown in the following figure: + +![img](./media/ec200x-evb/200U-1.png) + +Evaluation board dimensions: + +![img](./media/ec200x-evb/200U-chicun.png) + +The main pin placement of the evaluation board is shown in the following figure: + +![img](./media/ec200x-evb/EC200X_EVB.png) + +> **Tip** +> +> The function multiplexing pins beginning with A/U in the figure indicate the functional difference of EC200A and EC200U series modules, that is, the function multiplexing pins beginning with U will take effect only when the module is EC200U. The function multiplexing pins starting with A takes effect only when the module is EC200A. +> +> For more information about the evaluation board, please visit . + + +### Evaluation Board Configuration + +The detailed assignment of the peripheral interfaces on the evaluation board is as follows: + +| No. | Name | Model | Silkscreen | Comment | +| ---- | -------------- | ------------ | ---------- | ------------------------------------------------------------ | +| 1 | USB Type-C Interface | - | - | - | +| 2 | SIM Card Slot 1| SMN-315-ARP7 | SIM1 | Nano-SIM | +| 3 | SIM Card Slot 2| MUP-C7809-1 | SIM2 | - | +| 4 | SD Card Slot | TF-101A-P3 | SD | Before using the SD card, enable SD to provide power to the SD card in the 10-Pin Header. | +| 5 | USB Power Supply Switch | - | USB_ON/OFF | When the switch is normally closed, Type-C supplies power to the module and evaluation board, and USB can be connected normally. When the USB switch is normally open, Type-C supplies power only to the evaluation board. In this case, the module is not powered. | +| 6 | MIPI Interface | - | MIPI_DSI | When the main module is EC200U-XX, it supports MIPI LCD and is fully compatible with Raspberry Pi peripherals. | +| 7 | Camera Interface | - | - | The evaluation board supports customized SPI cameras with a maximum of 300,000 pixels. | +| 8 | Matrix Keyboard Interface | - | KO&KI | The matrix keyboard function is reserved. Users can customize the soldering or connection of the keyboard keys. No matrix keyboard on the board by default. | +| 9 | MIC&SPK Interface | AW8733A | +MIC-/-SPK+ | - | +| 10 | 40-Pin Header | - | - | Onboard 40-Pin header; For details, see the above figure and table. | +| 11 | 10-Pin Header | - | - | Onboard 10-Pin header; For details, see the above figure and table. | +| 12 | ADC Interface | - | ADC0_IN/ADC1_IN | ADC testing interface | +| 13 | PWK Botton | - | PWK | Turn-on button | +| 14 | RST Button | - | RST | Reset button | +| 15 | BOOT Button | - | BOOT | Firmware burning button | +| 16 | Antenna Interfaces | - | LTE
DIV/WIFI/BT
GNSS | LTE antenna connector
DIV/Wi-Fi/Bluetooth antenna connector
GNSS antenna connector | + +**The evaluation board has 5 functional indication LEDs, as follows:** + +- **P01**: Module Pin 1, default as EC200A-XX PWM0. +- **P05**: Module Pin 5, NET_MODE indication LED. +- **SCK1**: SIM1 detection indication LED, lights up when SIM1 is inserted. +- **SCK2**: SIM2 detection indication LED, lights up when SIM2 is inserted. Default connection to Pin 128. EC200A-XX does not have SIM2, this LED can be ignored. +- **PWR**: Power indication LED. + +> The positions of the above indication LEDs refer to the silkscreen on the top of the evaluation board mentioned in the previous text (the side where the module is located is the top). + +### Evaluation Board Interfaces + +This evaluation board provides 40 pins compatible with Raspberry Pi, as well as 10 pins with enabling function. The functions of the evaluation board are described as follows: + +**Pin Assignment of 10-Pin Header ** + +| **Header** | **No.** | **Silk**screen | **Function** | +| ---------- | ------- | -------------- | ------------ | +| 10-Pin | 1 | PWK_AUTO | POWERKEY Auto turn on | +| 10-Pin | 2 | PWK_AUTO | GND Auto turn on | +| 10-Pin | 3 | VDD_EXT | 1.8 V Provide power externally when connected and test power consumption when disconnected | +| 10-Pin | 4 | VDD_EXT | VDD_EXT Provide power externally when connected and test power consumption when disconnected | +| 10-Pin | 5 | MODULE_EN | 3.8 V Connect DCDC to power the module | +| 10-Pin | 6 | MODULE_EN | 3.8 V Connect DCDC to power the module | +| 10-Pin | 7 | SD_EN | SD_EN Enable SD power supply | +| 10-Pin | 8 | SD_EN | 3.3 V Enable SD power supply | +| 10-Pin | 9 | GNSS_EN | 3.3 V Enable GNSS active power supply | +| 10-Pin | 10 | GNSS_EN | GNSS_EN Enable GNSS active power supply | + +> When testing power consumption, make sure to switch off the USB power supply switch (USB_ON/OFF) on the back of the evaluation board. + +**Singular-pin Assignment of 40-Pin Header** + +| **Header** | No. | **Name** | **Function Multiplexing** | **Function** | +| ---------- | -------------- | -------- | ------------------------ | ------------ | +| 40-Pin | 1 | 3V3 | - | 3.3 V output | +| 40-Pin | 3 | SDA | I2C0_SDA/GPIO35 | I2C0 serial data/General-purpose input/output | +| 40-Pin | 5 | SCL | I2C0_SCL | I2C0 serial clock | +| 40-Pin | 7 | P06 | GPIO46/A_PWM2 | General-purpose input/output/PWM2 output (When the module is EC200A) | +| 40-Pin | 9 | GND | - | Ground | +| 40-Pin | 11 | P64 | GPIO19 | General-purpose input/output | +| 40-Pin | 13 | P136 | GPIO7 | General-purpose input/output | +| 40-Pin | 15 | P03 | GPIO9 | General-purpose input/output | +| 40-Pin | 17 | 3V3 | - | 3.3 V output | +| 40-Pin | 19 | MO1 | SPI1_MOSI/GPIO3 | SPI1 master-out slave-in/General-purpose input/output | +| 40-Pin | 21 | MI1 | SPI1_MISO/GPIO4 | SPI1 master-in slave-out/General-purpose input/output | +| 40-Pin | 23 | CLK1 | SPI1_CLK/GPIO1 | SPI1 clock/General-purpose input/output | +| 40-Pin | 25 | GND | - | Ground | +| 40-Pin | 27 | P63 | GPIO44/A_UART1_TXD | General-purpose input/output/UART1 transmit (When the module is EC200A) | +| 40-Pin | 29 | P01 | GPIO28/A_PWM0 | General-purpose input/output/PWM0 output (When the module is EC200A) | +| 40-Pin | 31 | P02 | GPIO29 | General-purpose input/output | +| 40-Pin | 33 | P04 | GPIO30/A_PWM1 | General-purpose input/output/PWM1 output (When the module is EC200A) | +| 40-Pin | 35 | P39 | GPIO13/A_SPI0_MISO | General-purpose input/output/SPI0 master-in slave-out (When the module is EC200A) | +| 40-Pin | 37 | P134 | GPIO37 | General-purpose input/output | +| 40-Pin | 39 | GND | | Ground | + +**Double-pin Assignment of 40-Pin Header** + +| Header | No. | **Name** | **Function Multiplexing** | **Function** | +| ------ | ---- | -------- | ------------------------- | ------------------------------------------------------------ | +| 40-Pin | 2 | 5V | - | 5 V output | +| 40-Pin | 4 | 5V | - | 5 V output | +| 40-Pin | 6 | GND | - | Ground | +| 40-Pin | 8 | TXD | UART2_TXD | UART2 transmit | +| 40-Pin | 10 | RXD | UART2_RXD | UART2 receive | +| 40-Pin | 12 | P37 | GPIO11/A_SPI0_CS | General-purpose input/output/SPI0 chip select (When the module is EC200A) | +| 40-Pin | 14 | GND | - | Ground | +| 40-Pin | 16 | P133 | GPIO8 | General-purpose input/output | +| 40-Pin | 18 | P65 | GPIO18 | General-purpose input/output | +| 40-Pin | 20 | GND | - | Ground | +| 40-Pin | 22 | P127 | GPIO22 | General-purpose input/output | +| 40-Pin | 24 | CS1 | SPI1_CS/GPIO2 | SPI1 chip select/General-purpose input/output | +| 40-Pin | 26 | P139 | GPIO20 | General-purpose input/output | +| 40-Pin | 28 | P66 | GPIO45/A_UART1_RXD | General-purpose input/output/UART1 receive (When the module is EC200A) | +| 40-Pin | 30 | GND | - | Ground | +| 40-Pin | 32 | P135 | GPIO6/U_PWM0 | General-purpose input/output/PWM0 output (When the module is EC200U) | +| 40-Pin | 34 | GND | - | Ground | +| 40-Pin | 36 | P62 | GPIO43 | General-purpose input/output | +| 40-Pin | 38 | P38 | GPIO12/A_SPI0_MOSI | General-purpose input/output/SPI0 master-out slave-in (When the module is EC200A) | +| 40-Pin | 40 | P40 | GPIO10/A_SPI0_CLK | General-purpose input/output/SPI0 clock (When the module is EC200A) | + +- ## Quick Start Guide + + ### Hardware Preparation + + - **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + + - **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + + - **Step 3: Connect the Board** + + - Power the board via USB-C. + + - **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + + ### Driver Installation + + 1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). + 2. Extract and run `setup.exe` or `setup.bat`. + 3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + + ### Tool Installation + + 1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. + 2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + + ### Firmware Burning + + 1. **Firmware Download**: Get the latest QuecPython firmware from [QuecPython Firmware](https://developer.quectel.com/en/resource-download?cid=2) Page. + + 2. **Burning Steps**: + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + - For BG95, enable DM serial port before burning. + + ![download_firmware1](./media/readme/download_firmware1.png) + + ![download_firmware2](./media/readme/download_firmware2.png) + + download_firmware3 + + ### REPL Debugging + + 1. Connect via QPYcom and open the REPL interface. + 2. Test with `print("Hello World!")`. + + ![hello](./media/readme/hello.png) + + ## First Script Development + + ### Writing a Script + + Create `helloworld.py`: + + ```python + print("Hello World!") + ``` + + ### File Transfer + + - **Method 1**: Drag-and-drop files via QPYcom’s GUI. + + ![download_script1](./media/readme/download_script1.jpg) + + - **Method 2**: Use the "Download Script" feature in QPYcom. + + ![download_script1](./media/readme/download_script2.jpg) + + ### Running Scripts + + Execute via REPL: + + ```python + import example + example.exec("/usr/helloworld.py") + ``` + + ### Stopping Program Execution + + How to stop a running program. The following methods are provided according to the type of the running script file: + + | Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | + | :--------------------------: | :-----------------------------------: | :------------------------------------: | ------------------------------------------------------------ | + | ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | + | ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | + | ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | + | ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | + | ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | + | ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | + | ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | + | ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | + + ## Low Power Consumption Testing Guide + + TheEC200X module supports multiple operating modes, each with distinct power consumption characteristics. The common operating modes are as follows: + + **ACTIVE**: The module is engaged in LTE data transmission, GSM calls, or executing RTOS logic. Power consumption varies significantly depending on specific tasks and network communication standards, as both CPU power usage and RF power levels differ across scenarios. + + **IDLE**: The module is in an idle state with hardware fully powered and RTOS running, but no active threads. It resumes operation immediately upon task initiation or incoming network activity. ECX00U series modules reduce clock frequency in IDLE mode, entering a light sleep state (disabling high-speed clocks while keeping the CPU active). + + **Sleep**: Sleep mode requires the module to be idle with autosleep enabled. In this mode, RTOS pauses, clock frequency slows, and peripheral controllers (UART, SPI, etc.) are powered down, retaining only essential interrupt controllers to minimize power consumption. + + **PSM**: PSM (Power Saving Mode) is a 3GPP-defined low-power mode where the module periodically wakes to perform tasks and remains in PSM sleep otherwise. During PSM sleep, behavior and power consumption resemble a powered-off state. + + **Power Off**: The module is fully powered down, with baseband chips and peripheral controllers disabled (PMIC remains active). It can be awakened via Powerkey or RTC alarm. + + + + | Module Model | ECX00U | + | :------------------- | :------- | + | IDLE (LTE FDD@64ms) | 12.34 mA | + | SLEEP (LTE FDD@64ms) | 2.05 mA | + | SLEEP (CFUN0) | 1.29 mA | + | Power Off | 40 μA | + + + + ### Test Preparation + + - **Step 1: Hardware Setup** + + Prepare the following components before starting: + + 1. **Development Board** + 2. **USB Cable** (USB-A to USB-TypeC) + 3. **PC** (Windows 10) + 4. **SIM Card** + 5. **4G Antenna** + 6. **Power Monitor Mini** + + - **Step 2: Antenna & SIM Card Installation** + + Install the provided antenna into the MAIN antenna socket and insert the SIM card into the development board's SIM slot. + + - **Step 3: Board Connection** + + Connect the development board's Type-C port to the PC using a USB Type-C cable. Attach the power monitor's positive lead to MODULE_EN's Vbat (refer to [BG95 User Guide](https://developer.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E4%BA%A7%E5%93%81%E8%A7%84%E6%A0%BC%E5%8F%8A%E7%94%A8%E6%88%B7%E6%8C%87%E5%AF%BC.pdf)) and the negative lead to the module's GND. Connection diagram: + + + + > **Important!** + > Remove all jumper caps during measurements to avoid external interference. + + ### Power Consumption Measurement + + #### Power-Off Current + + With the board connected via USB Type-C, power off the module by disabling USB_VBus (set USB switch to "off" on the board's rear). Measure the current while the module is inactive (output pins pulled low/floating). Average current remains stable at microampere levels. + + Power-off current measurement + + #### Idle Current + + After power-off measurement, press and hold Powerkey to boot the module (default: IDLE mode). The module remains idle with RTOS running but no active threads, ready to resume instantly for tasks or calls. + + Idle current measurement + + #### Sleep Current + + With autosleep enabled during idle, the module enters sleep mode by deactivating non-essential IP cores (peripherals/interrupts) and reducing clock frequency. + + 1. Re-enable USB_VBus. + + 2. Open [QPYcom Tool](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip) and execute: + + ```python + import pm + pm.autosleep(1) # Enable autosleep + ``` + + Sleep current waveform + + 3. Disable USB_VBus again (switch to "off"). + [API Reference](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#pm.autosleep) | [Details](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html) + + 4. Sleep current shows periodic spikes: + Sleep current waveform + + > **Notes:** + > + > - [Additional guidance](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html). diff --git a/docs/Dev_board_guide/en/ec2x-evb.md b/docs/Dev_board_guide/en/ec2x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..da56f967f0e690d0c005d656f997a9671e806489 --- /dev/null +++ b/docs/Dev_board_guide/en/ec2x-evb.md @@ -0,0 +1,218 @@ + +# EC2X EVB Introduction + +## Supported Modules + +Supported module models + +- [EC200U-EU](https://python.quectel.com/en/modules-cat/ec200u-series) +- [EC200A-EU](https://python.quectel.com/en/modules-cat/ec200a-series) +- [EC200A-AU](https://python.quectel.com/en/modules-cat/ec200a-series) + +## Feature List + +### Basic Overview + +The QuecPython_EC2X_EVB is specifically designed for QuecPython. It is a small and portable "pocket-sized" EVB with rich features, such as temperature and humidity sensor, acceleration sensor, SIM card slot, SD card slot, LCD connector, LDR and MIC. + +The EVB is equipped with a Type-C interface, so developers only need a USB Type-C cable to easily manipulate the EVB. + +The EVB is equipped with the EC200U series module. For details, see [EC200U-EU](https://python.quectel.com/en/modules-cat/ec200u-series). + +### Feature Description + +The main components and interface layout of the EVB are shown in the figure below. + +![](./media/ec2x-evb/peripheral-interfaces.png) + +## Document download + +- [EC2X_EVB_SCH2](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/EC200A_zsus-Series-EVB_SCH.pdf) + +## EVB Resources + +### EVB Interface + +**J5 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | ------- | ------- | +| J5 | - | VCC_5V | 5V | +| J5 | - | VCC_5V | 5V | +| J5 | - | GND | Ground | +| J5 | 24 | IO3 | GPIO3 | +| J5 | 25 | IO4 | GPIO4 | +| J5 | 26 | IO2 | GPIO2 | +| J5 | 27 | IO1 | GPIO1 | +| J5 | 44 | ADC1_IN | ADC1 | +| J5 | - | VDD_EXT | 1.8 V | + +**J6 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | ------- | ---------------------- | +| J6 | - | V3.3 | 3.3 V | +| J6 | - | GND | Ground | +| J6 | - | GND | Ground | +| J6 | 3 | IO9 | GPIO9 | +| J6 | 119 | SD_EN | SD card enable control | +| J6 | 142 | SDA | I2C1 | +| J6 | 141 | SCL | I2C1 | +| J6 | 43 | ADC2_IN | ADC2 | +| J6 | 45 | ADC0_IN | ADC0 | + +**J7 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | ---- | ------- | +| J7 | - | GND | Ground | +| J7 | 138 | RX1 | UART1 | +| J7 | 137 | TX1 | UART1 | +| J7 | 67 | TX2 | UART2 | +| J7 | 68 | RX2 | UART2 | +| J7 | 65 | IO18 | GPIO18 | +| J7 | 64 | IO19 | GPIO19 | +| J7 | 11 | D_RX | UART | +| J7 | 12 | D_TX | UART | + +**J10 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | ---- | ------- | +| J10 | 136 | IO7 | GPIO7 | +| J10 | 135 | IO6 | GPIO6 | +| J10 | 127 | IO22 | GPIO22 | +| J10 | 40 | IO10 | GPIO10 | +| J10 | 39 | IO13 | GPIO13 | +| J10 | 38 | IO12 | GPIO12 | +| J10 | 37 | IO11 | GPIO11 | +| J10 | - | GND | Ground | +| J10 | - | V3.8 | 3.8 V | + +The following figure shows the pin assignment. + +![](./media/ec2x-evb/EC2X_EVB.png) + +> **Tips** +> For more information about the EVB, please visit + +### EVB Configuration + +The EVB is equipped with various sensors and other peripherals. The pins of peripherals are shown in the table below. + +| Pin No. | Name | Model | Supported | Interface Type | +| --------- | ------------------------------------ | ------------- | --------- | -------------- | +| 41 and 42 | Temperature and Humidity Sensor | AHT20 | Yes | I2C | +| 45 | LDR | GT36528 | Yes | ADC | +| 41 and 42 | G-Sensor | QMA7981 | Yes | I2C | +| 75 and 77 | Microphone | GMI6050P-66DB | Yes | SPK | +| 73 and 74 | Power Amplifier Chip | NS4160 | Yes | SPK | +| 122–125 | LCD (Choose the package with screen) | ST7789 | Yes | SPI | +| 28–34 | SD_CARD | XKTF-NO2-N | Yes | SPI | + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | diff --git a/docs/Dev_board_guide/en/ec600u-235.md b/docs/Dev_board_guide/en/ec600u-235.md new file mode 100644 index 0000000000000000000000000000000000000000..13025615dbd0304f1194d0e84ee442c8ec34c09a --- /dev/null +++ b/docs/Dev_board_guide/en/ec600u-235.md @@ -0,0 +1,213 @@ +# EC600U U-235 EVB Introduction + +## Feature List + +### Basic Overview + +QuecPython U-235 large screen evb integrates almost all the functions of the existing modules, including a wealth of peripherals, including external Flash, WiFi, screen and so on. + +The evaluation board has a USB Type-C interface, making it convenient for development. Developers only need a USB Type-C cable to easily use the evaluation board. + +### Function Description + +This section provides instructions for some functions of the U-235 EVB. + + +![](./media/ec600u-235-evb/image8.jpg) + +1. **SD Card: ** + +Pull up Pin 53 (QuecPython GPIO27) of the EC600U module. + +2. **Wi-Fi Module: ** + +Pull the switch marked with "3" in the figure above to the "**GND**" side to download the firmware of the Wi-Fi module through the UART of the Wi-Fi module (marked with "2" in the figure above). After the download is complete, pull the switch marked with "3" to the "**NONE**" side, and reboot the Wi-Fi module. To enable the communication between the Wi-Fi module and the EC600U module, pull up Pin 3 of the EC600U module to switch the pin from UART 1 to Wi-Fi UART and pull up Pin 121 to power the Wi-Fi module. + +3. **Zigbee: ** + +When Pin 3 of the EC600U module is at a low level, the serial port marked with "1" in the figure above functions as UART 1. When this pin is at a high level, the serial port marked with "1" functions as Zigbee. + +4. **MIC & SPK: ** + +Both the left channel and the right channel of the microphone and the speaker interfaces are available. + +5. **External Power Supply:** + +Pull the Power Supply Selection Switch to the “**5V**” side, and connect the external power supply through the 5V Power Supply Interface. The maximum input voltage is 6.5 V. + +6. **Buzzer:** + +Pull up or down Pin 119 of the EC600U module to control the buzzer sound. + +7. **RS-485:** + +The RS-485 interface is connected to a physical serial port by default and communicates through UART 2. + +8. **MIPI:** + +Pull up Pin 118 (QuecPython GPIO 8) of the EC600U module. + +9. **Audio:** + +To enable PA, pull up Pin 4 (QuecPython GPIO 11) of the EC600U module. + +10. **Screen**: + +ST7701, 5 inch, MIPI interface, 480x854 Resolution, Capacitive touch screen, Touch chip GT911 + + +> In the QuecPython solution, for details about the correspondence between GPIOs and pins of EC600U series, please refer to QuecPython Documentation > Wiki > Peripherals > machine – Hardware > class Pin – Control I/O Pins. [**Control I/O Pins**](https://python.quectel.com/doc/API_reference/en/peripherals/machine.Pin.html) + +## Resource Download + +- [EC600U_U-235_EVB_SCH](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/12/EC600U_U-235_EVB_SCH.pdf) +- [Quectel_QuecPython_U 235_EVB](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/12/EC600U_U-235_EVB_Specification_and_User_Guide.pdf) + +## Evaluation Board Resources + +The abundant onboard resources of U-235 EVB are illustrated by the figure below: + +![](./media/ec600u-235-evb/image7.png) + +Starting from the "EC600U Module" indicator box in the figure above, the EVB resources are introduced as follows in a clockwise direction. + +- EC600U Module: The CPU with a Flash of 8 MB and a RAM of 16 MB. +- MIPI Screen I/O Interface +- MIPI LED Backlight Module +- Speaker R: The right channel speaker +- MIC: The microphone interface +- Speaker L: The left channel speaker +- TP I/O Interface +- Temperature & Humidity Sensor +- 5V Power Supply: The interface for 5V power supply +- Power Supply Selection Switch: The switch to select USB power supply or external power supply +- USB: The USB interface for downloading program codes and debugging scripts +- SIM Card Slot +- Ordinary Key: Three ordinary keys (no default function) +- Buzzer +- PWR Key: The power key for turning on/off the EC600U module +- RST Key: The reset key for reseting the EC600U module +- BOOT Key: The USB boot key for force-downloading firmware +- Camera Interface: The camera interface supporting taking photos and scanning +- Flash/MIPI_TE Selection Switch: If you need to use an external Flash, you must switch to the SIO3 side because the SIO3 of the Flash conflicts with the MIPI_TE pin. And most MIPI screens do not use MIPI_TE, so this switch is usually switched to the SIO3 side. +- Extended SPI Flash: The memory of the Flash W25Q32JWUUIQ is 4 MB. +- LTE Antenna Connector +- Wi-Fi Module +- WRST Key: The reset key for resetting the Wi-Fi module +- Ordinary KEY1 (no default function) +- Ordinary KEY2 (no default function) +- Wi-Fi Module UART +- TP Level Selection Switch: The switch to select the voltage level (1.8 V or 3.3 V) of the touch panel +- TP Interface +- SD Card Slot +- MIPI Screen Interface +- RS-485 Interface: SP3485EIM/TR is used + +> The MIPI interface and the TP interface are available synchronously to improve the reusability of U-235 EVB. + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware for EC600U from [QuecPython Firmware](https://developer.quectel.com/en/resource-download?cid=2) Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | diff --git a/docs/Dev_board_guide/en/ec800x-core-evb.md b/docs/Dev_board_guide/en/ec800x-core-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..0b95d415f1f2b9771900e1ee05f9c6db54a3993b --- /dev/null +++ b/docs/Dev_board_guide/en/ec800x-core-evb.md @@ -0,0 +1,47 @@ +# EC800X Core EVB Introduction + +## Quick Start + +Supported Module List + +- [EC800M-CNGB](https://developer.quectel.com/en/modules-cat/ec800m-series) +- [EC800M-CNGD](https://developer.quectel.com/en/modules-cat/ec800m-series) +- [EC800E-CNLE](https://developer.quectel.com/en/modules-cat/ec800m-series) +- [EC800M-CNLF](https://developer.quectel.com/en/modules-cat/ec800m-series) + +## Feature List + +### Overview + +The QuecPython_EC800X core board is a core development board with the smallest functions specially made for QuecPython. Users can choose the corresponding model according to their needs, including single-row pin pure data transmission version, double-row pin pure data transmission version, single-row pin positioning data transmission version and double-row pin positioning data transmission version. + +## Functional Description + +The main functional components and interface layout of the development board are shown in the figure below. + +![](./media/ec800x-core-evb/核心板-产品功能.png) + +## **Documents Download** + +- [EC800X_Series_EVB_SCH](https://developer.quectel.com/en/wp-content/uploads/sites/2/2024/12/EC800X_Series_EVB_SCH.pdf) +- [EC800X_Series_EVB_SilkScreen](https://developer.quectel.com/en/wp-content/uploads/sites/2/2024/12/EC800X_Series_EVB_SilkScreen.pdf) + +## EVB Resources + +The main pin layout of the development board is shown in the following figure. + +![](./media/ec800x-core-evb/核心板-熵.png) + +![](./media/ec800x-core-evb/核心板-宇.png) + +## Getting Started Preparation + +**Step1: Antenna Installation** + +Install the antenna that comes with the development board. The installation location is the LTE antenna seat, and insert the SIM card into the SIM card seat on the development board. If you need to use the GNSS function, you need to install the antenna in the corresponding antenna seat. + +**Step2: Development board connection** + +Use a USB Type-C data cable to connect the Type-C/Micro USB port of the development board and the USB port of the computer to complete the power supply and startup. + +> If the POW light stays on, it means the power on is successful. \ No newline at end of file diff --git a/docs/Dev_board_guide/en/eg91x-evb.md b/docs/Dev_board_guide/en/eg91x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..8847d7edae5318a4fca07a665cfdef5f54c3acd1 --- /dev/null +++ b/docs/Dev_board_guide/en/eg91x-evb.md @@ -0,0 +1,349 @@ +# Introduction to EG91X Evaluation Board + +## Supported Module List + +- [EG915U](https://python.quectel.com/en/modules-cat/eg915u-series) + + + +## Feature List + +### Basic Overview + +The QuecPython_EG91X series C1-P02 evaluation board is a compact and portable "pocket-sized" board designed specifically for QuecPython. + +The main equipped modules are the EG915U series LTE Cat 1 wireless communication modules, which are also compatible with Quectel's EG91 series, EG95 series, BG95 series, and BG96 modules in terms of packaging. This allows for seamless switching between 2G and 4G networks to meet the application requirements of different industries. + +The evaluation board has a built-in Type-C interface, making it convenient for development. Developers only need a USB Type-C cable to easily use the evaluation board. + +Additionally, the evaluation board is compatible with the expansion board of Raspberry Pi Zero, which can be directly used on the evaluation board. + + + + + + +## Evaluation Board Resources + +### Function Description + +The main component and interface placement of the evaluation board is shown in the following figure: + +![img](./media/eg91x-evb/EG915U_1.png) + +Evaluation board dimensions: + +![img](./media/eg91x-evb/915U_chicun.png) + +The main pin placement of the evaluation board is shown in the following figure: + +![img](./media/eg91x-evb/EG91X_EVB.png) + +> **Note** +> For more information about the evaluation board, please visit . + + + +### Evaluation Board Configuration + +The detailed assignment of the peripheral interfaces on the evaluation board is as follows: + +| No. | Name | Model | Silkscreen | Comment | +| ---- | ----------------------- | ------------ | ---------------------------- | ------------------------------------------------------------ | +| 1 | USB Type-C Interface | - | - | - | +| 2 | SIM Card Slot 1 | SMN-315-ARP7 | SIM1 | Nano-SIM | +| 3 | SIM Card Slot 2 | MUP-C7809-1 | SIM2 | E-SIM | +| 4 | SD Card Slot | TF-101A-P3 | SD 2.0 | Before using the SD card, enable SD to provide power to the SD card in the 10-Pin Header. | +| 5 | USB Power Supply Switch | - | USB_ON/OFF | When the switch is normally closed, Type-C supplies power to the module and evaluation board, and USB can be connected normally. When the USB switch is normally open, Type-C supplies power only to the evaluation board. In this case, the module is not powered. | +| 6 | MIPI Interface | - | MIPI_DSI | When the main module is EG91X series, it supports MIPI LCD and is fully compatible with Raspberry Pi peripherals. | +| 7 | Camera Interface | - | - | The evaluation board supports customized SPI cameras with a maximum of 300,000 pixels. | +| 8 | MIC&SPK Interface | AW8733A- | +MIC-/-SPK+ | - | +| 9 | 40-Pin Header | - | - | Onboard 40-Pin header; For details, see the above figure and table. | +| 10 | 10-Pin Header | - | - | Onboard 10-Pin header; For details, see the above figure and table. | +| 11 | ADC Interface | - | ADC1_IN | ADC testing interface | +| 12 | PWK Botton | - | PWK | Turn-on button | +| 13 | RST Button | - | RST | Reset button | +| 14 | BOOT Button | - | BOOT | Firmware burning button | +| 15 | Antenna Interfaces | - | LTE
DIV/WIFI/BT
GNSS | LTE antenna connector
DIV/Wi-Fi/Bluetooth antenna connector
GNSS antenna connector | + +**The evaluation board has 5 functional indication LEDs, as follows:** + +- **P21**: Power indication LED. +- **PSM**: Module Pin 1, PSM indication LED. +- **SCK1**: SIM1 detection indication LED, lights up when SIM1 is inserted. +- **SCK2**: SIM2 detection indication LED, lights up when SIM2 is inserted. +- **PWR**: Power indication LED. + +> The positions of the above indication LEDs refer to the silkscreen on the top of the evaluation board mentioned in the previous text (the side where the module is located is the top). + + +### Evaluation Board Interfaces + +**Pin Assignment of 10-Pin Header** + +| **Header** | **No.** | **Silk**screen | **Function** | +| ---------- | ------- | -------------- | ------------ | +| 10-Pin | 1 | PWK_AUTO | POWERKEY | +| 10-Pin | 2 | PWK_AUTO | GND | +| 10-Pin | 3 | VDD_EXT | 1.8 V | +| 10-Pin | 4 | VDD_EXT | VDD_EXT | +| 10-Pin | 5 | MODULE_EN | 3.8 V | +| 10-Pin | 6 | MODULE_EN | 3.8 V | +| 10-Pin | 7 | SD_EN | SD_EN | +| 10-Pin | 8 | SD_EN | 3.3 V | +| 10-Pin | 9 | GNSS_EN | 3.3 V | +| 10-Pin | 10 | GNSS_EN | GNSS_EN | + +- **1 & 2**: Auto turn on +- **3 & 4**: Provide power externally when connected and test power consumption when disconnected +- **5 & 6**: Connect DCDC to power the module +- **7 & 8**: Enable SD power supply +- **9 & 10**: Enable GNSS active power supply + +> When testing power consumption, make sure to switch off the USB power supply switch (USB_ON/OFF) on the back of the evaluation board. + +**Singular-pin Assignment of 40-Pin Header** + + +|**No ** | **Name** | **Function Multiplexing** | **Function** | **NO** | **Name** | **Function Multiplexing** | **Function** | +| -------- | -------- | ------------------- | --------------------------------- | -------- | -------- | ------------------- | --------------------------------- | +| 1 | 3V3 | - | 3.3 V Output | 2 | 5V | - | 5 V Output | +| 3 | SDA | I2C1_SDA
GPIO14 | I2C1 Data
General Purpose Input/Output | 4 | 5V | - | 5 V Output | +| 5 | SCL | I2C1_SCL
GPIO13 | I2C1 Clock
General Purpose Input/Output | 6 | GND | - | Ground | +| 7 | P92 | GPIO30 | General Purpose Input/Output | 8 | TXD | UART1_TXD | UART1 Send | +| 9 | GND | - | Ground | 10 | RXD | UART1_RXD | UART1 Recv | +| 11 | P116 | GPIO41 | General Purpose Input/Output | 12 | P05 | GPIO2
SPI1_CS | General Purpose Input/Output
SPI1 Chip Select | +| 13 | P16 | GPIO24 | General Purpose Input/Output | 14 | GND | - | Ground | +| 15 | P42 | GPIO26 | General Purpose Input/Output | 16 | P21 | GPIO17 | General Purpose Input/Output | +| 17 | 3V3 | - | 3.3 V Output | 18 | P111 | GPIO38 | General Purpose Input/Output | +| 19 | MO0 | SPI0_MOSI
GPIO15 | SPI0 Master Output Slave Input
General Purpose Input/Output | 20 | GND | - | Ground | +| 21 | MI0 | SPI0_MISO
GPIO21 | SPI0 Master Input Slave Output
General Purpose Input/Output | 22 | P37 | GPIO23 | General Purpose Input/Output | +| 23 | CLK0 | SPI0_CLK
GPIO10 | SPI0 Clock
General Purpose Input/Output | 24 | CS0 | SPI0_CS
GPIO9 | SPI0 Chip Select
General Purpose Input/Output | +| 25 | GND | - | Ground | 26 | P83 | GPIO28 | General Purpose Input/Output | +| 27 | P85 | GPIO18 | General Purpose Input/Output | 28 | P86 | GPIO19 |General Purpose Input/Output | +| 29 | P84 | GPIO29 | General Purpose Input/Output | 30 | GND | - | Ground | +| 31 | P104 | GPIO34 | General Purpose Input/Output | 32 | P20 | GPIO16
PWM0 | General Purpose Input/Output
PWM0 Output | +| 33 | P105 | GPIO35 | General Purpose Input/Output | 34 | GND | - | Ground | +| 35 | P07 | GPIO04
SPI1_MISO | General Purpose Input/Output
SPI1 Master Input Slave Output | 36 | P106 | GPIO36 | General Purpose Input/Output | +| 37 | P108 | GPIO37 | General Purpose Input/Output | 38 | P06 | GPIO3
SPI1_MOSI | General Purpose Input/Output
SPI1 Master Output Slave Input | +| 39 | GND | - | Ground | 40 | P04 | GPIO1
SPI1_CLK | General Purpose Input/Output
SPI1 Clock | + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | + +## Low Power Consumption Testing Guide + +The EG915U module supports multiple operating modes, each with distinct power consumption characteristics. The common operating modes are as follows: + +**ACTIVE**: The module is engaged in LTE data transmission, GSM calls, or executing RTOS logic. Power consumption varies significantly depending on specific tasks and network communication standards, as both CPU power usage and RF power levels differ across scenarios. + +**IDLE**: The module is in an idle state with hardware fully powered and RTOS running, but no active threads. It resumes operation immediately upon task initiation or incoming network activity. ECX00U series modules reduce clock frequency in IDLE mode, entering a light sleep state (disabling high-speed clocks while keeping the CPU active). + +**Sleep**: Sleep mode requires the module to be idle with autosleep enabled. In this mode, RTOS pauses, clock frequency slows, and peripheral controllers (UART, SPI, etc.) are powered down, retaining only essential interrupt controllers to minimize power consumption. + +**PSM**: PSM (Power Saving Mode) is a 3GPP-defined low-power mode where the module periodically wakes to perform tasks and remains in PSM sleep otherwise. During PSM sleep, behavior and power consumption resemble a powered-off state. + +**Power Off**: The module is fully powered down, with baseband chips and peripheral controllers disabled (PMIC remains active). It can be awakened via Powerkey or RTC alarm. + +| Module Model | EG915U | +| :------------------- | :------ | +| IDLE (LTE FDD@64ms) | 13.0 mA | +| SLEEP (LTE FDD@64ms) | 1.8 mA | +| SLEEP (CFUN0) | 1.0 mA | +| Power Off | 32 μA | + +### Test Preparation + +- **Step 1: Hardware Setup** + + Prepare the following components before starting: + + 1. **Development Board** + 2. **USB Cable** (USB-A to USB-TypeC) + 3. **PC** (Windows 10) + 4. **SIM Card** + 5. **4G Antenna** + 6. **Power Monitor Mini** + +- **Step 2: Antenna & SIM Card Installation** + + Install the provided antenna into the MAIN antenna socket and insert the SIM card into the development board's SIM slot. + +- **Step 3: Board Connection** + + Connect the development board's Type-C port to the PC using a USB Type-C cable. Attach the power monitor's positive lead to MODULE_EN's Vbat (refer to [BG95 User Guide](https://developer.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E4%BA%A7%E5%93%81%E8%A7%84%E6%A0%BC%E5%8F%8A%E7%94%A8%E6%88%B7%E6%8C%87%E5%AF%BC.pdf)) and the negative lead to the module's GND. Connection diagram: + + + + > **Important!** + > Remove all jumper caps during measurements to avoid external interference. + +### Power Consumption Measurement + +#### Power-Off Current + +With the board connected via USB Type-C, power off the module by disabling USB_VBus (set USB switch to "off" on the board's rear). Measure the current while the module is inactive (output pins pulled low/floating). Average current remains stable at microampere levels. + + Power-off current measurement + +#### Idle Current + +After power-off measurement, press and hold Powerkey to boot the module (default: IDLE mode). The module remains idle with RTOS running but no active threads, ready to resume instantly for tasks or calls. + + Idle current measurement + +#### Sleep Current + +With autosleep enabled during idle, the module enters sleep mode by deactivating non-essential IP cores (peripherals/interrupts) and reducing clock frequency. + +1. Re-enable USB_VBus. + +2. Open [QPYcom Tool](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip) and execute: + + ```python + import pm + pm.autosleep(1) # Enable autosleep + ``` + + Sleep current waveform + +3. Disable USB_VBus again (switch to "off"). + [API Reference](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#pm.autosleep) | [Details](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html) + +4. Sleep current shows periodic spikes: + Sleep current waveform + +#### PSM Current + +To enable PSM: + +1. Request PSM from the base station (via ATTACH/TA_UPDATER with timer parameters). + - Note: Base station determines final timer values. +2. Once ACT timer expires in IDLE, the module shuts down CPU/RF (partial power-off), retaining wake-up sources (ACT/TAU timers, PSM_INT). + +Steps: + +1. Enable USB_VBus. + +2. In QPYcom: + + ```python + pm.set_psm_time(tau_uint,tau_time,act_uint,act_time) # Configure PSM + ``` + + PSM current measurement + +3. Disable USB_VBus. + [PSM Guide](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html) | [API](https://developer.quectel.com/doc/quecpython/API_reference/en/syslib/pm.html) + +PSM baseline current (µA-level, similar to power-off): +PSM current measurement + +> **Notes:** +> +> - Confirm carrier support for PSM and configure compatible network standards (this test uses catM). +> - [Additional guidance](https://developer.quectel.com/doc/quecpython/Application_guide/en/system/power-consumption.html). \ No newline at end of file diff --git a/docs/Dev_board_guide/en/fcm360w-evb.md b/docs/Dev_board_guide/en/fcm360w-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..179ea887786ecb1dfe58352f57b30da8dbfd7a14 --- /dev/null +++ b/docs/Dev_board_guide/en/fcm360w-evb.md @@ -0,0 +1,185 @@ +# FCM360W EVB Introduction + +## Supported Modules + +Supported module model + +- [FCM360W](https://python.quectel.com/en/modules-cat/fcm360w-series) + +## Feature List + +### Basic Overview + +The QuecPython_FCM360W_EVB development board is a compact and portable "pocket-sized" board designed specifically for QuecPython. It features a Type-C interface, allowing developers to easily use the board with just a USB Type-C data cable. + +### Feature Description + +The main components and interface layout of the EVB are shown in the figure below. + +![img](./media/fcm360w-evb/peripheral-interfaces.png) + +## Document download + +- [FCM360X_EVB_SCH](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/FCM360X-EVB-V1.3-SCH.pdf) + +## EVB Resources + +### EVB Interface + +**J1 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | -------- | --------------------- | +| J1 | - | VCC_3V3 | 3.3 V | +| J1 | 26 | MAIN_RXD | UART0 | +| J1 | 27 | MAIN_TXD | UART0 | +| J1 | - | GND | Ground | +| J1 | 5 | CEN | Module enable control | +| J1 | 13 | IO22 | GPIO22 | +| J1 | 12 | IO21 | GPIO21 | +| J1 | 10 | IO16 | GPIO16 | +| J1 | 9 | IO4 | GPIO4 | +| J1 | 8 | IO14 | GPIO14 | +| J1 | 7 | IO15 | GPIO15 | +| J1 | 6 | IO20 | GPIO20 | + +**J2 Pin Assignment** + +| Pin Header | Pin No. | Name | Feature | +| ---------- | ------- | ----- | -------------------- | +| J2 | 16 | IO25 | GPIO25 | +| J2 | 15 | IO24 | GPIO24 | +| J2 | 14 | IO23 | GPIO23 | +| J2 | 19 | IO17 | GPIO17 | +| J2 | 20 | IO13 | GPIO13 | +| J2 | 21 | IO1 | GPIO1 | +| J2 | 22 | IO0 | GPIO0 | +| J2 | 23 | IO3 | GPIO3 | +| J2 | 29 | IO2 | GPIO2 | +| J2 | 11 | RESET | Module reset control | +| J2 | 17 | BOOT | Module boot control | +| J2 | - | GND | Ground | + +The following figure shows the pin assignment. + +![img](./media/fcm360w-evb/pin-layout.png) + +> **Tips** +> +> For more information about the EVB, please visit [QuecPython Download](https://python.quectel.com/en/resource-download?cid=252) + +### EVB Configuration + +The pins of peripherals are shown in the table below. + +| No. | Name | Model | Supported | Interface Type | Pin | +| ---- | ----------- | ------ | --------- | -------------- | --------- | +| 1 | USB to UART | CH340N | Yes | USB | 26 and 27 | +| 2 | Key | - | Yes | GPIO | 15 and 16 | + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | \ No newline at end of file diff --git a/docs/Dev_board_guide/en/fcm360w-teb.md b/docs/Dev_board_guide/en/fcm360w-teb.md new file mode 100644 index 0000000000000000000000000000000000000000..779d55ecf7b6fae0fad27677a8ac146385de7978 --- /dev/null +++ b/docs/Dev_board_guide/en/fcm360w-teb.md @@ -0,0 +1,176 @@ +# Introduction to FCM360W te-b development board + +## Supported module list + +- [FCM360W](https://python.quectel.com/en/modules-cat/fcm360w-series) + +## Function list + +### Basic overview + +QuecPython_FCM360W_TE-B development board is a Wi-Fi and Bluetooth development board launched by Quectel. Equipped with FCM360W module, it supports Wi-Fi 6 and Bluetooth 5.1 wireless connections, and provides large memory including 512 KB SRAM and 4MB flash memory. + +The development board connection interface is two micro-usb interfaces, and provides a variety of interfaces, including UART, SPI, I2C, ADC, etc. The supporting antennas include external pin antennas, PCB antennas, etc. + +### Functional Description + +The main components and interface layout of the development board are shown in the figure below + +![img](./media/fcm360w-teb/fcm360w-teb.png) + +## Download + +- [FCM360X_EVB_SCH](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/FCM360X-EVB-V1.0-SCH.pdf) + +- [Quectel_FCM360W_Hardware Design Manual](https://python.quectel.com/en/wp-content/uploads/sites/2/2024/11/Quectel_FCM360W_Hardware_Design_V1.0.pdf) + +## Development Board Resources + +### Development board interface + +The main pin layout of the development board is shown in the table below + +| **Pin header** | **Name** | **Pin** | **Function** | +| -------- | -------- | -------- | -------- | +| UART | UART0_RXD | 26 | UART0 receive | +| UART | UART0_TXD | 27 | UART0 send | +| UART | RST | 11 | Module reset | +| UART | UART2_RXD | 19 | UART2 receive | +| UART | UART2_TXD | 20 | UART2 send | +| UART | UART0_RXD_M | 26 | UART0 | +| UART | UART0_TXD_M | 27 | UART0 | +| UART | RST_M | 11 | Module reset | +| UART | UART2_RXD_M | 19 | UART2 | +| UART | UART2_TXD_M | 20 | UART2 | +| SPI | RESERVE | 17 | Reserved | +| SPI | MOSI | 29 | SPI Master Output Slave Input | +| SPI | MISO | 23 | SPI Master Input Slave Output | +| SPI | CLK | 22 | SPI Clock | +| SPI | CS0 | 21 | SPI Chip Select | +| SPI | GPIO25 | 16 | GPIO25 | +| SPI | MOSI_M | 29 | SPI Master Output Slave Input | +| SPI | MISO_M | 23 | SPI Master Input Slave Output | +| SPI | CLK_M | 22 | SPI Clock | +| SPI | CS0_M | 21 | SPI Chip Select | + +- **The pins with _M in the name are directly connected to the module end** + +> **Tips** +> For more information about the development board, please visit + +### Development board configuration + +The peripheral resource pin allocation table is as follows: + +| Serial number | Name | Model | Supported | Interface type | +| ---- | --------- | ------ | -------- | -------- | +| 1 | USB to serial port | CP2102 | Yes | UART | +| 2 | Button | - | Yes | GPIO | +| 2 | ANT | - | Yes | - | + +## Quick Start Guide + +### Hardware Preparation + +- **Step 1: Required Items** + + - Development board + - USB-C cable (A-to-C) + - Windows 10 PC + - Nano-SIM card + - 4G antenna + +- **Step 2: Antenna & SIM Installation** + + - Attach the provided antenna to the MAIN antenna port. + - Insert the SIM card into the Nano-SIM slot. + +- **Step 3: Connect the Board** + + - Power the board via USB-C. + +- **Step 4: Power On** + + - Press and hold PWK until the power indicator light on the mainboard (labeled as POW) lights up. + - If you short-circuited PWK_ON, there's no need to press PWK; the board will power on automatically. + + > **If the PWR indicator is constantly on, the EVB is successfully turned on.** + +### Driver Installation + +1. Download the **QuecPython USB Driver** from [QuecPython Official Drivers](https://developer.quectel.com/en/resource-download?cid=2). +2. Extract and run `setup.exe` or `setup.bat`. +3. Verify installation in **Device Manager** (look for "Quectel USB" ports). Ignore unrelated devices like "Mobile ECM Network Adapter." + +### Tool Installation + +1. **QPYcom**: Download from [QuecPython Tools](https://developer.quectel.com/en/resource-download?cid=2). Extract and use directly. +2. **VSCode Plugin**: Search for "QuecPython" in the Visual Studio Code marketplace.![](./media/readme/VScode_1.png) + +### Firmware Burning + +1. **Firmware Download**: Get the latest QuecPython firmware from QuecPython Firmware Page. + +2. **Burning Steps**: + + - Open QPYcom, select the USB REPL port, and create a new project. + + - Choose the `.bin` firmware file + - Set mode to "Download FW" and click **Download**. + +![download_firmware1](./media/readme/download_firmware1.png) + +![download_firmware2](./media/readme/download_firmware2.png) + +download_firmware3 + +### REPL Debugging + +1. Connect via QPYcom and open the REPL interface. +2. Test with `print("Hello World!")`. + +![hello](./media/readme/hello.png) + +## First Script Development + +### Writing a Script + +Create `helloworld.py`: + +```python +print("Hello World!") +``` + +### File Transfer + +- **Method 1**: Drag-and-drop files via QPYcom’s GUI. + +![download_script1](./media/readme/download_script1.jpg) + +- **Method 2**: Use the "Download Script" feature in QPYcom. + +![download_script1](./media/readme/download_script2.jpg) + +### Running Scripts + +Execute via REPL: + +```python +import example +example.exec("/usr/helloworld.py") +``` + +### Stopping Program Execution + +How to stop a running program. The following methods are provided according to the type of the running script file: + +| Is the program name main.py? | Does the program contain a dead loop? | Does the program use multiple threads? | Stopping Steps | +| :--------------------------: | :-----------------------------------: | :------------------------------------: | :----------------------------------------------------------- | +| ✓ | ✓ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, re-flash the firmware | +| ✓ | ✓ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✓ | ✗ | ✓ | (1) Press Ctrl + A to enter RAW mode
(2) Press Ctrl + D to restart the QuePython virtual machine
(3) Press Ctrl + B to return to the normal interactive mode
(4) If the above methods fail, wait for the program to finish running | +| ✓ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware | +| ✗ | ✓ | ✓ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✓ | ✗ | (1) Press Ctrl + D to restart the QuePython virtual machine
(2) If the above method fails, directly restart the module | +| ✗ | ✗ | ✓ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | +| ✗ | ✗ | ✗ | (1) Press Ctrl + C to interrupt the program execution
(2) If the above method fails, re-flash the firmware or directly restart the module | \ No newline at end of file diff --git a/docs/Dev_board_guide/en/media/bg-eg-core-evb/PH-7_all.png b/docs/Dev_board_guide/en/media/bg-eg-core-evb/PH-7_all.png new file mode 100644 index 0000000000000000000000000000000000000000..66e25cd5d8f03c3d77a439e3ebb939eeea35cd8b Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg-eg-core-evb/PH-7_all.png differ diff --git a/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_figure.png b/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_figure.png new file mode 100644 index 0000000000000000000000000000000000000000..8edc1b068d07027c07f3e0faf6be1cc8f7992789 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_figure.png differ diff --git a/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_pin_define.png b/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_pin_define.png new file mode 100644 index 0000000000000000000000000000000000000000..283199a39a4dbe6de5ac992acbfd064a417107c3 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg-eg-core-evb/bg95_pin_define.png differ diff --git a/docs/Dev_board_guide/en/media/bg-eg-core-evb/hello_world.png b/docs/Dev_board_guide/en/media/bg-eg-core-evb/hello_world.png new file mode 100644 index 0000000000000000000000000000000000000000..3cdaaabd822577470dee509287b891ee748dead9 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg-eg-core-evb/hello_world.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/BG95.png b/docs/Dev_board_guide/en/media/bg95/BG95.png new file mode 100644 index 0000000000000000000000000000000000000000..9d21c0187122f19cd92c7c35fd95cbf7b4b550f3 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/BG95.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/BG95_EVB.png b/docs/Dev_board_guide/en/media/bg95/BG95_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..b909ea568e7bdab28e89685499db7f52ccb11c86 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/BG95_EVB.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/BG95_layout.png b/docs/Dev_board_guide/en/media/bg95/BG95_layout.png new file mode 100644 index 0000000000000000000000000000000000000000..e2f82c6386b3518544dede2ad020b0dbf72609c6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/BG95_layout.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/PowerMonitor_connect.png b/docs/Dev_board_guide/en/media/bg95/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..801b825f80559c3cad916bfd2a67d73e95b25382 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/close_power.png b/docs/Dev_board_guide/en/media/bg95/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..e5d40f3023ec18391ccc2e2c1ef3186755a6c0ad Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/close_power.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/free_power.png b/docs/Dev_board_guide/en/media/bg95/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..c8bd75b51ff004c0c5ee9186c2018c604551d14a Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/free_power.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/open_auto_sleep.png b/docs/Dev_board_guide/en/media/bg95/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..1b035a1db548cc92b6e5f3f5abf6a78c4a2450f8 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/psm_power1.png b/docs/Dev_board_guide/en/media/bg95/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..bca71ae7c9a149dd85b334ac090bbee8fd2005a6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/psm_power1.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/set_psmmode.png b/docs/Dev_board_guide/en/media/bg95/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..8a9ac3834766e5e86ecebf0aaffe6344a519fa64 Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/set_psmmode.png differ diff --git a/docs/Dev_board_guide/en/media/bg95/sleep_power.png b/docs/Dev_board_guide/en/media/bg95/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..13d4a3b578865a472484f5d4fcce54b317fcc96a Binary files /dev/null and b/docs/Dev_board_guide/en/media/bg95/sleep_power.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/200U-1.png b/docs/Dev_board_guide/en/media/ec200x-evb/200U-1.png new file mode 100644 index 0000000000000000000000000000000000000000..3aeb3a53f6ff2e84ae56b99df18f51aabcf6259f Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/200U-1.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/200U-chicun.png b/docs/Dev_board_guide/en/media/ec200x-evb/200U-chicun.png new file mode 100644 index 0000000000000000000000000000000000000000..b7ec5264f373c4808f330b04f2f43c1b98b53c66 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/200U-chicun.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/EC200U.png b/docs/Dev_board_guide/en/media/ec200x-evb/EC200U.png new file mode 100644 index 0000000000000000000000000000000000000000..9b7e2e463c7f3eca571b628ddbcc8a7c264da3a9 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/EC200U.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/EC200X_EVB.png b/docs/Dev_board_guide/en/media/ec200x-evb/EC200X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..af9690fddaa36e581cb3443e5752502ad4278f54 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/EC200X_EVB.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/PowerMonitor_connect.png b/docs/Dev_board_guide/en/media/ec200x-evb/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..a04b96501fd856c54beaaccbdfd85881c07a7e10 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/close_power.png b/docs/Dev_board_guide/en/media/ec200x-evb/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..4408878554f11df2ee96c36b451fddba2ee5f3d0 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/close_power.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/free_power.png b/docs/Dev_board_guide/en/media/ec200x-evb/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..515a8833482189c7bb95f0f2ec7722e5a541d1dd Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/free_power.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/open_auto_sleep.png b/docs/Dev_board_guide/en/media/ec200x-evb/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..1b035a1db548cc92b6e5f3f5abf6a78c4a2450f8 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/psm_power1.png b/docs/Dev_board_guide/en/media/ec200x-evb/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..bca71ae7c9a149dd85b334ac090bbee8fd2005a6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/psm_power1.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/set_psmmode.png b/docs/Dev_board_guide/en/media/ec200x-evb/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..8a9ac3834766e5e86ecebf0aaffe6344a519fa64 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/set_psmmode.png differ diff --git a/docs/Dev_board_guide/en/media/ec200x-evb/sleep_power.png b/docs/Dev_board_guide/en/media/ec200x-evb/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..582f73bbf53e933f4b7dc3e06864d526eda3c557 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec200x-evb/sleep_power.png differ diff --git a/docs/Dev_board_guide/en/media/ec2x-evb/EC2X_EVB.png b/docs/Dev_board_guide/en/media/ec2x-evb/EC2X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..cabe23b2fdfd81dc45d1a047bb38c07720dd5298 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec2x-evb/EC2X_EVB.png differ diff --git a/docs/Dev_board_guide/en/media/ec2x-evb/peripheral-interfaces.png b/docs/Dev_board_guide/en/media/ec2x-evb/peripheral-interfaces.png new file mode 100644 index 0000000000000000000000000000000000000000..20eed04162bac89084a70f09ec5bb636f0f2db3c Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec2x-evb/peripheral-interfaces.png differ diff --git a/docs/Dev_board_guide/en/media/ec2x-evb/pin-layout.png b/docs/Dev_board_guide/en/media/ec2x-evb/pin-layout.png new file mode 100644 index 0000000000000000000000000000000000000000..5da9cc5985966319aab129c9158adb43e8a4ceb6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec2x-evb/pin-layout.png differ diff --git a/docs/Dev_board_guide/en/media/ec600u-235-evb/image7.png b/docs/Dev_board_guide/en/media/ec600u-235-evb/image7.png new file mode 100644 index 0000000000000000000000000000000000000000..fb5d69a18ef0665ec7b0482dff12507d3374acf9 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec600u-235-evb/image7.png differ diff --git a/docs/Dev_board_guide/en/media/ec600u-235-evb/image8.jpg b/docs/Dev_board_guide/en/media/ec600u-235-evb/image8.jpg new file mode 100644 index 0000000000000000000000000000000000000000..53b8d3285266c0b6084d5fc81d58b3dcfc5e633b Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec600u-235-evb/image8.jpg differ diff --git "a/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" new file mode 100644 index 0000000000000000000000000000000000000000..4826d33fd73a0f45f20b9cdd58943ed14cb95310 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" new file mode 100644 index 0000000000000000000000000000000000000000..ef892d5f47c345af78722b8febff76e765343f61 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" new file mode 100644 index 0000000000000000000000000000000000000000..bfa14eb15ba710988ae864ac9def5829b56c1106 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" new file mode 100644 index 0000000000000000000000000000000000000000..5e49122f966e1ec02c1a98e8d386a3dc85c99dda Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" new file mode 100644 index 0000000000000000000000000000000000000000..7be45005ebbdcfa48c72567a460175f532575044 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" differ diff --git a/docs/Dev_board_guide/en/media/ec600x-evb/600Ufunction.png b/docs/Dev_board_guide/en/media/ec600x-evb/600Ufunction.png new file mode 100644 index 0000000000000000000000000000000000000000..edf77b65885348925f2dbe256d04abceb4463c6d Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec600x-evb/600Ufunction.png differ diff --git a/docs/Dev_board_guide/en/media/ec600x-evb/600Uperipheral.png b/docs/Dev_board_guide/en/media/ec600x-evb/600Uperipheral.png new file mode 100644 index 0000000000000000000000000000000000000000..fb1e18bb9017aabc92a68b5df3ff7b7018d71427 Binary files /dev/null and b/docs/Dev_board_guide/en/media/ec600x-evb/600Uperipheral.png differ diff --git "a/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" new file mode 100644 index 0000000000000000000000000000000000000000..4826d33fd73a0f45f20b9cdd58943ed14cb95310 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" new file mode 100644 index 0000000000000000000000000000000000000000..ef892d5f47c345af78722b8febff76e765343f61 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" new file mode 100644 index 0000000000000000000000000000000000000000..bfa14eb15ba710988ae864ac9def5829b56c1106 Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec800x-evb/800M\345\244\226\350\256\276.png" "b/docs/Dev_board_guide/en/media/ec800x-evb/800M\345\244\226\350\256\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..91035d978a7b87e86b9582b8626f27b1e5e0e2dc Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec800x-evb/800M\345\244\226\350\256\276.png" differ diff --git "a/docs/Dev_board_guide/en/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" "b/docs/Dev_board_guide/en/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" new file mode 100644 index 0000000000000000000000000000000000000000..8218d71107172754e9cc4bdf97e1cacc3bc88e2e Binary files /dev/null and "b/docs/Dev_board_guide/en/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/915U_chicun.png b/docs/Dev_board_guide/en/media/eg91x-evb/915U_chicun.png new file mode 100644 index 0000000000000000000000000000000000000000..64bd4948171afb8970c8047094caecb69145bf23 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/915U_chicun.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/EG915U.png b/docs/Dev_board_guide/en/media/eg91x-evb/EG915U.png new file mode 100644 index 0000000000000000000000000000000000000000..51ffcfc8723c577dcc22af5d78c8b2b05f40ddbb Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/EG915U.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/EG915U_1.png b/docs/Dev_board_guide/en/media/eg91x-evb/EG915U_1.png new file mode 100644 index 0000000000000000000000000000000000000000..0a2c6d155ac24403edb96f66af906a0cffe0649e Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/EG915U_1.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/EG91X_EVB.png b/docs/Dev_board_guide/en/media/eg91x-evb/EG91X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..25a7046cfd97de1269569ddc353a0110c037bfd2 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/EG91X_EVB.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/PowerMonitor_connect.png b/docs/Dev_board_guide/en/media/eg91x-evb/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..9dafccbaed1d72e2f8d3ac791a4ab81b736387b8 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/close_power.png b/docs/Dev_board_guide/en/media/eg91x-evb/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..86669d6151df5ef441d808f2f577606958799aa5 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/close_power.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/free_power.png b/docs/Dev_board_guide/en/media/eg91x-evb/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..dbf198a47fcb448ca44e9c811f5866fe4882aaa5 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/free_power.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/open_auto_sleep.png b/docs/Dev_board_guide/en/media/eg91x-evb/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..1b035a1db548cc92b6e5f3f5abf6a78c4a2450f8 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/psm_power1.png b/docs/Dev_board_guide/en/media/eg91x-evb/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..6584a7e52fd64975c6fade50cdc64e4c84e6c690 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/psm_power1.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/set_psmmode.png b/docs/Dev_board_guide/en/media/eg91x-evb/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..8a9ac3834766e5e86ecebf0aaffe6344a519fa64 Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/set_psmmode.png differ diff --git a/docs/Dev_board_guide/en/media/eg91x-evb/sleep_power.png b/docs/Dev_board_guide/en/media/eg91x-evb/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..126cdec31a71c483cae6ef8e9302a35de2b9f01a Binary files /dev/null and b/docs/Dev_board_guide/en/media/eg91x-evb/sleep_power.png differ diff --git a/docs/Dev_board_guide/en/media/fcm360w-evb/peripheral-interfaces.png b/docs/Dev_board_guide/en/media/fcm360w-evb/peripheral-interfaces.png new file mode 100644 index 0000000000000000000000000000000000000000..a1aec0b7d70d7c368e9c526b9024376963320426 Binary files /dev/null and b/docs/Dev_board_guide/en/media/fcm360w-evb/peripheral-interfaces.png differ diff --git a/docs/Dev_board_guide/en/media/fcm360w-evb/pin-layout.png b/docs/Dev_board_guide/en/media/fcm360w-evb/pin-layout.png new file mode 100644 index 0000000000000000000000000000000000000000..fdd2d5d18f54d4c24e0fe35ca69beacd1451795b Binary files /dev/null and b/docs/Dev_board_guide/en/media/fcm360w-evb/pin-layout.png differ diff --git a/docs/Dev_board_guide/en/media/fcm360w-teb/fcm360w-teb.png b/docs/Dev_board_guide/en/media/fcm360w-teb/fcm360w-teb.png new file mode 100644 index 0000000000000000000000000000000000000000..7af23b39de9bedb34b77d3f79411fe12b13264a0 Binary files /dev/null and b/docs/Dev_board_guide/en/media/fcm360w-teb/fcm360w-teb.png differ diff --git a/docs/Dev_board_guide/en/media/readme/VScode_1.png b/docs/Dev_board_guide/en/media/readme/VScode_1.png new file mode 100644 index 0000000000000000000000000000000000000000..52b9d3f613666906af695452b2089fc642b56856 Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/VScode_1.png differ diff --git a/docs/Dev_board_guide/en/media/readme/download_firmware1.png b/docs/Dev_board_guide/en/media/readme/download_firmware1.png new file mode 100644 index 0000000000000000000000000000000000000000..428cc183a1765c14d7f7a2a23f3f268f6a7a3e04 Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/download_firmware1.png differ diff --git a/docs/Dev_board_guide/en/media/readme/download_firmware2.png b/docs/Dev_board_guide/en/media/readme/download_firmware2.png new file mode 100644 index 0000000000000000000000000000000000000000..aa0c6781bedfa187ea80f152bd537b6b559552e4 Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/download_firmware2.png differ diff --git a/docs/Dev_board_guide/en/media/readme/download_firmware3.png b/docs/Dev_board_guide/en/media/readme/download_firmware3.png new file mode 100644 index 0000000000000000000000000000000000000000..eb31f04e30e5c986200abd3ee475e8e7051db7dc Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/download_firmware3.png differ diff --git a/docs/Dev_board_guide/en/media/readme/download_script1.jpg b/docs/Dev_board_guide/en/media/readme/download_script1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c5409acc022549e15b7627ef00cb0c229612cdd6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/download_script1.jpg differ diff --git a/docs/Dev_board_guide/en/media/readme/download_script2.jpg b/docs/Dev_board_guide/en/media/readme/download_script2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c5059d8a03a8916f60b17ca335f41bf757d858ea Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/download_script2.jpg differ diff --git a/docs/Dev_board_guide/en/media/readme/hello.png b/docs/Dev_board_guide/en/media/readme/hello.png new file mode 100644 index 0000000000000000000000000000000000000000..e9388798046538db2a8b8165aa84f4f420bab2f6 Binary files /dev/null and b/docs/Dev_board_guide/en/media/readme/hello.png differ diff --git a/docs/Dev_board_guide/en/sidebar.yaml b/docs/Dev_board_guide/en/sidebar.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42b023e6456e8906117c74f8214f48ca35eec1b4 --- /dev/null +++ b/docs/Dev_board_guide/en/sidebar.yaml @@ -0,0 +1,19 @@ +items: +- label: QuecPython Development Board Introduction + file: ./README.md +- label: EC2X EVB Introduction + file: ec2x-evb.md +- label: BG95 EVB Introduction + file: bg95-evb.md +- label: EC200X EVB Introduction + file: ec200x-evb.md +- label: EG91X EVB Introduction + file: eg91x-evb.md +- label: FCM360W EVB Introduction + file: fcm360w-evb.md +- label: FCM360W TE-B EVB Introduction + file: fcm360w-teb.md +- label: EC600U U-235 EVB Introduction + file: ec600u-235.md +- label: BG95/EG915U/EG912U Core EVB Introduction + file: bg-eg-core-evb.md \ No newline at end of file diff --git a/docs/Dev_board_guide/zh/README.md b/docs/Dev_board_guide/zh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5d91a64d2fcef28ac6a78ef7f5e7d2d697849c3c --- /dev/null +++ b/docs/Dev_board_guide/zh/README.md @@ -0,0 +1,36 @@ +# QuecPython 开发板操作指南 + +QuecPython 开发板是由移远通信(Quectel)推出的嵌入式物联网开发平台,基于 QuecPython 嵌入式操作系统(专为物联网优化的 Python 轻量级解释器)。该开发板集成了蜂窝通信模组(如 4G Cat.1/NB-IoT/5G)、Wi-Fi/蓝牙等无线连接能力,支持通过 Python 语言快速开发物联网终端设备,大幅降低开发门槛。 + +## 核心特点 + +- 低代码开发:支持 Python 3 语法,无需复杂底层开发,适合快速原型设计。 + +- 多网络制式:支持 4G/NB-IoT/5G 等蜂窝网络,部分型号兼容 Wi-Fi/蓝牙。 + +- 丰富硬件接口:提供 GPIO、UART、I2C、SPI、ADC 等常用外设接口。 + +- 多样化板载传感器: :开发板默认搭载多种传感器(光敏、温湿度、三轴等) + +- 云端对接便捷:内置协议栈支持主流物联网云平台(如阿里云、腾讯云、AWS IoT)。 + +- 低功耗设计:支持休眠模式,适合电池供电场景。 + + +## 目录结构 + +- [EC2X 开发板介绍](./ec2x-evb.md) +- [EC600X 开发板介绍](ec600x-evb.md) +- [EC800X 开发板介绍](ec800x-evb.md) +- [EC800X-DP-DTU-Q600R 开发板介绍](ec800x-dp-dtu-q600r.md) +- [EC800X_pico 开发板介绍](ec800x-pico-evb.md) +- [EC600X/EC800X 核心板介绍](ec600x-ec800x-core-evb.md) +- [BG95 开发板介绍](bg95-evb.md) +- [EC200X 开发板介绍](ec200x-evb.md) +- [EG91X 开发板介绍](eg91x-evb.md) +- [FCM360W 开发板介绍](fcm360w-evb.md) +- [FCM360W TE-B开发板介绍](fcm360w-teb.md) +- [EC600U 铀 235 开发板介绍](ec600u-235.md) +- [BG95/EG915U/EG912U 核心板介绍](bg-eg-core-evb.md) +- [EC800G 华 DTU 开发板介绍](ec800g_hua_dtu.md) +- [EC800X Duino 开发板介绍](ec800x-duino-evb.md) \ No newline at end of file diff --git a/docs/Dev_board_guide/zh/bg-eg-core-evb.md b/docs/Dev_board_guide/zh/bg-eg-core-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..65ed1f7e9d6ac2fa7bd9fa86ef3652b1a545af25 --- /dev/null +++ b/docs/Dev_board_guide/zh/bg-eg-core-evb.md @@ -0,0 +1,310 @@ +# QuecPython BG&EG 系列核心板介绍 + +## 快速开始 + +支持的模组列表 + +- [BG95-M1](https://python.quectel.com/modules-cat/bg95-series) +- [BG95-M3](https://python.quectel.com/modules-cat/bg95-series) +- [BG95-M8](https://python.quectel.com/modules-cat/bg95-series) +- [EG915U-LA](https://python.quectel.com/modules-cat/eg915u-series) +- [EG915U-EU](https://python.quectel.com/modules-cat/eg915u-series) +- [EG912U-GL](https://python.quectel.com/modules-cat/eg912u-series) + +## 功能列表 + +### 基本描述 + +QuecPython BG&EG 系列核心板(PH-7(C4-P02))是专门针对 QuecPython 制造的、最小功能的核心开发板。核心板采用 2.54mm 排针方式设计,提供 38PIN 插针,含功能引脚以及使能控制引脚。主要针对客户开发、调试、以及量产设备提供支持与便利。该系列核心板适用 BG95 全系列、EG915UEUAB、EG915ULAAB、EG912UGLAA等EG系列,包含,但不仅仅包含以上模组型号。 + +## 核心板渲染图 + +![](./media/bg-eg-core-evb/PH-7_all.png) + + 开发板的功能主要组件、接口布局见下图。 + +![](./media/bg-eg-core-evb/bg95核心板实物图.png) + +- 充电与 USB:插入 Type-C 接口连接USB时,默认开启充电功能,且无法关闭,不使用充电功能无需理会。 +- GNSS:GNSS功能依模组型号而定,以BG95为例,核心板默认使用有源天线,且已默认开启对有源天线的供电。 +- SD & SIM 卡槽。 +- 38 Pin 插针引脚。 +- 天线接口。 + +## **资料下载** + +- [QuecPython PH-7(C4-P02)核心板产品规格及用户指导](https://python.quectel.com/wp-content/uploads/2024/11/PH-7C4-P02_核心板规格说明及使用指导手册V1.0.0.pdf) +- [QuecPython PH-7(C4-P02)核心板原理图](https://python.quectel.com/wp-content/uploads/2024/11/PH-7C4-P02_原理图.pdf) +- [QuecPython PH-7(C4-P02)核心板丝印](https://python.quectel.com/wp-content/uploads/2024/11/PH-7C4-P02_丝印图.pdf) + +## 开发板资源 + +开发板主要管脚布局见下图 + +![](./media/bg-eg-core-evb/bg95核心板pin定义.png) + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C/Micro USB 接口和电脑 USB 口即可完成供电。 + +> 开发板PWR灯常亮即为正常供电。 + +- **Step4: 开发板开机** + +将开发板上丝印为GND和PWR的排针短接后上电自动开机,开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有BG95和EG91XU两种型号,以EG912U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://images.quectel.com/python/2023/04/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + + + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://python.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中BG95系列选择官网下载固件包解压后mbn结尾的文件,EG91XU系列模组选择解压后的PAC文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +> 其中BG95系列需要打开DM串口后再点击**"Download FW"**,直接点击会提示打开串口 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/bg95-evb.md b/docs/Dev_board_guide/zh/bg95-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..0c88066e7a854bdfcda7d51642c8a84102c9c671 --- /dev/null +++ b/docs/Dev_board_guide/zh/bg95-evb.md @@ -0,0 +1,468 @@ +# BG95 开发板介绍 + +## 支持的模组列表 + +- [BG95-M1](https://python.quectel.com/modules-cat/bg95-series) +- [BG95-M3](https://python.quectel.com/modules-cat/bg95-series) +- [BG95-M8](https://python.quectel.com/modules-cat/bg95-series) + + +## 功能列表 + +### 基本概述 + +QuecPython_BG95_EVB 开发板是一款专门针对QuecPython设计的、小巧便携的“口袋型”开发板。 + +主模组搭载BG95,搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +该开发板兼容树莓派zero,树莓派zero的扩展板可以在BG95开发板上直接使用。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![img](./media/bg95/BG95_layout.png) + +## 资料下载 + +- [QuecPython_BG95_Zero开发板规格说明及使用指导手册](https://python.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero系列开发板产品规格及用户指导.pdf) +- [BG95_Board_原理图](https://python.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero系列开发板原理图.pdf) + + +## 开发板资源 + +### 开发板接口 + +**8Pin排针管脚分配表** + +| **排针** | **编号** | **丝印** | **引脚** | **功能** | +| -------- | -------- | --------- | -------- | -------- | +| JP6 | 1 | PWK_AUTO | 15 | POWERKEY | +| JP6 | 2 | PWK_AUTO | - | GND | +| JP6 | 3 | VDD_EXT | - | 1.8V | +| JP6 | 4 | VDD_EXT | 29 | VDD_EXT | +| JP6 | 5 | MODULE_EN | - | 3.6V | +| JP6 | 6 | MODULE_EN | - | 3.6V | +| JP6 | 7 | GNSS_EN | - | 3.3V | +| JP6 | 8 | GNSS_EN | 51 | GNSS_EN | + +- **1 & 2**:自动开机 +- **3 & 4**:VDD_EXT 连接时可对外供电,测量功耗时需断开 +- **5 & 6**:接通 DCDC 对模组供电 +- **7 & 8**:使能 GNSS 有源供电 + +**40Pin排针管脚分配表** + +| **排针** | **编号** | **名称** | **功能复用** | **功能** | **排针** | **编号** | **名称** | **功能复用** | **功能** | +| -------- | -------- | -------- | ------------------------------------ | --------------------------------------------- | -------- | -------- | -------- | -------------------------------- | ------------------------------------------------- | +| JP7 | 1 | 3V3 | - | 3.3V输出 | JP8 | 2 | 5V | - | 5V输出 | +| JP7 | 3 | SDA1 | I2C1_SDA
GPIO14 | I2C1串行数据
通用输入输出 | JP8 | 4 | 5V | - | 5V输出 | +| JP7 | 5 | SCL1 | I2C1_SCL
GPIO13 | I2C1串行时钟
通用输入输出 | JP8 | 6 | GND | - | 接地 | +| JP7 | 7 | P35 | GPIOX
UART4_TXD | 通用输入输出
UART4发送 | JP8 | 8 | TX2 | UART2_TXD | UART2发送 | +| JP7 | 9 | GND | - | 地 | JP8 | 10 | RX2 | UART2_RXD | UART2接收 | +| JP7 | 11 | P06 | GPIO3
PCM_DIN | 通用输入输出
数字音频输入信号 | JP8 | 12 | P37 | GPIOX
I2C_SDA | 通用输入输出
I2C串行数据 | +| JP7 | 13 | P05 | GPIO2
PCM_SYNC | 通用输入输出
数字音频同步信号 | JP8 | 14 | GND | - | 接地 | +| JP7 | 15 | P04 | GPIO1
PCM_CLK | 通用输入输出
数字音频时钟信号 | JP8 | 16 | P86 | GPIO19 | 通用输入输出 | +| JP7 | 17 | 3V3 | - | 3.3V输出 | JP8 | 18 | P88 | GPIO21 | 通用输入输出 | +| JP7 | 19 | MO2 | SPI2_MOSI
GPIO8
UART0_TXD | SPI2主输出从输入
通用输入输出
UART0发送 | JP8 | 20 | GND | - | 接地 | +| JP7 | 21 | MI2 | SPI2_MISO
GPIO7
UART0_RXD | SPI2主输入从输出
通用输入输出
UART0接收 | JP8 | 22 | P20 | GPIOX | 通用输入输出 | +| JP7 | 23 | CLK2 | SPI2-CLK
GPIO5
I2C0_CLK | SPI2时钟
通用输入输出
I2C0时钟 | JP8 | 24 | CS2 | SPI2_CS
GPIO6
I2C0_SDA | SPI2片选
通用输入输出
I2C0串行数据 | +| JP7 | 25 | GND | - | 接地 | JP8 | 26 | P38 | GPIOX | 通用输入输出 | +| JP7 | 27 | P25 | GPIO9
SPI0_CS | 通用输入输出
SPI0片选 | JP8 | 28 | P26 | GPIO10
SPI0_CLK | 通用输入输出
SPI0时钟 | +| JP7 | 29 | P34 | GPIOX
UART4_RXD | 通用输入输出
UART4接收 | JP8 | 30 | GND | - | 接地 | +| JP7 | 31 | P87 | GPIO20 | 通用输入输出 | JP8 | 32 | PWM | PWM0
GPIO17 | PWM0输出
通用输入输出 | +| JP7 | 33 | P85 | GPIO18
PWM1 | 通用输入输出
PWM1输出 | JP8 | 34 | GND | - | 接地 | +| JP7 | 35 | P28 | GPIO12
SPI0_MISO
UART3_RXD | 通用输入输出
SPI0主输入从输出
UART3接收 | JP8 | 36 | P39 | GPIOX | 通用输入输出 | +| JP7 | 37 | P07 | GPIO4
PCM_DOUT | 通用输入输出
数字音频输出信号 | JP8 | 38 | P27 | GPIO11
SPI0_MOSI
UART3_TXD | 通用输入输出
SPI0主输出从输入
UART3发送 | +| JP7 | 39 | GND | | 接地 | JP8 | 40 | P36 | GPIOX
I2C_SCL | 通用输入输出
I2C串行时钟 | + + +开发板主要管脚布局见下图 + +![img](./media/bg95/BG95_EVB.png) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 丝印 | 备注 | +| ---- | ------------------------- | ------------ | -------- | ----- | -------- | +| 1 | USB_TYPEC接口 | - | 是 | - | - | +| 2 | SIM卡座 | SMN-315-ARP7 | 是 | CARD2 | Nano-SIM | +| 3 | LED指示灯(详见下方说明) | - | 是 | - | - | + +**板载指示灯如下** + +- **SIM_CHK**: 卡槽 SIM 卡存在时,SIM_CHK 指示灯亮起。 +- **NET**:网络指示灯。 +- **PSM**:睡眠指示灯。 +- **PWM**:PWM 功能指示灯。 +- **PWR**:电源指示灯。 + +> 上述指示灯位置参考上文开发板正面图下方丝印(模组所在面为正面) + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口即可完成供电。 + +- **Step4:开发板开机** + +将PWK_AUTO的两个引脚使用跳帽短接之后上电后会自动开机,或者上电后长按PWK开机,建议从上电到按下PWK按键之间的时间间隔不少于 30 ms。 + +进行以上操作后等待主板上电源指示灯亮(主板上丝印为PWR灯,参考上文指示灯) + +**执行以上操作后PWR灯常亮即开机成功** + + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有BG95,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_BG](https://python.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverQ_NDIS_V2.7.14.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://python.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中BG95系列选择官网下载固件包解压后mbn结尾的文件。 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +> 其中BG95系列需要打开DM串口后再点击**"Download FW"**,直接点击会提示打开串口 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
+ + +## 低功耗测试指导 + +BG95模组支持多种工作模式,每种模式的功耗各不相同,常见的工作模式有以下几种: + +**ACTIVE**:模组进行LTE数传、GSM通话或RTOS在运行逻辑时的状态,功耗受到具体业务和网络通信制式的影响,CPU本身功耗和网络射频功率都有所不同,故实际功耗在不同工况下会有较大差异。 + +**IDLE**:此时模组处于空闲状态,硬件正常在电,RTOS保持运行,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。ECX00U系列模组会在IDLE模式下降低时钟频率,进入轻睡眠状态(关闭高速时钟,但CPU不休眠的状态)。 + +**休眠**:休眠模式的前提是模组处于空闲状态且使能autosleep,进入休眠模式后,RTOS暂停运行,模组的时钟频率会变慢,部分外设控制器(UART、SPI等)下电,同时只保留部分中断控制器,达到减小功耗的目的。 + +**PSM**:PSM模式是3GPP协议所规定的一种低功耗模式,这种模式下,模组只会周期性的唤醒并执行业务,其余时间都处于PSM休眠中。PSM休眠时,模组行为和功耗都近似于关机。 + +**关机**:模组完全下电的状态,此时BB芯片和外设控制器完全关闭,但PMIC仍是在电的。一般可由Powerkey或者RTC闹钟唤醒。 + +| 模组型号 | BG95 | +| :------------------- | :------------------ | +| IDLE(LTE FDD@64ms) | 18.9 mA(catm@128ms) | +| SLEEP(LTE FDD@64ms) | 1.89 mA(catm@128ms) | +| SLEEP(CFUN0) | 0.575mA | +| PSM | 5.10 μA | +| 关机 | 14.87 μA | + +### 测试准备 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + 6. **Power Monitor Mini**(功耗仪) + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,功耗仪正极连接MODULE_EN的Vbat,具体位置可以参考[BG95用户指导](https://developer.quectel.com/wp-content/uploads/2024/09/BG95-Pi-Zero%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E4%BA%A7%E5%93%81%E8%A7%84%E6%A0%BC%E5%8F%8A%E7%94%A8%E6%88%B7%E6%8C%87%E5%AF%BC.pdf),功耗仪负极连接模组GND即可。具体连接如图: + + + +> 注意!!! +> +> 测量功耗时需要拔出所有跳线帽,以免测量结果受其他外界因素影响 + +### 测量功耗 + +#### 关机耗流 + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,待测设备硬件连接完毕后,不进行开机,断开USB_VBus(位于开发板背面,USB开关拨至off即可),即可直接测量关机电流。此时,模组不工作,对外的输出引脚也全部拉低或悬空,整体平均耗流保持相对稳定,基本都在uA级。 + +image-20250709190947650 + +#### 空闲耗流 + +完成关机电流测量后,长按powerkey开机,模组开机默认的功耗模式是IDLE(即空闲模式)。此时模组处于空闲状态,硬件正常在电,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。 + +image-20250709193332755 + +#### 休眠耗流 + +模组处于空闲状态时,若autosleep被使能,则模组会进入休眠状态。此时,模组会关闭部分IP核(如外设控制器和中断控制器等)并且降低时钟频率,从而实现功耗的降低。 + +完成空闲耗流测量后,打开USB_VBus,电脑端打开[QPYcom工具](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip),导入`pm`模块,调用`autosleep`方法打开模组的自动休眠,在没有任务执行时,模组会自动进入休眠状态,调用方法后记得断开USB_VBus(USB开关拨至off),否则模组不会进入休眠状态。[API参考](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#%3Ccode%3Epm.autosleep%3C/code%3E)。关于休眠耗流的详细介绍[参考](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 + +image-20250709194047484 + +进入休眠模式后,模组应有的耗流波形会有周期稳定的凸起,如下图: + +image-20250709194047484 + +#### PSM耗流 + +启用PSM时,需要先向基站发送请求(通过ATTACH或TA_UPDATER携带定时器信息)。基站若支持进入PSM,则会在对应的REQUEST中下发定时器信息,需要注意的是,实际PSM的参数会使用基站下发的值,并不一定和我们请求的值相同。模组会以基站下发的值来配置定时器时间,当模组进入IDLE且ACT定时器超时,模组会关闭CPU和一切射频,此时相当于部分关机,只是保留了比关机更多的唤醒源,一般包括ACT、TAU定时器和PSM_INT。功耗一般下降到微安级别。 + +打开USB_VBus,电脑端打开[QPYcom工具](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip),启用PSM,开启后记得断开USB_VBus(USB开关拨至off)。关于PSM详细介绍[参考](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html#PSM-%E6%A8%A1%E5%BC%8F)。启用PSM模式的[API参考](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#%3Ccode%3Epm.set_psm_time%3C/code%3E)。 + +image-20250709194047484 + +等待ACT定时器超时后,我们可查看PSM休眠下的底电流。如图可见,PSM的底电流远低于普通的autosleep模式,和关机耗流的大小、特征较为相似。 + +image-20250709194047484 + +> 注意: +> +> 进入PSM模式需要确认运营商是否支持,还需配置支持的网络制式 ! ! ! +> +> 更多耗流测试指导请[参考这里](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 diff --git a/docs/Dev_board_guide/zh/config.json b/docs/Dev_board_guide/zh/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e6ee1f6fb9fb2e9a6dc7f583f640b7e0b495f8be --- /dev/null +++ b/docs/Dev_board_guide/zh/config.json @@ -0,0 +1,4 @@ +{ + "import": "config_zh", + "name": "快速入门" +} \ No newline at end of file diff --git a/docs/Dev_board_guide/zh/ec200x-evb.md b/docs/Dev_board_guide/zh/ec200x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..d64fa412f7f5e4229240b36e65d93bb098ec7534 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec200x-evb.md @@ -0,0 +1,505 @@ +# EC200U/A C4-P01 + +## 支持的模块列表 + +- [EC200U-CN](https://python.quectel.com/modules-cat/ec200u-series) +- [EC200U-EU](https://python.quectel.com/modules-cat/ec200u-series) +- [EC200A-CN](https://python.quectel.com/modules-cat/ec200a-series) +- [EC200A-AU](https://python.quectel.com/modules-cat/ec200a-series) +- [EC200A-EU](https://python.quectel.com/modules-cat/ec200a-series) + + +## 功能列表 + +### 基本概述 + +QuecPython_EC200U/A C4-P01开发板是一款专门针对QuecPython设计的、小巧便携的开发板。 + +主模块搭载EC200U/A系列LTE Cat 1/LTE Cat 4无线通信模块。 + +该开发板自身板载USB Type-C接口,方便开发,开发者仅需一条USB Type-C数据线即可轻松玩转开发板。 + +并且该开发板兼容树莓派zero的扩展板,树莓派zero的扩展板可以在开发板上直接使用。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![img](./media/ec200x-evb/200U-1.png) + +开发板尺寸图 + +![img](./media/ec200x-evb/200U-chicun.png) + +### 资料下载 + +- [QuecPython_EC20X_EVB_SCH](https://developer.quectel.com/wp-content/uploads/2024/09/EC200UA_C4-P01%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E5%8E%9F%E7%90%86%E5%9B%BE.pdf) +- [EC20X_EVB_丝印](https://developer.quectel.com/wp-content/uploads/2024/09/EC200UA_C4-P01%E7%B3%BB%E5%88%97%E5%BC%80%E5%8F%91%E6%9D%BF%E4%B8%9D%E5%8D%B0.pdf) + + +## 开发板资源 + +### 开发板接口 + +该开发板提供40-Pin兼容树莓派的引脚,以及10-Pin功能使能引脚,开发板功能描述如下: + +**10-Pin排针引脚分配表** + +| **排针** | **编号** | **丝印** | **功能** | +| -------- | -------- | --------- | -------- | +| 10-Pin | 1 | PWK_AUTO | POWERKEY | +| 10-Pin | 2 | PWK_AUTO | GND | +| 10-Pin | 3 | VDD_EXT | 1.8 V | +| 10-Pin | 4 | VDD_EXT | VDD_EXT | +| 10-Pin | 5 | MODULE_EN | 3.8 V | +| 10-Pin | 6 | MODULE_EN | 3.8 V | +| 10-Pin | 7 | SD_EN | SD_EN | +| 10-Pin | 8 | SD_EN | 3.3 V | +| 10-Pin | 9 | GNSS_EN | 3.3 V | +| 10-Pin | 10 | GNSS_EN | GNSS_EN | + +- **1 & 2**:自动开机 +- **3 & 4**:VDD_EXT连接时可对外供电,测量功耗时需断开 +- **5 & 6**:接通DCDC对模块供电 +- **7 & 8**:使能SD供电 +- **9 & 10**:使能GNSS有源供电 + +> 测量功耗时注意关闭USB供电开关,开发板背面USB_ON/OFF的拨杆开关。 + +**40-Pin排针单号引脚分配表** + +| **排针** | **编号** | **名称** | **功能复用** | **功能** | +| -------- | -------- | -------- | ------------------ | ----------------------------------------------- | +| 40-Pin | 1 | 3V3 | - | 3.3 V输出 | +| 40-Pin | 3 | SDA | I2C0_SDA/GPIO35 | I2C0串行数据/通用输入输出 | +| 40-Pin | 5 | SCL | I2C0_SCL | I2C0串行时钟 | +| 40-Pin | 7 | P06 | GPIO46/A_PWM2 | 通用输入输出/PWM2输出(模块为EC200A时) | +| 40-Pin | 9 | GND | - | 接地 | +| 40-Pin | 11 | P64 | GPIO19 | 通用输入输出 | +| 40-Pin | 13 | P136 | GPIO7 | 通用输入输出 | +| 40-Pin | 15 | P03 | GPIO9 | 通用输入输出 | +| 40-Pin | 17 | 3V3 | - | 3.3 V输出 | +| 40-Pin | 19 | MO1 | SPI1_MOSI/GPIO3 | SPI1主输出从输入/通用输入输出 | +| 40-Pin | 21 | MI1 | SPI1_MISO/GPIO4 | SPI1主输入从输出/通用输入输出 | +| 40-Pin | 23 | CLK1 | SPI1_CLK/GPIO1 | SPI1时钟/通用输入输出 | +| 40-Pin | 25 | GND | - | 接地 | +| 40-Pin | 27 | P63 | GPIO44/A_UART1_TXD | 通用输入输出/UART1发送(模块为EC200A时) | +| 40-Pin | 29 | P01 | GPIO28/A_PWM0 | 通用输入输出/PWM0输出(模块为EC200A时) | +| 40-Pin | 31 | P02 | GPIO29 | 通用输入输出 | +| 40-Pin | 33 | P04 | GPIO30/A_PWM1 | 通用输入输出/PWM1输出(模块为EC200A时) | +| 40-Pin | 35 | P39 | GPIO13/A_SPI0_MISO | 通用输入输出/SPI0主输入从输出(模块为EC200A时) | +| 40-Pin | 37 | P134 | GPIO37 | 通用输入输出 | +| 40-Pin | 39 | GND | - | 接地 | + +**40-Pin排针双号引脚分配表** + +| **排针** | **编号** | **名称** | **功能复用** | **功能** | +| -------- | -------- | -------- | ------------------ | ----------------------------------------------- | +| 40-Pin | 2 | 5V | - | 5 V输出 | +| 40-Pin | 4 | 5V | - | 5 V输出 | +| 40-Pin | 6 | GND | - | 接地 | +| 40-Pin | 8 | TXD | UART2_TXD | UART2发送 | +| 40-Pin | 10 | RXD | UART2_RXD | UART2接收 | +| 40-Pin | 12 | P37 | GPIO11/A_SPI0_CS | 通用输入输出/SPI0片选(模块为EC200A时) | +| 40-Pin | 14 | GND | - | 接地 | +| 40-Pin | 16 | P133 | GPIO8 | 通用输入输出 | +| 40-Pin | 18 | P65 | GPIO18 | 通用输入输出 | +| 40-Pin | 20 | GND | - | 接地 | +| 40-Pin | 22 | P127 | GPIO22 | 通用输入输出 | +| 40-Pin | 24 | CS1 | SPI1_CS/GPIO2 | SPI1片选/通用输入输出 | +| 40-Pin | 26 | P139 | GPIO20 | 通用输入输出 | +| 40-Pin | 28 | P66 | GPIO45/A_UART1_RXD | 通用输入输出/UART1接收(模块为EC200A时) | +| 40-Pin | 30 | GND | - | 接地 | +| 40-Pin | 32 | P135 | GPIO6/U_PWM0 | 通用输入输出/PWM0输出(模块为EC200U时) | +| 40-Pin | 34 | GND | - | 接地 | +| 40-Pin | 36 | P62 | GPIO43 | 通用输入输出 | +| 40-Pin | 38 | P38 | GPIO12/A_SPI0_MOSI | 通用输入输出/SPI0主输出从输入(模块为EC200A时) | +| 40-Pin | 40 | P40 | GPIO10/A_SPI0_CLK | 通用输入输出/SPI0时钟(模块为EC200A时) | + +开发板主要引脚布局见下图 + +![img](./media/ec200x-evb/EC200X_EVB.png) + +> **小提示** +> +> 图中以A/U开头的引脚复用功能为EC200A/U系列模块的功能差异项,即模块为EC200U时,U开头的引脚功能才会生效;模块为EC200A时,A开头的引脚功能才会生效。 +> +> 开发板的更多资料,请访问 。 + +### 开发板配置 + +开发板外设接口分配表明细如下: + +| 序号 | 名称 | 型号 | 丝印 | 备注 | +| ---- | -------------- | ------------ | --------------- | ------------------------------------------------------------ | +| 1 | USB Type-C接口 | - | - | - | +| 2 | SIM卡座1 | SMN-315-ARP7 | SIM1 | Nano-SIM | +| 3 | SIM卡座2 | MUP-C7809-1 | SIM2 | - | +| 4 | SD卡槽 | TF-101A-P3 | SD | 使用SD卡前,首先需要在10-Pin功能排针中使能SD,对 SD供电。 | +| 5 | USB 供电开关 | - | USB_ON/OFF | 开关处于常闭状态时,Type-C对模块和开发板供电,USB可正常连接;USB开关处于常开状态时,Type-C仅对开发板供电,此时模块处于未供电状态。 | +| 6 | MIPI接口 | - | MIPI_DSI | 主模块为 EC200U-XX 时,支持MIPI屏幕,且全兼容树莓派外设。 | +| 7 | 摄像头接口 | - | - | 开发板支持定制的SPI摄像头,最大像素支持30W像素。 | +| 8 | 矩阵键盘接口 | - | KO&KI | 预留矩阵键盘引脚,用户可进行自定义焊接或者连接,默认不带板载键盘按键。 | +| 9 | MIC&SPK接口 | AW8733A | +MIC-/-SPK+ | - | +| 10 | 40-Pin排针 | - | - | 板载40-Pin排针,具体参见上文图表。 | +| 11 | 10-Pin排针 | - | - | 板载10-Pin排针,具体参见上文图表。 | +| 12 | ADC接口 | - | ADC0_IN/ADC1_IN | ADC测量接口 | +| 13 | PWK按键 | - | PWK | 开机按键 | +| 14 | RST按键 | - | RST | 重启按键 | +| 15 | BOOT按键 | - | BOOT | 固件烧录按键 | +| 16 | 天线接口 | - | LTE
DIV/WIFI/BT
GNSS | LTE天线座
DIV/Wi-Fi/蓝牙天线座
GNSS天线座 | + +**开发板载有5颗功能性指示灯,分别如下** + +- **P01**:模块Pin 1,默认为EC200A-XX PWM0。 +- **P05**:模块Pin 5,为NET_MODE指示灯。 +- **SCK1**:SIM1检测指示灯,SIM1卡插入时亮起。 +- **SCK2**:SIM2检测指示灯,SIM2卡插入时亮起。默认连接Pin 128,EC200A-XX无SIM2,可忽略。 +- **PWR**:电源指示灯。 + +> 上述指示灯位置参考上文开发板正面图下方丝印(模块所在面为正面)。 + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C/Micro USB 接口和电脑 USB 口即可完成供电。 + +> 开发板PWR灯常亮即为正常供电。 + +- **Step4: 开发板开机** + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。如果需上电自动开机且不需要关机功能,则可以把10-Pin排针中PWK_AUTO丝印对应的两个引脚短接。 + +如果上一步短接PWK_ON则无需长按PWK自动开机,开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC200U和EC200A两种型号,以EC200U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://images.quectel.com/python/2023/04/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://python.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC200A系列选择解压后的文件夹内blf文件结尾的文件,EC200U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
+ + + +## 低功耗测试指导 + +EC200X模组支持多种工作模式,每种模式的功耗各不相同,常见的工作模式有以下几种: + +**ACTIVE**:模组进行LTE数传、GSM通话或RTOS在运行逻辑时的状态,功耗受到具体业务和网络通信制式的影响,CPU本身功耗和网络射频功率都有所不同,故实际功耗在不同工况下会有较大差异。 + +**IDLE**:此时模组处于空闲状态,硬件正常在电,RTOS保持运行,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。ECX00U系列模组会在IDLE模式下降低时钟频率,进入轻睡眠状态(关闭高速时钟,但CPU不休眠的状态)。 + +**休眠**:休眠模式的前提是模组处于空闲状态且使能autosleep,进入休眠模式后,RTOS暂停运行,模组的时钟频率会变慢,部分外设控制器(UART、SPI等)下电,同时只保留部分中断控制器,达到减小功耗的目的。 + +**PSM**:PSM模式是3GPP协议所规定的一种低功耗模式,这种模式下,模组只会周期性的唤醒并执行业务,其余时间都处于PSM休眠中。PSM休眠时,模组行为和功耗都近似于关机。 + +**关机**:模组完全下电的状态,此时BB芯片和外设控制器完全关闭,但PMIC仍是在电的。一般可由Powerkey或者RTC闹钟唤醒。 + +| 模组型号 | EC200U | +| :------------------- | :------- | +| IDLE(LTE FDD@64ms) | 12.34 mA | +| SLEEP (LTE FDD@64ms) | 2.05 mA | +| SLEEP (CFUN0) | 1.29 mA | +| 关机 | 40 μA | + +### 测试准备 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + 6. **Power Monitor Mini**(功耗仪) + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 LTE 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,功耗仪正极连接MODULE_EN的Vbat,功耗仪负极连接模组GND即可。具体连接如图: + + + +> 注意!!! +> +> 测量功耗时需要拔出所有跳线帽,以免测量结果受其他外界因素影响 + +### 测量功耗 + +#### 关机耗流 + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,待测设备硬件连接完毕后,断开USB_VBus,不进行开机,即可直接测量关机电流。此时,模组不工作,对外的输出引脚也全部拉低或悬空,整体平均耗流保持相对稳定,基本都在uA级。 + +image-20250709190947650 + +#### 空闲耗流 + +完成关机电流测量后,长按powerkey开机,模组开机默认的功耗模式是IDLE(即空闲模式)。此时模组处于空闲状态,硬件正常在电,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。 + +image-20250709193332755 + +#### 休眠耗流 + +模组处于空闲状态时,若autosleep被使能,则模组会进入休眠状态。此时,模组会关闭部分IP核(如外设控制器和中断控制器等)并且降低时钟频率,从而实现功耗的降低。 + +完成空闲耗流测量后,打开USB_VBus,电脑端打开[QPYcom工具](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip),导入`pm`模块,调用`autosleep`方法打开模组的自动休眠,在没有任务执行时,模组会自动进入休眠状态,调用方法后记得断开USB_VBus(USB开关拨至off),否则模组不会进入休眠状态。[API参考](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#%3Ccode%3Epm.autosleep%3C/code%3E)。关于休眠耗流的详细介绍[参考](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 + +image-20250709194047484 + +进入休眠模式后,模组应有的耗流波形会有周期稳定的凸起,如下图: + +image-20250709194047484 + +> 注意: +> +> 更多耗流测试指导请[参考这里](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 diff --git a/docs/Dev_board_guide/zh/ec2x-evb.md b/docs/Dev_board_guide/zh/ec2x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..7061a456df3156e39416f9fe69d03483aa231cc6 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec2x-evb.md @@ -0,0 +1,374 @@ +# EC2X 开发板介绍 + +## 支持的模组列表 + +- [EC200A-CN](https://python.quectel.com/modules-cat/ec200a-series) +- [EC200U-CN](https://python.quectel.com/modules-cat/ec200u-series) +- [EC200A-EU](https://python.quectel.com/modules-cat/ec200a-series) +- [EC200A-AU](https://python.quectel.com/modules-cat/ec200a-series) + +## 功能列表 + +### 基本概述 + +QuecPython_EC2X_EVB_Vx.x 开发板是专门针对QuecPython制造,是一款小巧便携的“口袋型”开发板。体型虽小,但是功能丰富,拥有温湿度传感器、加速度传感器、SIM卡座、SD卡座、LCD接口、光敏电阻、MIC等元件。 + +开发板搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +开发板搭载EC200U模组,详细资料参考 [EC200U-EU](https://python.quectel.com/modules-cat/ec200u-series) + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![](./media/ec2x-evb/peripheral-interfaces.png) + +## 资料下载 + +- [EC2X_EVB_SCH2](https://python.quectel.com/wp-content/uploads/2024/09/EC2X_EVB_SCH2-2.pdf) + +## 开发板资源 + +### 开发板接口 + +**J5排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ------- | ---- | ----- | +| J5 | 1 | VCC_5V | - | 5V | +| J5 | 2 | VCC_5V | - | 5V | +| J5 | 3 | GND | - | 接地 | +| J5 | 4 | IO3 | 24 | GPIO3 | +| J5 | 5 | IO4 | 25 | GPIO4 | +| J5 | 6 | IO2 | 26 | GPIO2 | +| J5 | 7 | IO1 | 27 | GPIO1 | +| J5 | 8 | ADC1_IN | 44 | ADC1 | +| J5 | 9 | VDD_EXT | - | 1.8V | + +**J6排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ------- | ---- | -------- | +| J6 | 1 | V3.3 | - | 3.3V | +| J6 | 2 | GND | - | 接地 | +| J6 | 3 | GND | - | 接地 | +| J6 | 4 | IO9 | 3 | GPIO9 | +| J6 | 5 | SD_EN | 119 | SD卡使能 | +| J6 | 6 | SDA | 142 | I2C1 | +| J6 | 7 | SCL | 141 | I2C1 | +| J6 | 8 | ADC2_IN | 43 | ADC2 | +| J6 | 9 | ADC0_IN | 45 | ADC0 | + +**J7排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ---- | ------ | +| J7 | 1 | GND | - | 接地 | +| J7 | 2 | RX1 | 138 | UART1 | +| J7 | 3 | TX1 | 137 | UART1 | +| J7 | 4 | TX2 | 67 | UART2 | +| J7 | 5 | RX2 | 68 | UART2 | +| J7 | 6 | IO18 | 65 | GPIO18 | +| J7 | 7 | IO19 | 64 | GPIO19 | +| J7 | 8 | D_RX | 11 | UART | +| J7 | 9 | D_TX | 12 | UART | + +**J10排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ---- | ------ | +| J10 | 1 | IO7 | 136 | GPIO7 | +| J10 | 2 | IO6 | 135 | GPIO6 | +| J10 | 3 | IO22 | 127 | GPIO22 | +| J10 | 4 | IO10 | 40 | GPIO10 | +| J10 | 5 | IO13 | 39 | GPIO13 | +| J10 | 6 | IO12 | 38 | GPIO12 | +| J10 | 7 | IO11 | 37 | GPIO11 | +| J10 | 8 | GND | - | 接地 | +| J10 | 9 | V3.8 | - | 3.8V | + +开发板主要管脚布局见下图 + +![](./media/ec2x-evb/EC2X_EVB.png) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +开发板配备了多种传感器,以及其他外设。外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | 引脚 | +| ---- | ---------------------------- | ------------- | -------- | -------- | ------- | +| 1 | 温湿度传感器 | AHT20 | 是 | I2C | 41,42 | +| 2 | 光敏电阻 | GT36528 | 是 | ADC | 45 | +| 3 | G-Sensor | QMA7981 | 是 | I2C | 41,42 | +| 4 | 麦克风 | GMI6050P-66DB | 是 | SPK | 75,77 | +| 5 | 功放芯片 | NS4160 | 是 | SPK | 73,74 | +| 6 | LCD 显示屏(需选择含屏套餐) | ST7789 | 是 | SPI | 122~125 | +| 7 | SD_CARD | XKTF-NO2-N | 是 | SPI | 28~34 | + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C/Micro USB 接口和电脑 USB 口即可完成供电。 + +> 开发板PWR灯常亮即为正常供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处,开发板上的PWK_ON跳帽短接AUTO(上电自动开机) + +按住PWK直至主板上电源指示灯亮(主板上丝印为PWR的灯),如果上一步短接PWK_ON则无需长按PWK自动开机,开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC200U和EC200A两种型号,以EC200U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://images.quectel.com/python/2023/04/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://python.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC200A系列选择解压后的文件夹内blf文件结尾的文件,EC200U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec600u-235.md b/docs/Dev_board_guide/zh/ec600u-235.md new file mode 100644 index 0000000000000000000000000000000000000000..657edffef62f1b209c8116b359a6b5ea36afdea4 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec600u-235.md @@ -0,0 +1,346 @@ +# QuecPython U-235 开发板介绍 + +## 支持的模组列表 + +- [EC600U-CN](https://python.quectel.com/modules-cat/ec600u-series) + +## 功能列表 + +### 基本概述 + +QuecPython 铀-235 大屏开发板,集成了现有模组几乎所有功能 ,包含丰富的外设,包括外扩的Flash、WiFi、屏幕等等。 + +开发板当前以EC600U作为主控模组,搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +### 功能说明 + +![](./media/ec600u-235-evb/image8.jpg) + +1. **SD卡**:上拉 EC600U 模块的引脚 53,即对应 QuecPython GPIO 27。 +2. **Wi-Fi** 模块:将上图中标识为“3”的开关拨到“**GND**”一侧,通过 Wi-Fi模块串口(上图中标识为“2”)烧录 Wi-Fi模块固件。烧录完成后,将标识为“3”开关拨至“**NONE**”侧并重启 Wi-Fi模块。若想使用 Wi-Fi 模块与 EC600U 模块进行通信,拉高 EC600U模块的引脚 3,将其从串口 UART 1 切换为 Wi-Fi 串口,并拉高引脚 121,为Wi-Fi 模块供电,之后,Wi-Fi 模块即可与 EC600U 模块进行通信。 +3. **Zigbee**:当 EC600U 模块的引脚 PIN3 为低电平时,图中标识“1”指示的串口功能为 UART1,当 PIN3 为高电平时,“1”指示的串口功能变为 Zigbee。 +4. **MIC & SPK**:MIC & SPK 拥有左右两个连接器接口,均可供使用。 +5. **外部供电**:将开关拨至“5V”一侧,通过 5V外部供电接口连接外部电源,最大输入电压为 6.5 V。 +6. **蜂鸣器**:拉高或拉低模块引脚 119 控制蜂鸣器发声。 +7. **RS-485**:RS-485 接口默认连接物理串口,并使用 UART 2 进行通信。 +8. **MIPI**:上拉 EC600U 模块的引脚 118,即对应 QuecPython GPIO 8。 +9. **音频**:使能 PA,上拉 EC600U 模块的引脚 4,即对应 QuecPython GPIO 11。 +10. **屏幕**: ST7701 IPS 5寸 MIPI接口 480x854分辨率 电容触摸屏,触控芯片GT911 + +> 备注 : QuecPython 方案下,GPIO 和 EC600U 系列模块引脚对应关系详情请参考[**控制I/O引脚**](https://python.quectel.com/doc/API_reference/zh/peripherals/machine.Pin.html) + +## 资料下载 + +- [EC600U_U-235_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/600U_铀235-SCH.pdf) +- [EC600U_U-235_EVB_丝印](https://python.quectel.com/wp-content/uploads/2024/09/600U_铀235_丝印.pdf) +- [Quectel_QuecPython_铀235_EVB_用户指导](https://python.quectel.com/wp-content/uploads/2024/09/Quectel_QuecPython_铀235_EVB_用户指导_V1.0.pdf) + +## 开发板资源 + +铀 235 EVB 丰富的板载资源如下图所示: +![](./media/ec600u-235-evb/image7.png) + +以下从上图中的“EC600U模块”指示框为开端,顺时针介绍指示框中提到的开发板资源。 + +- EC600U 模块:为中央处理器;Flash:8 MB;RAM:16 MB。 +- MIPI 屏 I/O 接口 +- MIPI LED 背光模块 +- 扬声器 R:右声道扬声器 +- MIC:麦克风接口 +- 扬声器 L:左声道扬声器 +- 触摸屏 I/O 接口 +- 温湿度传感器 +- 5V 电源供电 +- 电源供电选择开关:用于选择 USB 供电或外接电源供电的开关 +- USB:用于程序代码下载和脚本调试的 USB 接口 +- SIM 卡槽 +- 普通按键:3 个通用按键(无默认功能) +- 蜂鸣器 +- PWR 按键:用于开启或关闭 EC600U 模块的开关键 +- RST 按键:用于模块复位的按键 +- BOOT 按键:用于强制烧录固件的按键 +- 摄像头接口:支持拍照和扫描功能 +- Flash/MIPI_TE 选择开关:因为 Flash 的 SIO3 与 MIPI_TE引脚冲突,所以若需使用外部 Flash,则必须将开关切换到 SIO3 一侧。大部分的 MIPI 屏幕不使用 MIPI_TE,故该开关通常被切换至SIO3 一侧。 +- 扩展 SPI Flash:该 FLASH W25Q32JWUUIQ 的内存为 4 MB。 +- LTE 天线座 +- Wi-Fi 模块 +- WRST 按键:用于复位 Wi-Fi 模块的按键 +- 普通按键 KEY1(无默认功能) +- 普通按键 KEY2(无默认功能) +- Wi-Fi 模块串口 +- 触摸屏电平选择开关(1.8 V 或 3.3 V) +- 触摸屏接口 +- SD 卡槽 +- MIPI 屏接口 +- RS-485 接口,芯片采用 SP3485EIM/TR + +> 开发板同时开放 MIPI 接口和触摸屏接口以提高复用性。 +> +> 开发板的更多资料,请访问 [https://python.quectel.com/resource-download](https://python.quectel.com/resource-download?cid=23) + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC600U,以EC600U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://images.quectel.com/python/2023/04/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://python.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC600U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
+ + + + diff --git a/docs/Dev_board_guide/zh/ec600x-ec800x-core-evb.md b/docs/Dev_board_guide/zh/ec600x-ec800x-core-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..cfb59981b107503cd76c07e9c04951585e030774 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec600x-ec800x-core-evb.md @@ -0,0 +1,308 @@ +# EC600X/EC800X 核心板介绍 + +## 快速开始 + +支持的模组列表 + +- [EC600N-CNLA](https://python.quectel.com/modules-cat/ec600n-series) +- [EC600M-CNLA](https://python.quectel.com/modules-cat/ec600m-series) +- [EC800M-CNGA](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800M-CNGC](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800M-CNLC](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800M-CNLF](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800E-CNLE](https://python.quectel.com/modules-cat/ec800e-series) + +## 功能列表 + +### 基本描述 + +QuecPython_EC600X/EC800X 核心板是专门针对 QuecPython 制造的、最小功能的核心开发板。用户可根据自己需求选择对应的型号,有单排针纯数传版本、双排针纯数传版本、单排针定位数传版本和双排针定位数传版本等。 + +## 功能说明 + +开发板的功能主要组件、接口布局见下图 + +![](./media/ec600x-ec800x-core-evb/核心板-产品功能.png) + +## **资料下载** + +- [EC600N核心板“锵”规格说明及使用指导手册](https://python.quectel.com/wp-content/uploads/2024/09/EC600N核心板锵规格说明及使用指导手册_V1.4.pdf) +- [EC600N核心板“軒”规格书以及操作说明](https://python.quectel.com/wp-content/uploads/2024/09/EC600N核心板軒规格书以及操作说明V1.2.pdf) +- [EC800M双排针核心板_“熵”(GNSS)规格说明及使用指导手册](https://python.quectel.com/wp-content/uploads/2024/09/EC800M双排针核心板_熵GNSS规格说明及使用指导手册_V1.41.pdf) +- [EC800X核心板“宇”规格书以及操作说明](https://python.quectel.com/wp-content/uploads/2024/09/EC800X核心板宇规格书以及操作说明V1.2.pdf) +- [EC600X_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/EC600X_EVB_V3.2-SCH.pdf) + +## 开发板资源 + +开发板主要管脚布局见下图 + +![](./media/ec600x-ec800x-core-evb/核心板-锵.png) + +![](./media/ec600x-ec800x-core-evb/核心板-轩.png) + +![](./media/ec600x-ec800x-core-evb/核心板-熵.png) + +![](./media/ec600x-ec800x-core-evb/核心板-宇.png) + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800M,以EC800M为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB_Driver_Win10_ASR](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverA_Customer_V1.1.13.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC600U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec600x-evb.md b/docs/Dev_board_guide/zh/ec600x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..6f880f500f5b9062f494a78acb0ae2ad755c379c --- /dev/null +++ b/docs/Dev_board_guide/zh/ec600x-evb.md @@ -0,0 +1,362 @@ +# EC600X 开发板介绍 + +## 快速开始 + +支持的模组列表 + +- [EC600N-CN](https://python.quectel.com/modules-cat/ec600n-series) + +- [EC600U-CN](https://python.quectel.com/modules-cat/ec600u-series) + +- [EC600M-CN](https://python.quectel.com/modules-cat/ec600m-series) + +## 功能列表 + +### 基本概述 + +QuecPython_EC600X_EVB 开发板是专门针对 QuecPython 制造的、小巧便携的“口袋型”开发板。其体型虽小,但是功能丰富,拥有温湿度传感器、SIM卡座、LCD接口、光敏电阻、MIC等元件。 + +开发板当前以EC600U作为主控模组,搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![](./media/ec600x-evb/600Ufunction.png) + +## 资料下载 + +- [EC600X_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/EC600X_EVB_V3.2-SCH.pdf) + +## 开发板资源 + +### 开发板接口 + +**J5排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ---- | ----------------- | +| J5 | 1 | GND | - | 接地 | +| J5 | 2 | GND | - | 接地 | +| J5 | 3 | P60 | 60 | GPIO4,SPI1 MISO | +| J5 | 4 | P59 | 59 | GPIO30,SPI1 MOSI | +| J5 | 5 | P58 | 58 | GPIO2,SPI1 CS | +| J5 | 6 | TX0 | 71 | UART0 | +| J5 | 7 | RX0 | 72 | UART0 | +| J5 | 8 | TX2 | 32 | UART2 | +| J5 | 9 | RX2 | 31 | UART2 | +| J5 | 10 | SDA | 56 | GPIO16,I2C1 | +| J5 | 11 | SCL | 57 | GPIO15,I2C1 | +| J5 | 12 | CLK | 1 | GPIO10,SPI0 CLK | +| J5 | 13 | MISO | 2 | GPIO13,SPI0 MISO | +| J5 | 14 | MOSI | 3 | GPIO12,SPI0 MOSI | +| J5 | 15 | CS | 4 | GPIO11,SPI0 CS | +| J5 | 16 | RX1 | 123 | GPIO7,UART1 | +| J5 | 17 | TX1 | 124 | GPIO19,UART1 | +| J5 | 18 | GND | - | 接地 | + +**J6排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ----- | ------ | --------------- | +| J6 | 1 | 5V | - | 5V | +| J6 | 2 | 3V3 | - | 3.3V | +| J6 | 3 | 1V8 | 76 | 1.8V | +| J6 | 4 | ADC0 | 19 | ADC0 | +| J6 | 5 | ADC1 | 20 | ADC1 | +| J6 | 6 | ADC2 | 113 | ADC2 | +| J6 | 7 | ADC3 | 114 | ADC3 | +| J6 | 8 | PWM3 | 69 | GPIO5 | +| J6 | 9 | PWM2 | 70 | GPIO6,PWM0 | +| J6 | 10 | P40 | 40 | GPIO24 | +| J6 | 11 | P39 | 39 | GPIO23 | +| J6 | 12 | P61 | 61 | GPIO1,SPI1 CLK | +| J6 | 13 | P48 | 48 | GPIO22 | +| J6 | 14 | LSPKN | 110 | 喇叭通道 | +| J6 | 15 | LSPKP | 109 | 喇叭通道 | +| J6 | 16 | VRTC | 115 | 实时时钟电源 | +| J6 | 17 | GND | - | 接地 | +| J6 | 18 | VBAT | 36、37 | 3.8V | + + + +开发板主要管脚布局见下图 + +![](./media/ec600x-evb/600Uperipheral.png) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +开发板配备了多种传感器,以及其他外设。外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | 引脚 | +| ---- | ---------------------------- | ------------- | -------- | -------- | ----- | +| 1 | 温湿度传感器 | AHT20 | 是 | I2C | 56,57 | +| 2 | 光敏电阻 | GT36528 | 是 | ADC | 19 | +| 3 | 麦克风 | GMI6050P-66DB | 是 | SPK | 23,24 | +| 4 | 功放芯片 | NS4160 | 是 | SPK | 21,22 | +| 5 | LCD 显示屏(需选择含屏套餐) | ST7789 | 是 | SPI | 63~67 | + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC600U,以EC600U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC600U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec800g_hua_dtu.md b/docs/Dev_board_guide/zh/ec800g_hua_dtu.md new file mode 100644 index 0000000000000000000000000000000000000000..24e56171666257a28354b316746fc1eb86eef617 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec800g_hua_dtu.md @@ -0,0 +1,319 @@ +# EC800GCN 华系列 DTU 开发板介绍 + +## 支持的模块列表 + +- [EC800G-CN](https://python.quectel.com/modules-cat/ec800g-series) + + +## 功能列表 + +### 基本概述 + +华系列 DTU 产品搭载移远 EC800G-CN 模块,支持 4G Cat1 全网通,可实现串口与 4G(CAT1)的数据互传,相比于传统 2G/3G 网络,覆盖更广、速率更快、延时更低。采用宽电(9~36V)供电。接口丰富,提供 RS232、RS485 和 TTL 三种接口可选。开发方便快捷,支持透传,支持 Python 二次开发。安全可靠,支持软、硬件看门狗守护。体型小巧安装方便(22.6 * 74.6 mm)。 + +产品特点: + +- 小体积 +- 全网通 4G Cat1 +- 9~36V 宽压供电 +- 成品可选挂或导轨式安装 +- 软、硬件看门狗 +- 可选 RS232/RS485/TTL 三种接口 +- 支持 Python 二次开发 + +## 开发板资源 + +### 功能说明 + +开发板的主要组件、接口布局见下图。 + +![img](./media/ec800g_hua_dtu/DTU_wires_connection.png) + +① 连接胶棒天线 + +② 插入 Nano Sim 卡 + +③ 使用 mini USB 数据线连接至电脑 + +④ 使用 USB 转 TTL 模块连接至电脑。TX(DTU开发板) 接 RX(USB 转 TTL 模块);RX(DTU开发板) 接 TX(USB 转 TTL 模块);GND(DTU开发板) 接 GND(USB 转 TTL 模块)共地; + +⑤ 开发板采用 9-36 V 宽幅供电,正负极。 + +| 接口 | 功能 | 描述 | +| ------ | --------------------- | ------------------------------------------------------------ | +| 串口*1 | 通信 | RS232 3P 拔插式端子(2.54mm)
RS485 2P 拔插式端子(2.54mm)
TTL 3P 拔插式端子(2.54mm) | +| USB | 烧录/调试 | microUSB 不能用USB 给设备供电
用于烧录固件,更新Python 脚本 | +| LED | POWER/WORK/DATA指示灯 | POWER:电源指示灯,上电后常亮。
WORK:引脚号 PinGPIO12,用户自定义指示灯。
DATA:引脚号 Pin.GPIO36,用户自定义指示灯。 | +| Reload | 按键输入 | 引脚号 Pin.GPIO29,用户自定义用途。 | + + +> **小提示** +> 更多资料,请访问 。 + +## **资料下载** + +[EC800G_华-DTU系列开发板产品规格及用户指导](https://python.quectel.com/wp-content/uploads/2024/09/EC800G_华-DTU系列开发板产品规格及用户指导.pdf) + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **Nano SIM 卡** + 5. **胶棒天线** + 6. **USB转TTL模块** + +- **Step2:天线&SIM卡安装** + +安装配套的胶棒天线,并将Nano SIM卡插入开发板上的SIM卡座。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800G,以EC800G为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](./media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](./media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC600U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](./media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](./media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*work.py*文件,实现 WORK 指示灯 每隔 0.2 秒周期性高低电平变化,编写脚本如下所示: + +```python +import utime +from machine import Pin +print('Start') +LED_Work = Pin(Pin.GPIO12, Pin.OUT, Pin.PULL_DISABLE, 1) +while True: + if LED_Work.read(): + LED_Work.write(0) + else: + LED_Work.write(1) + utime.sleep(0.2) +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](./media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/work.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图,观察 WORK 指示灯变化 + +![](./media/ec800g_hua_dtu/work.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
+ + diff --git a/docs/Dev_board_guide/zh/ec800x-dp-dtu-q600r.md b/docs/Dev_board_guide/zh/ec800x-dp-dtu-q600r.md new file mode 100644 index 0000000000000000000000000000000000000000..a2eaba5fc9b89e1a9f9f34f60527c132df7b38fc --- /dev/null +++ b/docs/Dev_board_guide/zh/ec800x-dp-dtu-q600r.md @@ -0,0 +1,318 @@ +# EC800X_DP-DTU-Q600R 系列开发板介绍 + +## 快速开始 + +支持的模组列表 + +- [EC800K-CN](https://python.quectel.com/modules-cat/ec800k-series) +- [EC800M-CN](https://python.quectel.com/modules-cat/ec800m-series) + +## 功能列表 + +### 基本概述 + +EC800X_DP-DTU-Q600R 系列开发板是一款使用 LTE CAT1 网络的 DTU 开发板,其物理尺寸为 98mm x 46mm x 26mm,方便集成到工控机、工业设备、传感设备里。 + +- 开发板具备网络覆盖广、传输延时低的特点,支持三大运营商接入; +- 具备三个指示灯,方便客户确认设备状态; +- 支持 FOTA 远程升级,为产品提供可靠性; +- 支持 DC5 - 28V 宽电压供电; +- 具备标准 RS485 接口; +- 自带硬件看门狗; +- 适合各种工业场合,安装便捷; +- 同时开发板支持 TCP、MQTT、阿里云、电信云等云接入,未来扩展支持华为云、腾讯云、OneNET 等。 + +## 开发板渲染图 + +![](./media/ec800x-dp-dtu-q600r/渲染图.png) + +## 资料下载 + +[DP-DTU-Q600R 系列开发板产品规格及用户指导](https://python.quectel.com/wp-content/uploads/2024/11/EC800X_DP-DTU-Q600R系列开发板产品规格及用户指导.pdf) + +[DP-DTU-Q600R 系列开发板原理图](https://python.quectel.com/wp-content/uploads/2024/11/EC800X_DP-DTU-Q600R系列开发板原理图.pdf) + +[DP-DTU-Q600R 系列开发板丝印](https://python.quectel.com/wp-content/uploads/2024/11/EC800X_DP-DTU-Q600R系列开发板丝印.pdf) + +## 开发板资源 + +开发板的主要接口布局见下图。 + +![](./media/ec800x-dp-dtu-q600r/dp-dtu-q600r.png) + +- VCC:供电输入,DC5 - 28V。 +- GND:地。 +- 485A/RXD:支持 RS485,TTL。TTL:3.3V。 +- 485B/TXD:支持 RS485,TTL。TTL:3.3V。 +- POW:红灯,表示电源指示灯,上电即亮。 +- NET:红灯。 + - 常亮:正常工作; + - 灭:损坏; + - 快闪:信号好; + - 慢闪:信号差。 +- USER:红灯。 + - 常亮:已连接服务器; + - 灭:未连接。 +- SIM 卡槽:NANO SIM 卡槽支持的 USIM 符合 ETSI 和 IMT-2000 规范,并且支持 1.8V 和 3.0V USIM 卡。 +- USB 口。 +- 天线接口。 + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800M,以EC800M为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB_Driver_Win10_ASR](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverA_Customer_V1.1.13.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](./media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](./media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](./media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](./media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](./media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec800x-duino-evb.md b/docs/Dev_board_guide/zh/ec800x-duino-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..a70cfe3e811244cf2413dfb507117486f2499a38 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec800x-duino-evb.md @@ -0,0 +1,344 @@ +# EC800X QuecDuino开发板介绍 + +## 支持的模组列表 + +- [EG800K](https://python.quectel.com/modules-cat/eg800k-series) +- [EC800M](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800G](https://python.quectel.com/modules-cat/ec800g-series) +- [EC800E](https://python.quectel.com/modules-cat/ec800e-series) + +## 功能列表 + +### 基本概述 + +EC800X QuecDuino EVB 搭载移远 EC800 系列模组。支持模组型号为: +EC800M 系列、EC800K 系列、EG800K 系列、EC800E 系列等。 + +### 渲染图 + +开发板的主要组件、接口布局见下图 + +![](./media/ec800x-duino-evb/layout.jpg) + +## 资料下载 + +- [EC800X-QuecDuino-EVB-规格书](https://python.quectel.com/wp-content/uploads/2025/02/EC800X-QuecDuino-EVB-规格书V1.1.pdf) + +## 开发板资源 + +### 开发板接口 + +**接口定义** + +| 排针 | 引脚 | 描述 | 功能 | +| ---- | ---- | ---- | --------------------- | +| BOOT | - | 模组 USB_BOOT 引脚 | 根据不同型号模组进行上下拉进入强制下载模式 | +| NC | - | 悬空 | - | +| RST | - | 模组 RESET 引脚 | 拉低复位 | +| 3.3V | - | 电源输出 | 3.3V/200mA | +| 5V | - | 电源输入/输出 | 5V/2A (V1.1 版本悬空不可用) | +| GND | - | 地 | - | +| GND | - | 地 | - | +| 5V | - | 电源输入/输出 | 5V/2A (V1.1 版本悬空不可用) | +| A0 | - | 模组 ADC0 输入引脚 | 0-1.2V | +| A1 | - | 模组 ADC1 输入引脚 | 0-1.2V | +| D0 | 19 | I/O | 3.3V | +| D1 | 20 | I/O | 3.3V | +| D2 | 21 | I/O | 3.3V | +| D3 | 25 | I/O | 3.3V | +| 0 | - | 主串口接收 | 3.3V | +| 1 | - | 主串口发送 | 3.3V | +| 2 | - | 辅助串口接收 | 3.3V | +| 3 | - | 辅助串口接收 | 3.3V | +| 4 | 23 | I/O | 3.3V | +| 5 | 22 | I/O | 3.3V | +| 6 | 28 | I/O | 3.3V | +| 7 | 29 | I/O | 3.3V | +| 8 | 58 | I/O | 3.3V | +| 9 | 80 | I/O | 3.3V | +| 10 | 31 | I/O | 3.3V | +| 11 | 32 | I/O | 3.3V | +| 12 | 33 | I/O | 3.3V | +| 13 | 30 | I/O | 3.3V | +| 14 | - |地 | - | +| 15 | - |NC | 悬空 | +| 16 | 66 | I/O | 3.3V | +| 17 | 67 | I/O | 3.3V | + + +开发板主要管脚布局见下图 + +![](./media/ec800x-duino-evb/pin.jpg) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +开发板配备了多种传感器,以及其他外设。外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | 引脚 | +| ---- | ---------------------------- | ------------- | -------- | -------- | ----- | +| 1 | USB接口 | - | 是 | Type-C | - | +| 2 | LED灯 | - | 是 | GPIO | - | +| 3 | 麦克风 | B4013AM423-092 | 是 | SPK | - | + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用USB Type-C数据线连接开发板的Type-C接口和电脑USB口即可完成供电, 上电前需要跳帽短接 VUBS EN、VDD_EXT EN、VBAT EN 排针 + +- **Step4: 开发板开机** + +按住S1直至主板上电源指示灯亮(主板上丝印为D1的灯),如果上一步短接PWK_ON则无需长按PWK自动开机 + +`关于开发板灯光和电源详细设置参见规格书` + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800G,以EC800G为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](./media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](./media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](./media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](./media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](./media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](./media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec800x-evb.md b/docs/Dev_board_guide/zh/ec800x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..c6e69923a382086e153410f543d194e37c3a870b --- /dev/null +++ b/docs/Dev_board_guide/zh/ec800x-evb.md @@ -0,0 +1,369 @@ +# EC800X 开发板介绍 + +## 支持的模组列表 + +- [EC800N-CN](https://python.quectel.com/modules-cat/ec800n-series) +- [EC800M-CN](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800G-CN](https://python.quectel.com/modules-cat/ec800g-series) + +## 功能列表 + +### 基本概述 + +EC800X_QuecPython_EVB 开发板是专门针对 QuecPython 制造的、小巧便携的“口袋型”开发板。其搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![](./media/ec800x-evb/800X_产品功能.png) + +## 资料下载 + +- [EC800X_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/EC800X_EVB_V1.1-SCH.pdf) + +## 开发板资源 + +### 开发板接口 + +**J5排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ----- | --------------------- | +| J5 | 1 | GND | - | 接地 | +| J5 | 2 | GND | - | 接地 | +| J5 | 3 | RX0 | 38 | GPIO34
UART0_RXD | +| J5 | 4 | TX0 | 39 | GPIO35
UART0_TXD | +| J5 | 5 | RX1 | 28 | GPIO32 | +| J5 | 6 | TX1 | 29 | GPIO33 | +| J5 | 7 | RX2 | 17 | GPIO25
UART2_RXD | +| J5 | 8 | TX2 | 18 | GPIO26
UART2_TXD | +| J5 | 9 | SCL | 67 | GPIO24
I2C0_SCL | +| J5 | 10 | SDA | 66 | GPIO23
I2C0_SDA | +| J5 | 11 | P19 | 19 | GPIO27 | +| J5 | 12 | P20 | 20 | GPIO28 | +| J5 | 13 | P21 | 21 | GPIO29 | +| J5 | 14 | P22 | 22 | GPIO30 | +| J5 | 15 | ADC1 | | | +| J5 | 16 | ADC0 | 9 | ADC0 | +| J5 | 17 | GND | | | +| J5 | 18 | VBAT | 42/43 | | + +**J6排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ---- | -------------------- | +| J6 | 1 | 5V | - | 5V | +| J6 | 2 | 3V3 | - | 3.3V | +| J6 | 3 | EXT | 24 | 接地 | +| J6 | 4 | MISO | 33 | GPIO4
SPI0_MISO | +| J6 | 5 | MOSI | 32 | GPIO3
SPI0_MOSI | +| J6 | 6 | CS | 31 | GPIO2
SPI0_CS | +| J6 | 7 | CLK | 30 | GPIO1
SPI0_CLK | +| J6 | 8 | P23 | 23 | GPIO31 | +| J6 | 9 | IN0 | 28 | GPIO32 | +| J6 | 10 | IN1 | 87 | GPIO22 | +| J6 | 11 | IN2 | 77 | GPIO18 | +| J6 | 12 | IN4 | 83 | GPIO20 | +| J6 | 13 | IN5 | 75 | | +| J6 | 14 | OUT0 | 29 | GPIO33 | +| J6 | 15 | OUT1 | 86 | GPIO21 | +| J6 | 16 | OUT2 | 76 | GPIO17 | +| J6 | 17 | OUT4 | 82 | GPIO19 | +| J6 | 18 | OUT5 | 74 | | + +**J3排针管脚分配表** + +| 排针 | 编号 | 名称 | 引脚 | 功能 | +| ---- | ---- | ---- | ---- | ----------------------------------- | +| J3 | 1 | GND | - | 接地 | +| J3 | 2 | 3V3 | - | 3.3V | +| J3 | 3 | CLK | 53 | GPIO9
SPI1_CLK | +| J3 | 4 | SDA | 50 | GPIO6
UART1_TX
SPI1_MOSI | +| J3 | 5 | RST | 49 | GPIO5
PWM3 | +| J3 | 6 | DC | 51 | GPIO7
UART1_RXD
SPI1_MISO | +| J3 | 7 | BLK | | | +| J7 | 8 | CS | 52 | GPIO8
SPI1_CS | + + + +开发板主要管脚布局见下图 + +![](./media/ec800x-evb/800M外设.png) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +开发板配备了多种传感器,以及其他外设。外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | 引脚 | +| ---- | ---------------------------- | ------------- | -------- | -------- | ----- | +| 1 | 温湿度传感器 | AHT20 | 是 | I2C | 66,67 | +| 2 | 光敏电阻 | GT36528 | 是 | ADC | 9 | +| 3 | 麦克风 | GMI6050P-66DB | 是 | SPK | 3,4 | +| 4 | 功放芯片 | NS4160 | 是 | SPK | 5,6 | +| 5 | LCD 显示屏(需选择含屏套餐) | ST7789 | 是 | SPI | 49~53 | + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800U,以EC800U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EC800G系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/ec800x-pico-evb.md b/docs/Dev_board_guide/zh/ec800x-pico-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..cbc74f6edf815ab3ec7714f1a132b5e84364df19 --- /dev/null +++ b/docs/Dev_board_guide/zh/ec800x-pico-evb.md @@ -0,0 +1,341 @@ +# EC800X_pico 系列开发板介绍 + +## 快速开始 + +支持的模组列表 + +- [EC800K-CN](https://python.quectel.com/modules-cat/ec800k-series) +- [EC800M-CN](https://python.quectel.com/modules-cat/ec800m-series) +- [EC800E-CN](https://python.quectel.com/modules-cat/ec800e-series) +- [EG800K-CN](https://python.quectel.com/modules-cat/eg800k-series) + +## 功能列表 + +### 基本概述 + +EC800X_pico 系列开发板是一款使用 LTE CAT1 网络,基于移远 EC800 系列模组的低成本但灵活的开发板。 + +- 开发板上 40 个拓展引脚具备 28.6mm× 65.5mm 'DIP'风格,封装上 PCB 厚度为 1.6mm; +- 拓展引脚中多达 30 个 3.3V 通用 GPIO; +- 具备 2 路 ADC 接口; +- 最多 4 × UART,最多 2 × I2C,最多 3 × SPI,最多 4 × PWM 通道; +- 简单的电源架构,可从 TypeC 接口供电,亦可以通过 40pin 排针接口供电。 + +## 开发板渲染图 + +![](./media/ec800x-pico-evb/渲染图.png) + +## 资料下载 + +- [EC800X_pico 系列开发板产品规格及用户指导](https://images.quectel.com/python/2024/12/EC800X_pico系列开发板产品规格及用户指导.pdf) +- [EC800X_pico 系列开发板原理图](https://images.quectel.com/python/2024/12/EC800X_pico系列开发板原理图.pdf) +- [EC800X_pico 系列开发板丝印](https://images.quectel.com/python/2024/12/EC800X_pico系列开发板丝印.pdf) + +## 开发板资源 + +开发板的主要接口布局见下图。 + +![](./media/ec800x-pico-evb/pin.png) + +| 引脚序号 | 引脚定义 | 描述 | DC 特性 | +| :------: | :------: | :----------------: | :----------------------------------------------------------: | +| 1 | 5V | 供电输入 | 5V/2A | +| 2 | 5V | 供电输入 | 5V/2A | +| 3 | 3.3V | 电源输出 | 3.3V/200mA | +| 4 | 3.3V | 电源输出 | 3.3V/200mA | +| 5 | GND | 地 | \ | +| 6 | GND | 地 | \ | +| 7 | PIN84 | I/O | 3.3V 电平 | +| 8 | PIN85 | I/O | 3.3V 电平 | +| 9 | PIN68 | I/O | 3.3V 电平 | +| 10 | PIN69 | I/O | 3.3V 电平 | +| 11 | PIN77 | I/O | 3.3V 电平 | +| 12 | PIN76 | I/O | 3.3V 电平 | +| 13 | PIN75 | I/O | 3.3V 电平 | +| 14 | PIN74 | I/O | 3.3V 电平 | +| 15 | PIN54 | I/O | 3.3V 电平 | +| 16 | PIN55 | I/O | 3.3V 电平 | +| 17 | ADC1 | AI | 0 - 1.2V | +| 18 | ADC0 | AI | 0 - 1.2V | +| 19 | SPK_N | AO | 37 mW @ THD =1%, R = 32 Ω。
若输出功率无法满足需求,可用此接口驱动外部功放。
不用则悬空。 | +| 20 | SPK_P | AO | 37 mW @ THD =1%, R = 32 Ω。
若输出功率无法满足需求,可用此接口驱动外部功放。
不用则悬空。 | +| 21 | PIN66 | I/O | 3.3V 电平 | +| 22 | PIN67 | I/O | 3.3V 电平 | +| 23 | PIN30 | I/O | 3.3V 电平 | +| 24 | PIN31 | I/O | 3.3V 电平 | +| 25 | PIN32 | I/O | 3.3V 电平 | +| 26 | PIN33 | I/O | 3.3V 电平 | +| 27 | PIN56 | I/O | 3.3V 电平 | +| 28 | PIN57 | I/O | 3.3V 电平 | +| 29 | PIN58 | I/O | 3.3V 电平 | +| 30 | PIN25 | I/O | 3.3V 电平 | +| 31 | PIN20 | I/O | 3.3V 电平 | +| 32 | PIN19 | I/O | 3.3V 电平 | +| 33 | PIN29 | I/O | 3.3V 电平 | +| 34 | PIN28 | I/O | 3.3V 电平 | +| 35 | TXD2 | 主串口发送引脚 | 3.3V 电平 | +| 36 | RXD2 | 主串口接收引脚 | 3.3V 电平 | +| 37 | PIN22 | I/O | 3.3V 电平 | +| 38 | PIN23 | I/O | 3.3V 电平 | +| 39 | TXD0 | debug 串口发送引脚 | 3.3V 电平 | +| 40 | RXD0 | debug 串口接收引脚 | 3.3V 电平 | + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +开发板上USB和DC的电源选择开关拨到USB处 + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EC800M,以EC800M为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB_Driver_Win10_ASR](https://developer.quectel.com/wp-content/uploads/2024/09/Quectel_Windows_USB_DriverA_Customer_V1.1.13.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/eg91x-evb.md b/docs/Dev_board_guide/zh/eg91x-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..35d17beedf94ff9bf29cb15d3c0fd39640bd9750 --- /dev/null +++ b/docs/Dev_board_guide/zh/eg91x-evb.md @@ -0,0 +1,476 @@ +# EG91X开发板介绍 + +## 支持的模块列表 + +- [EG915U](https://python.quectel.com/modules-cat/eg915u-series) + + +## 功能列表 + +### 基本概述 + +QuecPython_EG91X系列C1-P02开发板是一款专门针对QuecPython设计的、小巧便携的“口袋型”开发板。 + +主模块搭载EG915U系列LTE Cat 1无线通信模块,同时在封装上兼容移远通信多网络制式EG91系列、EG95系列、BG95系列和BG96模块,实现了2G网络和4G网络的无缝切换,以满足不同行业产品应用需求。 + +该开发板自身板载Type-C接口,方便开发,开发者仅需一条USB Type-C数据线即可轻松玩转开发板。 + +并且该开发板兼容树莓派zero的扩展板,树莓派zero的扩展板可以在开发板上直接使用。 + + +## 开发板资源 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![img](./media/eg91x-evb/EG915U_1.png) + +开发板尺寸图 + +![img](./media/eg91x-evb/915U_chicun.png) + +开发板主要引脚布局见下图 + +![img](./media/eg91x-evb/EG91X_EVB.png) + +> **小提示** +> 开发板的更多资料,请访问 。 + + +### 开发板配置 + +开发板外设接口分配表明细如下: + +| 序号 | 名称 | 型号 | 丝印 | 备注 | +| ---- | -------------- | ------------ | ----------- | ------------------------------------------------------------ | +| 1 | USB Type-C接口 | - | - | - | +| 2 | SIM卡座1 | SMN-315-ARP7 | SIM1 | Nano-SIM | +| 3 | SIM卡座2 | MUP-C7809-1 | SIM2 | E-SIM | +| 4 | SD卡槽 | TF-101A-P3 | SD 2.0 | 使用SD卡前,首先需要在10PIN功能排针中使能SD,对SD供电。 | +| 5 | USB 供电开关 | - | USB_ON/OFF | 开关处于常闭状态时,Type-C对模块和开发板供电,USB可正常连接;USB开关处于常开状态时,Type-C仅对开发板供电,此时模块处于未供电状态。 | +| 6 | MIPI接口 | - | MIPI_DSI | 主模块为EG91X系列时,支持MIPI屏幕,且全兼容树莓派外设。 | +| 7 | 摄像头接口 | - | - | 开发板支持定制的SPI摄像头,最大像素支持30W像素。 | +| 8 | MIC&SPK接口 | AW8733A- | +MIC-/-SPK+ | - | +|9 | 40-Pin排针 | - | - | 板载40-Pin排针,具体参见上文图表。 | +| 10 | 10-Pin排针 | - | - | 板载10-Pin排针,具体参见上文图表。 | +| 11 | ADC接口 | - | ADC1_IN | ADC测量接口 | +| 12 | PWK按键 | - | PWK | 开机按键 | +| 13 | RST按键 | - | RST | 重启按键 | +| 14 | BOOT按键 | - | BOOT | 固件烧录按键 | +| 15 | 天线接口 | - | LTE
DIV/WIFI/BT
GNSS | LTE天线座
DIV/WIFI/BT天线座
GNSS天线座 | + +**开发板载有5颗功能性指示灯,分别如下** + +- **P21**:电源指示灯。 +- **PSM**:模块Pin 1,为PSM指示灯。 +- **SCK1**:SIM1检测指示灯,SIM1卡插入时亮起。 +- **SCK2**:SIM2检测指示灯,SIM2卡插入时亮起。 +- **PWR**:电源指示灯。 + +> 上述指示灯位置参考上文开发板正面图下方丝印(模块所在面为正面)。 +> + + +### 开发板接口 + +**10-Pin排针引脚分配表** + +| **排针** | **编号** | **丝印** | **功能** | +| -------- | -------- | --------- | -------- | +| 10-Pin | 1 | PWK_AUTO | POWERKEY | +| 10-Pin | 2 | PWK_AUTO | GND | +| 10-Pin | 3 | VDD_EXT | 1.8 V | +| 10-Pin | 4 | VDD_EXT | VDD_EXT | +| 10-Pin | 5 | MODULE_EN | 3.8 V | +| 10-Pin | 6 | MODULE_EN | 3.8 V | +| 10-Pin | 7 | SD_EN | SD_EN | +| 10-Pin | 8 | SD_EN | 3.3 V | +| 10-Pin | 9 | GNSS_EN | 3.3 V | +| 10-Pin | 10 | GNSS_EN | GNSS_EN | + +- **1 & 2**:自动开机 +- **3 & 4**:VDD_EXT 连接时可对外供电,测量功耗时需断开 +- **5 & 6**:接通 DCDC 对模块供电 +- **7 & 8**:使能 SD 供电 +- **9 & 10**:使能 GNSS 有源供电 + +> 测量功耗时注意关闭USB供电开关,开发板背面USB_ON/OFF的拨杆开关。 + +**40-Pin单号排针引脚分配表** + +|**编号** | **名称** | **功能复用** | **功能** | **编号** | **名称** | **功能复用** | **功能** | +| -------- | -------- | ------------------- | --------------------------------- | -------- | -------- | ------------------- | --------------------------------- | +| 1 | 3V3 | - | 3.3 V输出 | 2 | 5V | - | 5 V输出 | +| 3 | SDA | I2C1_SDA
GPIO14 | I2C1串行数据
通用输入输出 | 4 | 5V | - | 5 V输出 | +| 5 | SCL | I2C1_SCL
GPIO13 | I2C1串行时钟
通用输入输出 | 6 | GND | - | 接地 | +| 7 | P92 | GPIO30 | 通用输入输出 | 8 | TXD | UART1_TXD | UART1发送 | +| 9 | GND | - | 接地 | 10 | RXD | UART1_RXD | UART1接收 | +| 11 | P116 | GPIO41 | 通用输入输出 | 12 | P05 | GPIO2
SPI1_CS | 通用输入输出
SPI1片选 | +| 13 | P16 | GPIO24 | 通用输入输出 | 14 | GND | - | 接地 | +| 15 | P42 | GPIO26 | 通用输入输出 | 16 | P21 | GPIO17 | 通用输入输出 | +| 17 | 3V3 | - | 3.3 V输出 | 18 | P111 | GPIO38 | 通用输入输出 | +| 19 | MO0 | SPI0_MOSI
GPIO15 | SPI0主输出从输入
通用输入输出 | 20 | GND | - | 接地 | +| 21 | MI0 | SPI0_MISO
GPIO21 | SPI0主输入从输出
通用输入输出 | 22 | P37 | GPIO23 | 通用输入输出 | +| 23 | CLK0 | SPI0_CLK
GPIO10 | SPI0时钟
通用输入输出 | 24 | CS0 | SPI0_CS
GPIO9 | SPI0片选
通用输入输出 | +| 25 | GND | - | 接地 | 26 | P83 | GPIO28 | 通用输入输出 | +| 27 | P85 | GPIO18 | 通用输入输出 | 28 | P86 | GPIO19 |通用输入输出 | +| 29 | P84 | GPIO29 | 通用输入输出 | 30 | GND | - | 接地 | +| 31 | P104 | GPIO34 | 通用输入输出 | 32 | P20 | GPIO16
PWM0 | 通用输入输出
PWM0输出 | +| 33 | P105 | GPIO35 | 通用输入输出 | 34 | GND | - | 接地 | +| 35 | P07 | GPIO04
SPI1_MISO | 通用输入输出
SPI1主输入从输出 | 36 | P106 | GPIO36 | 通用输入输出 | +| 37 | P108 | GPIO37 | 通用输入输出 | 38 | P06 | GPIO3
SPI1_MOSI | 通用输入输出
SPI1主输出从输入 | +| 39 | GND | - | 接地 | 40 | P04 | GPIO1
SPI1_CLK | 通用输入输出
SPI1时钟 | + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为LTE天线座位置,并将SIM卡插入开发板上的SIM卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step4: 开发板开机** + +长按PWRKEY开机,在按下PWRKEY按键之前,需保证供电电压稳定。建议从上电到按下PWRKEY按键之间的时间间隔不少于30 ms。开机后开发板NET灯闪烁,开发板已正常开机。 如果PWK_AUTO已使用跳线帽短接则模组上电会自动开机。 + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://python.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有EG915U,以EG915U为例,在下载页面右侧选择该型号的USB驱动[QuecPython_USB Driver Win10_U_G](https://images.quectel.com/python/2023/04/Quectel_Windows_USB_DriverU_V1.0.19.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**"setup.exe"** 或者是**"setup.bat"**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + +- 右键打开【**我的电脑**】——选择【**管理**】——选择【**设备管理器**】,然后在设备管理器中选择 【**端口**】,按照步骤打开页面后如图所示能刷新出**Quectel USB** 名称开头的串口则USB驱动安装成功。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://python.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](./media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](./media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +如果是老版本固件,固件文件格式不一定以bin结尾,其中EG915U系列模组选择解压后的pac文件 + +- **Step3:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step4:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](./media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**Quectel USB REPL Port**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](./media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](./media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](./media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
+ + +## 低功耗测试指导 + +EG915U模组支持多种工作模式,每种模式的功耗各不相同,常见的工作模式有以下几种: + +**ACTIVE**:模组进行LTE数传、GSM通话或RTOS在运行逻辑时的状态,功耗受到具体业务和网络通信制式的影响,CPU本身功耗和网络射频功率都有所不同,故实际功耗在不同工况下会有较大差异。 + +**IDLE**:此时模组处于空闲状态,硬件正常在电,RTOS保持运行,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。ECX00U系列模组会在IDLE模式下降低时钟频率,进入轻睡眠状态(关闭高速时钟,但CPU不休眠的状态)。 + +**休眠**:休眠模式的前提是模组处于空闲状态且使能autosleep,进入休眠模式后,RTOS暂停运行,模组的时钟频率会变慢,部分外设控制器(UART、SPI等)下电,同时只保留部分中断控制器,达到减小功耗的目的。 + +**PSM**:PSM模式是3GPP协议所规定的一种低功耗模式,这种模式下,模组只会周期性的唤醒并执行业务,其余时间都处于PSM休眠中。PSM休眠时,模组行为和功耗都近似于关机。 + +**关机**:模组完全下电的状态,此时BB芯片和外设控制器完全关闭,但PMIC仍是在电的。一般可由Powerkey或者RTC闹钟唤醒。 + +| 模组型号 | EG915U | +| :------------------- | :------ | +| IDLE(LTE FDD@64ms) | 13.0 mA | +| SLEEP(LTE FDD@64ms) | 1.8 mA | +| SLEEP(CFUN0) | 1.0mA | +| 关机 | 32 μA | + +### 测试准备 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + 4. **SIM 卡** + 5. **4G 天线** + 6. **Power Monitor Mini**(功耗仪) + +- **Step2:天线&SIM卡安装** + +安装开发板配套的天线,安装位置为 MAIN 天线座位置,并将 SIM 卡插入开发板上的 SIM 卡座。 + +- **Step3:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,功耗仪正极连接MODULE_EN的Vbat,功耗仪负极连接模组GND即可。具体连接如图: + + + +> 注意!!! +> +> 测量功耗时需要拔出所有跳线帽,以免测量结果受其他外界因素影响 + +### 测量功耗 + +#### 关机耗流 + +使用 USB Type-C 数据线连接开发板的 Type-C 接口和电脑 USB 口,待测设备硬件连接完毕后,不进行开机,断开USB_VBus(位于开发板背面,USB开关拨至off即可),即可直接测量关机电流。此时,模组不工作,对外的输出引脚也全部拉低或悬空,整体平均耗流保持相对稳定,基本都在uA级。 + +image-20250709190947650 + +#### 空闲耗流 + +完成关机电流测量后,长按powerkey开机,模组开机默认的功耗模式是IDLE(即空闲模式)。此时模组处于空闲状态,硬件正常在电,但没有任何线程需要被执行。有业务启动或网络业务呼入时,会立即恢复运行。 + +image-20250709193332755 + +#### 休眠耗流 + +模组处于空闲状态时,若autosleep被使能,则模组会进入休眠状态。此时,模组会关闭部分IP核(如外设控制器和中断控制器等)并且降低时钟频率,从而实现功耗的降低。 + +完成空闲耗流测量后,打开USB_VBus,电脑端打开[QPYcom工具](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip),导入`pm`模块,调用`autosleep`方法打开模组的自动休眠,在没有任务执行时,模组会自动进入休眠状态,调用方法后记得断开USB_VBus(USB开关拨至off),否则模组不会进入休眠状态。[API参考](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#%3Ccode%3Epm.autosleep%3C/code%3E)。关于休眠耗流的详细介绍[参考](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 + +image-20250709194047484 + +进入休眠模式后,模组应有的耗流波形会有周期稳定的凸起,如下图: + +image-20250709194047484 + +#### PSM耗流 + +启用PSM时,需要先向基站发送请求(通过ATTACH或TA_UPDATER携带定时器信息)。基站若支持进入PSM,则会在对应的REQUEST中下发定时器信息,需要注意的是,实际PSM的参数会使用基站下发的值,并不一定和我们请求的值相同。模组会以基站下发的值来配置定时器时间,当模组进入IDLE且ACT定时器超时,模组会关闭CPU和一切射频,此时相当于部分关机,只是保留了比关机更多的唤醒源,一般包括ACT、TAU定时器和PSM_INT。功耗一般下降到微安级别。 + +打开USB_VBus,电脑端打开[QPYcom工具](https://developer.quectel.com/wp-content/uploads/2024/09/QPYcom_V3.8.0.zip),启用PSM,开启后记得断开USB_VBus(USB开关拨至off)。启用PSM模式的[API参考](https://developer.quectel.com/doc/quecpython/API_reference/zh/syslib/pm.html#%3Ccode%3Epm.set_psm_time%3C/code%3E)。 + +image-20250709194047484 + +等待ACT定时器超时后,我们可查看PSM休眠下的底电流。如图可见,PSM的底电流远低于普通的autosleep模式,和关机耗流的大小、特征较为相似。 + +image-20250709194047484 + +> 注意: +> +> 进入PSM模式需要确认运营商是否支持,还需配置支持的网络制式 ! ! ! +> +> 更多耗流测试指导请[参考这里](https://developer.quectel.com/doc/quecpython/Application_guide/zh/system/power-consumption.html)。 diff --git a/docs/Dev_board_guide/zh/fcm360w-evb.md b/docs/Dev_board_guide/zh/fcm360w-evb.md new file mode 100644 index 0000000000000000000000000000000000000000..bb64a1781db3a61fb737421262d40d98e905c44b --- /dev/null +++ b/docs/Dev_board_guide/zh/fcm360w-evb.md @@ -0,0 +1,335 @@ +# FCM360W 开发板介绍 + +## 支持的模组列表 + +- [FCM360W](https://python.quectel.com/modules-cat/fcm360w-series) + + +## 功能列表 + +### 基本概述 + +QuecPython_FCM360W_EVB 开发板是一款专门针对QuecPython设计的、小巧便携的“口袋型”开发板。其搭载Type-C接口,开发者仅需一条USB Type-C 数据线即可轻松玩转开发板。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![img](./media/fcm360w-evb/peripheral-interfaces.png) + +## 资料下载 + +- [FCM360X_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/FCM360X-EVB-V1.3-SCH.pdf) + + +## 开发板资源 + +### 开发板接口 + +**J1排针管脚分配表** + +| **排针** | **编号** | **名称** | **引脚** | **功能** | +| -------- | -------- | -------- | -------- | -------- | +| J1 | 1 | VCC_3V3 | - | 3.3V | +| J1 | 2 | MAIN_RXD | 26 | UART0 | +| J1 | 3 | MAIN_TXD | 27 | UART0 | +| J1 | 4 | GND | - | 接地 | +| J1 | 5 | CEN | 5 | 模组使能 | +| J1 | 6 | IO22 | 13 | GPIO22 | +| J1 | 7 | IO21 | 12 | GPIO21 | +| J1 | 8 | IO16 | 10 | GPIO16 | +| J1 | 9 | IO4 | 9 | GPIO4 | +| J1 | 10 | IO14 | 8 | GPIO14 | +| J1 | 11 | IO15 | 7 | GPIO15 | +| J1 | 12 | IO20 | 6 | GPIO20 | + +**J2排针管脚分配表** + +| **排针** | **编号** | **名称** | **引脚** | **功能** | +| -------- | -------- | -------- | -------- | ---------------- | +| J2 | 1 | IO25 | 16 | GPIO25 | +| J2 | 2 | IO24 | 15 | GPIO24 | +| J2 | 3 | IO23 | 14 | GPIO23 | +| J2 | 4 | IO17 | 19 | GPIO17 | +| J2 | 5 | IO13 | 20 | GPIO13 | +| J2 | 6 | IO1 | 21 | GPIO1 | +| J2 | 7 | IO0 | 22 | GPIO0 | +| J2 | 8 | IO3 | 23 | GPIO3 | +| J2 | 9 | IO2 | 29 | GPIO2 | +| J2 | 10 | RESET | 11 | 模组复位 | +| J2 | 11 | BOOT | 17 | 模组启动方式选择 | +| J2 | 12 | GND | - | 接地 | + +开发板主要管脚布局见下图 + +![img](./media/fcm360w-evb/pin-layout.png) + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | 引脚 | +| ---- | --------- | ------ | -------- | -------- | ----- | +| 1 | USB转串口 | CH340N | 是 | USB | 26,27 | +| 2 | 按键 | - | 是 | GPIO | 15,16 | + + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **USB 数据线** (USB-A TO USB-TypeC) + 3. **PC** (Windows10) + +- **Step2:开发板连接** + +使用 USB Type-C 数据线连接开发板的 Type-C 和电脑 USB 口即可完成供电。 + +- **Step3: 开发板开机** + + +**执行以上操作后POW灯常亮即开机成功** + + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有FCM360W,以FCM360W为例,在下载页面右侧选择该型号的USB 转串口驱动[CH343SER](https://developer.quectel.com/wp-content/uploads/2024/09/CH343SER_V1.8.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**CH343SER.EXE**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** + +- **Step1:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step2:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +- **Step3:选择固件** + +端口选择连接**USB-Enhanced-SERIAL-A CH342** + +- **Step4:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step5:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:进入交互页面** + +打开QPYcom工具,端口选择连接**USB-Enhanced-SERIAL-B CH342**,选择“交互”界面 + +- **Step2:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/fcm360w-teb.md b/docs/Dev_board_guide/zh/fcm360w-teb.md new file mode 100644 index 0000000000000000000000000000000000000000..a3d329f9362ea96fcdf0219bc3a17826a87a541e --- /dev/null +++ b/docs/Dev_board_guide/zh/fcm360w-teb.md @@ -0,0 +1,334 @@ +# FCM360W te-b开发板介绍 + +## 支持的模组列表 + +- [FCM360W](https://python.quectel.com/modules-cat/fcm360w-series) + + +## 功能列表 + +### 基本概述 + +QuecPython_FCM360W_TE-B 开发板是一款Quectel推出的Wi-Fi 和蓝牙开发板。搭载FCM360W模组,支持 Wi-Fi 6 和蓝牙 5.1无线连接,提供包括 512 KB SRAM 和 4MB 闪存在内的超大内存。 + +开发板连接接口为两个micro-usb接口,并提供多种接口,包括 UART、SPI、I2C、ADC等,配套天线有外置引脚天线、PCB 天线等。 + +### 功能说明 + +开发板的主要组件、接口布局见下图 + +![img](./media/fcm360w-teb/fcm360w-teb.png) + +## 资料下载 + +- [FCM360X_EVB_SCH](https://python.quectel.com/wp-content/uploads/2024/09/FCM360X-EVB-V1.0-SCH.pdf) +- [Quectel_FCM360W_硬件设计手册](https://python.quectel.com/wp-content/uploads/2024/09/Quectel_FCM360W_硬件设计手册_V1.0.pdf) + + +## 开发板资源 + +### 开发板接口 + +开发板主要管脚布局见下表 + +| **排针** | **名称** | **引脚** | **功能** | +| -------- | -------- | -------- | -------- | +| UART | UART0_RXD | 26 | UART0接收 | +| UART | UART0_TXD | 27 | UART0发送 | +| UART | RST | 11 | 模组复位 | +| UART | UART2_RXD | 19 | UART2接收 | +| UART | UART2_TXD | 20 | UART2发送 | +| UART | UART0_RXD_M | 26 | UART0 | +| UART | UART0_TXD_M | 27 | UART0 | +| UART | RST_M | 11 | 模组复位 | +| UART | UART2_RXD_M | 19 | UART2 | +| UART | UART2_TXD_M | 20 | UART2 | +| SPI | RESERVE | 17 | 预留 | +| SPI | MOSI | 29 | SPI主输出从输入| +| SPI | MISO | 23 | SPI主输入从输出| +| SPI | CLK | 22 | SPI时钟 | +| SPI | CS0 | 21 | SPI片选 | +| SPI | GPIO25 | 16 | GPIO25 | +| SPI | MOSI_M | 29 | SPI主输出从输入| +| SPI | MISO_M | 23 | SPI主输入从输出| +| SPI | CLK_M | 22 | SPI时钟 | +| SPI | CS0_M | 21 | SPI片选 | + +- **名称中带_M的引脚为模组端直接引出来的脚** + + +> **小提示** +> 开发板的更多资料,请访问 + +### 开发板配置 + +外设资源管脚分配表明细如下: + +| 序号 | 名称 | 型号 | 是否支持 | 接口类型 | +| ---- | --------- | ------ | -------- | -------- | +| 1 | USB转串口 | CP2102 | 是 | UART | +| 2 | 按键 | - | 是 | GPIO | +| 2 | ANT | - | 是 | - | + + +## 快速入门 + +### 硬件准备 + +以下是开发板上手之后的硬件准备步骤 + +- **Step1:硬件准备** + + 开始之前需要准备以下配件 + + 1. **开发板** + 2. **micro usb 数据线** + 3. **PC** (Windows10) + +- **Step2:开发板连接** + +使用micro usb数据线将开发板上的UART2接口和电脑USB口连接即可完成供电,开发板的POWER开关切换到ON状态 + +- **Step3: 开发板开机** + +上电后会自动开机 + + +### 驱动安装 + +- 打开[QuecPython官网驱动下载链接](https://developer.quectel.com/resource-download?cid=5) + +- 选择与模组型号匹配的驱动,该开发板搭载的模组有FCM360W,以FCM360W为例,在下载页面右侧选择该型号的USB 转串口驱动[CH343SER](https://developer.quectel.com/wp-content/uploads/2024/09/CH343SER_V1.8.zip)点击下载,如果开发板搭载的是其他型号同样按照以上操作即可。 + +- 下载后解压驱动压缩包,找到**CH343SER.EXE**,双击运行即可,安装完之后打开设备管理器就可以看到设备管理器中端口的黄色感叹号消失了,说明安装成功,能够正常通信。 + +> 出现 Mobile ECM Network Adapter CDC Ethernet Control Modle (ECM) 等设备未被识别属于正常现象,不影响固件烧录和后续开发,无需理会。 + + +### 工具安装 + +- QPYcom获取 + +使用QuecPython进行开发需要用到专用的开发调试工具——**QPYcom**,包括但不限于调试代码、分析日志、文件传输、烧录固件、合并固件等。 + +打开[QuecPython工具下载页面](https://developer.quectel.com/resource-download?cid=8),根据操作系统选择对应的工具进行下载。 + +*注意:该工具无需安装,解压即用。* + +- VSCode插件 + +编辑Python代码一般会用到专用于Python或者兼容多种语言的IDE,可以有效提升开发效率,这里推荐VSCode + +针对VScode,QuecPython推出专用插件实现代码提示、代码补全和串口调试等功能,安装方法见下图 + +在VSCode中点击侧边栏插件市场,在插件市场中搜索 “QuecPython”,根据搜索结果下载该插件即可 + +![](media/readme/VScode_1.png) + +### 固件烧录 + +**固件获取** + +模组在出厂时通常烧录有标准 AT 固件或 QuecOpen 固件,如需基于 QuecPython 对模块进行开发,需要手动为其重新烧录专门的 QuecPython 固件。 + +[官网固件下载地址](https://developer.quectel.com/resource-download?cid=15) + +![](media/readme/Firmware.png) + +面对官网种类众多的固件,如何选择合适的固件包,首先需要知道使用的模组的型号,模组型号可以通过模组的镭雕或者发送AT指令来获得。 + +在获取到模组型号之后根据模组的型号去官网下载该模组对应的固件即可,固件的名称一般为`QPY_OCPU_版本号_模组型号_FW`,没有特殊需求默认下载最新版本即可。 + +点击下载列的下载按钮即可下载,下载成功后会得到一个固件名称命名的压缩包文件(zip包) + +从官网下载的固件包为压缩包格式,固件压缩包下载到本地后,需进行解压。解压后可获得两个文件,其中 .bin 格式的是 QuecPython 固件本体,.md 格式的是更新日志。 + +![](media/readme/firmware_zip.png) + +> 请务必将压缩包内容解压至一个**不包含中文、空格和其他特殊字符**的路径下,否则下载工具可能无法正常识别到固件,同时下载工具路径也**不可包含中文、空格和其他特殊字符**。 + +**固件烧录** +- **Step1:连接设备** + +使用micro usb数据线将开发板上的UART0接口和电脑USB口连接 + +- **Step2:创建项目** + +首先确保模组连接正常并已开机,打开QPYcom工具进入下载页面,点击**"创建"**项目,新建要下载的固件项目,项目名称自定义,配置完成后持久化保存 + +- **Step3:选择固件** + +选择要下载到模组的固件(根据要下载的模组型号选择对应的固件,若为新格式固件则所有模组型号都选择.bin文件即可) + +- **Step4:打开串口** + +点击打开串口 + +- **Step5:设置下载模式** + +单击**“Download script”**右侧的下拉选择箭头,选择**"Download FW"** + +- **Step6:开始烧录固件** + +点击**"Download FW"**后,开始下载固件,下载过程会有进度条和进度百分比显示,等待下载完毕会有弹窗提示下载成功 + +![](media/readme/firmware.gif) + +### REPL调试 + +REPL全称为**Read-Eval-Print-Loop (交互式解释器)**,可以在REPL中进行QuecPython程序的调试 + +运行 **QPYcom** 工具后,选择正确的串口(波特率无需指定)并打开,即可开始 Python 命令行交互。 + +- **Step1:连接设备** + +使用micro usb数据线将开发板上的UART2接口和电脑USB口连接 + +- **Step2:进入交互页面** + +打开QPYcom工具,选择端口,选择“交互”界面 + +- **Step3:打开串口** + +点击“打开串口”按钮,在交互界面输入**print(‘hello world’)**,按回车后可以看到执行的结果信息 + +```python +>>> print('hello world') +hello world +``` + +![](media/readme/hello_world.png) + +*注意:工具交互页面输入时需要输入英文字符,中文字符将会被屏蔽* + +## 开发第一个脚本 + +### 编写第一个脚本文件 + +创建*helloworld.py*文件输出“hello world”,打印“hello world”,编写脚本如下所示: + +```python +print("hello world") +``` + +通过QPYcom将上面编辑好的文件下载到模组中去并运行 + +![](media/readme/QPYcom_hello.jpg) + +### PC与模组间的文件传输 + +**下载方法一:** + +image-2021081301 + +- **Step1:打开串口** + +首先选择模组的交互口,点击"打开串口"按钮 + +- **Step2:通过工具按钮下载** + +可以通过文件页面右侧上面的 "**+**","**-**" 按钮来上传和删除文件 + +- **Step3:通过拖拽形式下载** + +也可以通过拖拽的方式将文件页面左侧显示的本地文件直接拖拽到右侧模组中去(也可以拖拽文件夹) + +- **Step4:下载进度和结果** + +下载过程中会在状态栏显示下载文件名和下载进度 + +**下载方法二:** + +image-2021081301 + +- **Step1:创建项目** + +根据需求,创建用户项目(点击"创建"按钮),步骤同上文烧录固件 + +- **Step2:配置要下载的文件** + +选择需要下载到模块的用户脚本(在"用户脚本"区域通过右键菜单添加) + +- **Step3:设置下载模式** + +左击下拉选择箭头,选择"下载脚本",即"Download Script" + +- **Step4:开始下载脚本** + +点击"下载脚本"开始下载脚本,下载过程中有进度条提示 + +### 运行脚本文件 + +- **Step1:下载脚本** + +将要执行的脚本文件下载到模组中去,具体步骤参考上文 + +- **Step2:通过repl执行脚本** + +打开串口之后,在QPYcom交互页面输入以下代码执行脚本文件 + +```python +import example +example.exec("/usr/helloworld.py") # filePath为要执行的脚本文件路径 +``` + +- **Step3:通过GUI工具执行脚本** + +或者通过QPYcom文件页面 **执行** 按钮执行脚本文件,在工具的文件页面选择要执行的脚本文件然后点击 "**▷**"按钮 + +执行结果如图 + +![](media/readme/QPYcom_repl_hello.png) + +### 停止程序运行 + +如何停止正在运行的程序,根据运行的脚本文件类型有以下方法: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
程序名是否
为main.py
程序中是否
包含了死循环
程序中是否
使用了多线程
停止步骤
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请重新烧录固件
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + A 键进入 RAW 模式
(2)按 Ctrl + D 键重启 QuecPython 虚拟机
(3)按 Ctrl + B 键回到普通交互模式
(4)若以上方法无效,请耐心等待程序运行结束
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + D 键重启 QuecPython 虚拟机
(2)若以上方法无效,请直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
(1)按 Ctrl + C 键打断程序运行
(2)若以上方法无效,请重新烧录固件或直接重启模块
diff --git a/docs/Dev_board_guide/zh/media/bg-eg-core-evb/PH-7_all.png b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/PH-7_all.png new file mode 100644 index 0000000000000000000000000000000000000000..66e25cd5d8f03c3d77a439e3ebb939eeea35cd8b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/PH-7_all.png differ diff --git "a/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277pin\345\256\232\344\271\211.png" "b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277pin\345\256\232\344\271\211.png" new file mode 100644 index 0000000000000000000000000000000000000000..283199a39a4dbe6de5ac992acbfd064a417107c3 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277pin\345\256\232\344\271\211.png" differ diff --git "a/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277\345\256\236\347\211\251\345\233\276.png" "b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277\345\256\236\347\211\251\345\233\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..8edc1b068d07027c07f3e0faf6be1cc8f7992789 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/bg95\346\240\270\345\277\203\346\235\277\345\256\236\347\211\251\345\233\276.png" differ diff --git a/docs/Dev_board_guide/zh/media/bg-eg-core-evb/hello_world.png b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/hello_world.png new file mode 100644 index 0000000000000000000000000000000000000000..3cdaaabd822577470dee509287b891ee748dead9 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg-eg-core-evb/hello_world.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/BG95.png b/docs/Dev_board_guide/zh/media/bg95/BG95.png new file mode 100644 index 0000000000000000000000000000000000000000..9d21c0187122f19cd92c7c35fd95cbf7b4b550f3 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/BG95.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/BG95_EVB.png b/docs/Dev_board_guide/zh/media/bg95/BG95_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..b909ea568e7bdab28e89685499db7f52ccb11c86 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/BG95_EVB.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/BG95_layout.png b/docs/Dev_board_guide/zh/media/bg95/BG95_layout.png new file mode 100644 index 0000000000000000000000000000000000000000..e2f82c6386b3518544dede2ad020b0dbf72609c6 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/BG95_layout.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/PowerMonitor_connect.png b/docs/Dev_board_guide/zh/media/bg95/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..801b825f80559c3cad916bfd2a67d73e95b25382 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/close_power.png b/docs/Dev_board_guide/zh/media/bg95/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..e5d40f3023ec18391ccc2e2c1ef3186755a6c0ad Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/close_power.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/free_power.png b/docs/Dev_board_guide/zh/media/bg95/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..c8bd75b51ff004c0c5ee9186c2018c604551d14a Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/free_power.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/open_auto_sleep.png b/docs/Dev_board_guide/zh/media/bg95/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..dbdbb95878679ef136aa2a91d4c3727adafd5c3b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/psm_power1.png b/docs/Dev_board_guide/zh/media/bg95/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..bca71ae7c9a149dd85b334ac090bbee8fd2005a6 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/psm_power1.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/set_psmmode.png b/docs/Dev_board_guide/zh/media/bg95/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..cea9e0afbf9600094a51ba00e55fa596e884816a Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/set_psmmode.png differ diff --git a/docs/Dev_board_guide/zh/media/bg95/sleep_power.png b/docs/Dev_board_guide/zh/media/bg95/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..13d4a3b578865a472484f5d4fcce54b317fcc96a Binary files /dev/null and b/docs/Dev_board_guide/zh/media/bg95/sleep_power.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/200U-1.png b/docs/Dev_board_guide/zh/media/ec200x-evb/200U-1.png new file mode 100644 index 0000000000000000000000000000000000000000..9adbfcaeebf992e611ec6f8cfa80cd167113368c Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/200U-1.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/200U-chicun.png b/docs/Dev_board_guide/zh/media/ec200x-evb/200U-chicun.png new file mode 100644 index 0000000000000000000000000000000000000000..b7ec5264f373c4808f330b04f2f43c1b98b53c66 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/200U-chicun.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/EC200U.png b/docs/Dev_board_guide/zh/media/ec200x-evb/EC200U.png new file mode 100644 index 0000000000000000000000000000000000000000..9b7e2e463c7f3eca571b628ddbcc8a7c264da3a9 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/EC200U.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/EC200X_EVB.png b/docs/Dev_board_guide/zh/media/ec200x-evb/EC200X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..af9690fddaa36e581cb3443e5752502ad4278f54 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/EC200X_EVB.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/PowerMonitor_connect.png b/docs/Dev_board_guide/zh/media/ec200x-evb/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..a04b96501fd856c54beaaccbdfd85881c07a7e10 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/close_power.png b/docs/Dev_board_guide/zh/media/ec200x-evb/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..0d9e71ed0f661443dba8e4b95e566e53e7a87192 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/close_power.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/free_power.png b/docs/Dev_board_guide/zh/media/ec200x-evb/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..ab6d44f293b210bc712718629e7c34d8cc3455cc Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/free_power.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/open_auto_sleep.png b/docs/Dev_board_guide/zh/media/ec200x-evb/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..dbdbb95878679ef136aa2a91d4c3727adafd5c3b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/psm_power1.png b/docs/Dev_board_guide/zh/media/ec200x-evb/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..bca71ae7c9a149dd85b334ac090bbee8fd2005a6 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/psm_power1.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/set_psmmode.png b/docs/Dev_board_guide/zh/media/ec200x-evb/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..cea9e0afbf9600094a51ba00e55fa596e884816a Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/set_psmmode.png differ diff --git a/docs/Dev_board_guide/zh/media/ec200x-evb/sleep_power.png b/docs/Dev_board_guide/zh/media/ec200x-evb/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..46a5a58146809fd3b6dd6a7b20b2b583a02fa5a4 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec200x-evb/sleep_power.png differ diff --git a/docs/Dev_board_guide/zh/media/ec2x-evb/EC2X_EVB.png b/docs/Dev_board_guide/zh/media/ec2x-evb/EC2X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..cabe23b2fdfd81dc45d1a047bb38c07720dd5298 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec2x-evb/EC2X_EVB.png differ diff --git a/docs/Dev_board_guide/zh/media/ec2x-evb/peripheral-interfaces.png b/docs/Dev_board_guide/zh/media/ec2x-evb/peripheral-interfaces.png new file mode 100644 index 0000000000000000000000000000000000000000..20eed04162bac89084a70f09ec5bb636f0f2db3c Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec2x-evb/peripheral-interfaces.png differ diff --git a/docs/Dev_board_guide/zh/media/ec2x-evb/pin-layout.png b/docs/Dev_board_guide/zh/media/ec2x-evb/pin-layout.png new file mode 100644 index 0000000000000000000000000000000000000000..5da9cc5985966319aab129c9158adb43e8a4ceb6 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec2x-evb/pin-layout.png differ diff --git a/docs/Dev_board_guide/zh/media/ec600u-235-evb/image7.png b/docs/Dev_board_guide/zh/media/ec600u-235-evb/image7.png new file mode 100644 index 0000000000000000000000000000000000000000..87a512af1d06fe4458bfa3b0ab40f1af7df025d6 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec600u-235-evb/image7.png differ diff --git a/docs/Dev_board_guide/zh/media/ec600u-235-evb/image8.jpg b/docs/Dev_board_guide/zh/media/ec600u-235-evb/image8.jpg new file mode 100644 index 0000000000000000000000000000000000000000..53b8d3285266c0b6084d5fc81d58b3dcfc5e633b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec600u-235-evb/image8.jpg differ diff --git "a/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" new file mode 100644 index 0000000000000000000000000000000000000000..4826d33fd73a0f45f20b9cdd58943ed14cb95310 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\344\272\247\345\223\201\345\212\237\350\203\275.png" differ diff --git "a/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" new file mode 100644 index 0000000000000000000000000000000000000000..ef892d5f47c345af78722b8febff76e765343f61 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\345\256\207.png" differ diff --git "a/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" new file mode 100644 index 0000000000000000000000000000000000000000..bfa14eb15ba710988ae864ac9def5829b56c1106 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\347\206\265.png" differ diff --git "a/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" new file mode 100644 index 0000000000000000000000000000000000000000..5e49122f966e1ec02c1a98e8d386a3dc85c99dda Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\350\275\251.png" differ diff --git "a/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" new file mode 100644 index 0000000000000000000000000000000000000000..7be45005ebbdcfa48c72567a460175f532575044 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec600x-ec800x-core-evb/\346\240\270\345\277\203\346\235\277-\351\224\265.png" differ diff --git a/docs/Dev_board_guide/zh/media/ec600x-evb/600Ufunction.png b/docs/Dev_board_guide/zh/media/ec600x-evb/600Ufunction.png new file mode 100644 index 0000000000000000000000000000000000000000..edf77b65885348925f2dbe256d04abceb4463c6d Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec600x-evb/600Ufunction.png differ diff --git a/docs/Dev_board_guide/zh/media/ec600x-evb/600Uperipheral.png b/docs/Dev_board_guide/zh/media/ec600x-evb/600Uperipheral.png new file mode 100644 index 0000000000000000000000000000000000000000..fb1e18bb9017aabc92a68b5df3ff7b7018d71427 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec600x-evb/600Uperipheral.png differ diff --git a/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/DTU_wires_connection.png b/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/DTU_wires_connection.png new file mode 100644 index 0000000000000000000000000000000000000000..aa1735693b58f1771d2db976b02ff4b51288e9bc Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/DTU_wires_connection.png differ diff --git a/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/work.png b/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/work.png new file mode 100644 index 0000000000000000000000000000000000000000..91210af335628503d36c23e632c5eb86a3c13c1f Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800g_hua_dtu/work.png differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/dp-dtu-q600r.png b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/dp-dtu-q600r.png new file mode 100644 index 0000000000000000000000000000000000000000..67aa6a1524698ee12f76bc64f30547408fc9f6b5 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/dp-dtu-q600r.png differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/hello_world.png b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/hello_world.png new file mode 100644 index 0000000000000000000000000000000000000000..3cdaaabd822577470dee509287b891ee748dead9 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/hello_world.png differ diff --git "a/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/\346\270\262\346\237\223\345\233\276.png" "b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/\346\270\262\346\237\223\345\233\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..089f5ccff3c21dcc4adc1e0f511b958450e06470 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec800x-dp-dtu-q600r/\346\270\262\346\237\223\345\233\276.png" differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-duino-evb/layout.jpg b/docs/Dev_board_guide/zh/media/ec800x-duino-evb/layout.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f075f7eab1dabc8e6d389b89c079e9cb390f81bb Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-duino-evb/layout.jpg differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-duino-evb/pin.jpg b/docs/Dev_board_guide/zh/media/ec800x-duino-evb/pin.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f33d98826c6e57a5e05c4a796d800defbe45d748 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-duino-evb/pin.jpg differ diff --git "a/docs/Dev_board_guide/zh/media/ec800x-evb/800M\345\244\226\350\256\276.png" "b/docs/Dev_board_guide/zh/media/ec800x-evb/800M\345\244\226\350\256\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..91035d978a7b87e86b9582b8626f27b1e5e0e2dc Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec800x-evb/800M\345\244\226\350\256\276.png" differ diff --git "a/docs/Dev_board_guide/zh/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" "b/docs/Dev_board_guide/zh/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" new file mode 100644 index 0000000000000000000000000000000000000000..8218d71107172754e9cc4bdf97e1cacc3bc88e2e Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec800x-evb/800X_\344\272\247\345\223\201\345\212\237\350\203\275.png" differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-pico-evb/hello.png b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/hello.png new file mode 100644 index 0000000000000000000000000000000000000000..c6f6fe562768a432191fee53f38e80288c7be4b7 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/hello.png differ diff --git a/docs/Dev_board_guide/zh/media/ec800x-pico-evb/pin.png b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/pin.png new file mode 100644 index 0000000000000000000000000000000000000000..97d0e7ed08daf5ae5dfd601842a539b29194dab2 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/pin.png differ diff --git "a/docs/Dev_board_guide/zh/media/ec800x-pico-evb/\346\270\262\346\237\223\345\233\276.png" "b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/\346\270\262\346\237\223\345\233\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..15e82958bab3c085f33230d3f6e8cc8b5fca33a4 Binary files /dev/null and "b/docs/Dev_board_guide/zh/media/ec800x-pico-evb/\346\270\262\346\237\223\345\233\276.png" differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/915U_chicun.png b/docs/Dev_board_guide/zh/media/eg91x-evb/915U_chicun.png new file mode 100644 index 0000000000000000000000000000000000000000..64bd4948171afb8970c8047094caecb69145bf23 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/915U_chicun.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U.png b/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U.png new file mode 100644 index 0000000000000000000000000000000000000000..51ffcfc8723c577dcc22af5d78c8b2b05f40ddbb Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U_1.png b/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U_1.png new file mode 100644 index 0000000000000000000000000000000000000000..bfcfe4fa65b1649d45dae669426a1b5e6ab6f006 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/EG915U_1.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/EG91X_EVB.png b/docs/Dev_board_guide/zh/media/eg91x-evb/EG91X_EVB.png new file mode 100644 index 0000000000000000000000000000000000000000..25a7046cfd97de1269569ddc353a0110c037bfd2 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/EG91X_EVB.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/PowerMonitor_connect.png b/docs/Dev_board_guide/zh/media/eg91x-evb/PowerMonitor_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..9dafccbaed1d72e2f8d3ac791a4ab81b736387b8 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/PowerMonitor_connect.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/close_power.png b/docs/Dev_board_guide/zh/media/eg91x-evb/close_power.png new file mode 100644 index 0000000000000000000000000000000000000000..6465452ee59cf936c15b263fe0990a94ab9fa64b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/close_power.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/free_power.png b/docs/Dev_board_guide/zh/media/eg91x-evb/free_power.png new file mode 100644 index 0000000000000000000000000000000000000000..bfdee0a862df11e077f305470d266ac326053a0b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/free_power.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/open_auto_sleep.png b/docs/Dev_board_guide/zh/media/eg91x-evb/open_auto_sleep.png new file mode 100644 index 0000000000000000000000000000000000000000..dbdbb95878679ef136aa2a91d4c3727adafd5c3b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/open_auto_sleep.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/psm_power1.png b/docs/Dev_board_guide/zh/media/eg91x-evb/psm_power1.png new file mode 100644 index 0000000000000000000000000000000000000000..2292fdecb8fd9a82e1eb823e2ee199edfdccb1a4 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/psm_power1.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/set_psmmode.png b/docs/Dev_board_guide/zh/media/eg91x-evb/set_psmmode.png new file mode 100644 index 0000000000000000000000000000000000000000..cea9e0afbf9600094a51ba00e55fa596e884816a Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/set_psmmode.png differ diff --git a/docs/Dev_board_guide/zh/media/eg91x-evb/sleep_power.png b/docs/Dev_board_guide/zh/media/eg91x-evb/sleep_power.png new file mode 100644 index 0000000000000000000000000000000000000000..136e53d87884a5d51861134979f434b2e518b04b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/eg91x-evb/sleep_power.png differ diff --git a/docs/Dev_board_guide/zh/media/fcm360w-evb/hello.png b/docs/Dev_board_guide/zh/media/fcm360w-evb/hello.png new file mode 100644 index 0000000000000000000000000000000000000000..a15a3e13a3556519e908bec15822aa7d987afd0e Binary files /dev/null and b/docs/Dev_board_guide/zh/media/fcm360w-evb/hello.png differ diff --git a/docs/Dev_board_guide/zh/media/fcm360w-evb/peripheral-interfaces.png b/docs/Dev_board_guide/zh/media/fcm360w-evb/peripheral-interfaces.png new file mode 100644 index 0000000000000000000000000000000000000000..a1aec0b7d70d7c368e9c526b9024376963320426 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/fcm360w-evb/peripheral-interfaces.png differ diff --git a/docs/Dev_board_guide/zh/media/fcm360w-evb/pin-layout.png b/docs/Dev_board_guide/zh/media/fcm360w-evb/pin-layout.png new file mode 100644 index 0000000000000000000000000000000000000000..fdd2d5d18f54d4c24e0fe35ca69beacd1451795b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/fcm360w-evb/pin-layout.png differ diff --git a/docs/Dev_board_guide/zh/media/fcm360w-teb/fcm360w-teb.png b/docs/Dev_board_guide/zh/media/fcm360w-teb/fcm360w-teb.png new file mode 100644 index 0000000000000000000000000000000000000000..7af23b39de9bedb34b77d3f79411fe12b13264a0 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/fcm360w-teb/fcm360w-teb.png differ diff --git a/docs/Dev_board_guide/zh/media/fcm360w-teb/hello.png b/docs/Dev_board_guide/zh/media/fcm360w-teb/hello.png new file mode 100644 index 0000000000000000000000000000000000000000..a15a3e13a3556519e908bec15822aa7d987afd0e Binary files /dev/null and b/docs/Dev_board_guide/zh/media/fcm360w-teb/hello.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/Firmware.png b/docs/Dev_board_guide/zh/media/readme/Firmware.png new file mode 100644 index 0000000000000000000000000000000000000000..8fa0e5e35d5a1a926de8df530450603255848242 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/Firmware.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/QPYcom_drag.jpg b/docs/Dev_board_guide/zh/media/readme/QPYcom_drag.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8678c5d18990316aa968b93fe24785882df71573 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/QPYcom_drag.jpg differ diff --git a/docs/Dev_board_guide/zh/media/readme/QPYcom_hello.jpg b/docs/Dev_board_guide/zh/media/readme/QPYcom_hello.jpg new file mode 100644 index 0000000000000000000000000000000000000000..345a7974e28a9b1252caf00f2454e7e86b554c9b Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/QPYcom_hello.jpg differ diff --git a/docs/Dev_board_guide/zh/media/readme/QPYcom_repl_hello.png b/docs/Dev_board_guide/zh/media/readme/QPYcom_repl_hello.png new file mode 100644 index 0000000000000000000000000000000000000000..80dca4c0423448fc8e1a00e8bf0e062be2246d75 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/QPYcom_repl_hello.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/QPYcom_sc_1.jpg b/docs/Dev_board_guide/zh/media/readme/QPYcom_sc_1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..76d02573f99e75df90c4bde5c95301a9c42fd0f0 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/QPYcom_sc_1.jpg differ diff --git a/docs/Dev_board_guide/zh/media/readme/VScode_1.png b/docs/Dev_board_guide/zh/media/readme/VScode_1.png new file mode 100644 index 0000000000000000000000000000000000000000..52b9d3f613666906af695452b2089fc642b56856 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/VScode_1.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/VScode_2.png b/docs/Dev_board_guide/zh/media/readme/VScode_2.png new file mode 100644 index 0000000000000000000000000000000000000000..d57dfd2ef141a733becdd3de48198d56fdb62dff Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/VScode_2.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/driver_after.jpg b/docs/Dev_board_guide/zh/media/readme/driver_after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3e1053c6c7f86c3cf81e08e211c1fa925467f5a5 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/driver_after.jpg differ diff --git a/docs/Dev_board_guide/zh/media/readme/driver_eg912u.png b/docs/Dev_board_guide/zh/media/readme/driver_eg912u.png new file mode 100644 index 0000000000000000000000000000000000000000..1f1d4cee83e4ad5ff4841a9275aa696d9c2e4be4 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/driver_eg912u.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/firmware.gif b/docs/Dev_board_guide/zh/media/readme/firmware.gif new file mode 100644 index 0000000000000000000000000000000000000000..38b25f7d97d52e8b5a280750b0806e84d6631aa4 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/firmware.gif differ diff --git a/docs/Dev_board_guide/zh/media/readme/firmware_zip.png b/docs/Dev_board_guide/zh/media/readme/firmware_zip.png new file mode 100644 index 0000000000000000000000000000000000000000..5a5c7e81e17821cfb80c0e54a71e399d1333cdbe Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/firmware_zip.png differ diff --git a/docs/Dev_board_guide/zh/media/readme/hello_world.png b/docs/Dev_board_guide/zh/media/readme/hello_world.png new file mode 100644 index 0000000000000000000000000000000000000000..f370f4b6efe05a416c4bb878e4376534f6c07551 Binary files /dev/null and b/docs/Dev_board_guide/zh/media/readme/hello_world.png differ diff --git a/docs/Dev_board_guide/zh/sidebar.yaml b/docs/Dev_board_guide/zh/sidebar.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ad953a01961b6d63274203d0c124d4883888f55 --- /dev/null +++ b/docs/Dev_board_guide/zh/sidebar.yaml @@ -0,0 +1,33 @@ +items: +- label: QuecPython开发板操作指南 + file: ./README.md +- label: EC2X 开发板介绍 + file: ./ec2x-evb.md +- label: EC600X 开发板介绍 + file: ec600x-evb.md +- label: EC800X 开发板介绍 + file: ec800x-evb.md +- label: EC800X-DP-DTU-Q600R 开发板介绍 + file: ec800x-dp-dtu-q600r.md +- label: EC800X_pico 开发板介绍 + file: ec800x-pico-evb.md +- label: EC600X/EC800X 核心板介绍 + file: ec600x-ec800x-core-evb.md +- label: BG95 开发板介绍 + file: bg95-evb.md +- label: EC200X 开发板介绍 + file: ec200x-evb.md +- label: EG91X 开发板介绍 + file: eg91x-evb.md +- label: FCM360W 开发板介绍 + file: fcm360w-evb.md +- label: FCM360W TE-B开发板介绍 + file: fcm360w-teb.md +- label: EC600U 铀 235 开发板介绍 + file: ec600u-235.md +- label: BG95/EG915U/EG912U 核心板介绍 + file: bg-eg-core-evb.md +- label: EC800G 华 DTU 开发板介绍 + file: ec800g_hua_dtu.md +- label: EC800X Duino 开发板介绍 + file: ec800x-duino-evb.md \ No newline at end of file