### Build and start the Docker container Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_linux.html Build the Docker image and start the container using the provided scripts. ```bash bash build.sh sh run.sh ``` -------------------------------- ### Example: Build a list of strings using arg Source: https://pikadoc-en.readthedocs.io/en/latest/coreapi_arg.html Example showing how to create a list object, initialize it, create an arg with arg_newStr, append it to the list, and destroy the arg. Includes a comment to include PikaStdData_List.h. ```c ## Include "PikaStdData_List.h" ... /* Create a list object */ PikaObj* list = newNormalObj(New_PikaStdData_List); /* initialize list */ PikaStdData_List___init__(list); /* Create arg with api of arg_new */ Arg* str_arg1 = arg_newStr("aaa"); /* add to list object */ PikaStdData_List_append(list, str_arg1); /* destroy arg */ arg_deinit(str_arg1); ... ``` -------------------------------- ### Install requests via requirements.txt Source: https://pikadoc-en.readthedocs.io/en/latest/lib_requests.html Add 'requests' to your requirements.txt file to install the module. ```text requests ``` -------------------------------- ### Example packages.toml with package releases Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8C%85%E7%AE%A1%E7%90%86%E5%99%A8%E4%B8%8E%E6%A8%A1%E5%9D%97%E7%AE%A1%E7%90%86.html Example configuration file for the PikaPackage manager. Lists packages (pikascript-core, PikaStdLib, PikaStdDevice, STM32) with their release versions and commit IDs. Used to publish modules so the package manager can recognize them. ```toml [[packages]] name = "pikascript-core" releases = [ "v0.8.1 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v0.8.2 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v0.8.3 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v0.9.0 332ef8afb0692cddd194782a07e30f2688d0f813", "v0.10.0 c86eaefa4516dd82b1050fa74a7d85399459d5ed", "v1.0.0 7b816b1546ef91a03f77760d4b10806ab956d452", "v1.1.0 845d1fc6520237e2238087800f72608dcb81afa6", "v1.1.1 c77e42450ed0eb09fcd7bb2b7d7c2b7eeeb55a2e", "v1.1.2 f6ad2c78f49162ab3f898abc6a0a4d87777ce655", "v1.1.3 6539072bf7bebb242ea40f8595bfb5c9aae3de7f", "v1.2.0 ce3df083b68fbfc85e64e6793fe07a6736d6f29f", "v1.2.1 e29a77527fd753c4eb811b047899534472bfc8ec", "v1.2.2 5316ede928b01a20571103616a64666abbc40e0a", "v1.2.3 5ae86929851ff6a62342a7072b77e9cf5be85f1c", "v1.2.4 b7ac057d75e88736cc844de0bafb447a48f2fb6d", "v1.2.5 db51f0520a673074a14ef0f5c4434da0d5c3425f", "v1.2.6 044a2a8f0905c6ca90c633759f397323ce57eefd", ] [[packages]] name = "PikaStdLib" releases = [ "v1.0.1 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v1.1.0 0b3b866dbacc363c7b6b3899faa0cbcaccd59d5e", "v1.2.0 ca29e112687525ee7511bd30418d368754627a00", "v1.2.1 5ae86929851ff6a62342a7072b77e9cf5be85f1c", "v1.2.2 b7ac057d75e88736cc844de0bafb447a48f2fb6d", ] [[packages]] name = "PikaStdDevice" releases = [ "v1.3.0 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v1.4.0 29c3c5b3b0cb4d3e41e6a2a0aef9e2826bc6f7ba", "v1.4.1 6539072bf7bebb242ea40f8595bfb5c9aae3de7f", "v1.4.2 5ae86929851ff6a62342a7072b77e9cf5be85f1c", ] [[packages]] name = "STM32" releases = [ "v1.0.0 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v1.0.1 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v1.0.2 af42fd61884dc7048628b0d3bafaa42697f6e8ea", "v1.1.0 a18910b5dc349c64297bba3a13b7044f41d48e5f", "v1.1.1 91818aab0fa87b007e84866d479af5ac507339fe", "v1.2.0 6bd4aac6e9aba2a603da602be8583021da1272c0", "v1.3.0 7b816b1546ef91a03f77760d4b10806ab956d452", "v1.4.0 29c3c5b3b0cb4d3e41e6a2a0aef9e2826bc6f7ba", "v1.4.1 6539072bf7bebb242ea40f8595bfb5c9aae3de7f", "v1.4.2 8866710f653ad005f5c3edc5e6417ad31075b7d5", "v2.0.0 e29a77527fd753c4eb811b047899534472bfc8ec", "v2.0.1 5ae86929851ff6a62342a7072b77e9cf5be85f1c", ] ``` -------------------------------- ### main.py example script Source: https://pikadoc-en.readthedocs.io/en/latest/Keil%20%E4%BB%BF%E7%9C%9F%E5%B7%A5%E7%A8%8B.html Example main.py script that imports Device and PikaStdLib, creates LED, Uart, and MemChecker objects, prints a greeting, sets the UART name, sends a message, prints the name, and checks memory usage. ```python # main.py import Device import PikaStdLib led = Device.LED() uart = Device.Uart() mem = PikaStdLib.MemChecker() print('hello wrold') uart.setName('com1') uart.send('My name is:') uart.printName() print('mem used max:') mem.max() print('mem used now:') mem.now() ``` -------------------------------- ### connect() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Connects to the MQTT server. No parameters are required. Returns 0 on success or an error code. ```python c.connect() ``` -------------------------------- ### requestment.txt module description example Source: https://pikadoc-en.readthedocs.io/en/latest/%E4%BD%BF%E7%94%A8%20BSP%20%E5%B7%A5%E7%A8%8B.html Example of a requestment.txt file that specifies the modules to be pulled by the package manager. It includes the kernel, standard library, and peripheral modules with version constraints. ```text pikascript-core==v1.10.0 PikaStdLib PikaStdDevice==v1.6.0 STM32G0==v1.2.0 PikaPiZero==v1.1.3 ``` -------------------------------- ### MemChecker usage example Source: https://pikadoc-en.readthedocs.io/en/latest/PikaStdLib%20%E6%A0%87%E5%87%86%E5%BA%93.html Example demonstrating how to use MemChecker to track and reset memory usage. ```python # main.py import PikaStdLib mem = PikaStdLib.MemChecker() print('mem used max:') mem.max() print('mem used now:') mem.resetMax() print('mem used max:' + str(mem.getMax())) print('mem used now:' + str(mem.getNow())) ``` -------------------------------- ### LVGL Button Event Callback Example Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_lvgl.html An example demonstrating how to define event callbacks for buttons and register them using add_event_cb. ```python # lv_callback1.py import pika_lvgl as lv import PikaStdLib mem = PikaStdLib.MemChecker() def event_cb_1(evt): print('in evt1') print('mem used now: %0.2f kB' % (mem.getNow())) def event_cb_2(evt): print('in evt2') print('mem used now: %0.2f kB' % (mem.getNow())) btn1 = lv.btn(lv.scr_act()) btn1.align(lv.ALIGN.TOP_MID, 0, 10) btn2 = lv.btn(lv.scr_act()) btn2.align(lv.ALIGN.TOP_MID, 0, 50) btn1.add_event_cb(event_cb_1, lv.EVENT.CLICKED, 0) btn2.add_event_cb(event_cb_2, lv.EVENT.CLICKED, 0) print('mem used max: %0.2f kB' % (mem.getMax())) print('mem used now: %0.2f kB' % (mem.getNow())) ``` -------------------------------- ### Initialize PikaPython in main.c Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_cmsis-pack.html Start PikaPython after system initialization and printf by calling pikaScriptInit(). ```c PikaObj *pikaMain = pikaScriptInit(); ``` -------------------------------- ### Run the REPL Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_linux.html Start the PikaPython REPL within the container. ```bash sh run.sh ``` -------------------------------- ### Debug logging example with commands Source: https://pikadoc-en.readthedocs.io/en/latest/PikaDebug%20%E8%B0%83%E8%AF%95%E5%99%A8.html Shows a debug session with commands n, p, print, i =, and q, and the corresponding output. ```text # Debug logging example i : 1 (pika-debug) n i : 2 (pika-debug) n i : 3 (pika-debug) n i : 4 (pika-debug) p i 4 (pika-debug) print(i) 4 (pika-debug) i = 2 (pika-debug) n i : 3 (pika-debug) n i : 4 (pika-debug) i = 9 (pika-debug) n i : 10 (pika-debug) i = 2 (pika-debug) n i : 3 (pika-debug) q i : 4 i : 5 i:6 i : 7 i :8 i :9 i : 10 ``` -------------------------------- ### Example Test Case: String Startswith Source: https://pikadoc-en.readthedocs.io/en/latest/contribute_to_stdlib.html A test case demonstrating string method validation using obj_run and EXPECT_EQ. ```cpp TEST(pikaMain, string_startswith) { /* init */ pikaMemInfo.heapUsedMax = 0; PikaObj* pikaMain = newRootObj("pikaMain", New_PikaMain); /* run */ obj_run(pikaMain, "a = PikaStdData.String('test')\n" "res1 = a.starswith('te')\n" "res2 = a.startswith('st')\n" ); /* collect */ int res1 = obj_getInt(pikaMain, "res1"); int res2 = obj_getInt(pikaMain, "res2"); /* assert */ EXPECT_EQ(res1, 1); EXPECT_EQ(res2, 0); /* deinit */ obj_deinit(pikaMain); EXPECT_EQ(pikaMemNow(), 0); } ``` -------------------------------- ### ByteArray usage example Source: https://pikadoc-en.readthedocs.io/en/latest/PikaStdData%20%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84.html Demonstrates initializing a ByteArray, iterating over it, appending values, and accessing elements by index. ```python >>> bytes = PikaStdData.ByteArray(b'test') >>> for byte in bytes: ... print(byte) ... 116 101 115 116 >>> bytes.append(0xff) >>> bytes.append(0x0f) >>> print(bytes[4]) 255 >>> print(bytes[5]) 15 ``` -------------------------------- ### MQTT __init__() examples Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Shows various ways to instantiate an MQTT client, from minimal to encrypted connections. The constructor accepts ip (required), port (default 1883), clientID (default MAC), username, password, version (default MQTT-3.1.1), ca, and keepalive (default 60). ```python # Minimalist creation c = MQTT("broker-cn.emqx.io") # Create a custom port c = MQTT("broker-cn.emqx.io", 1111) # Create a custom clientID c = MQTT("broker-cn.emqx.io", clientID="pikascript") # Requires the creation of a user name and password c = MQTT("broker-cn.emqx.io", username="pikascript123", password="123456") # The creation of an encrypted mqtt c = MQTT("broker-cn.emqx.io", 8883, username="pikascript123", password="123456", ca=open(cert_file).read()) ``` -------------------------------- ### Comprehensive MQTT example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Comprehensive example showing MQTTS connection to broker-cn.emqx.io on port 8883 with client ID "pikaone", username, password, and CA certificate. It sets a will message, a disconnect handler, subscribes to three topics with different QoS levels, publishes messages, lists subscribed topics, and disconnects. The test() function is called at the end. ```python # coding=utf-8 def sub_test1_cb(evt): print("sub test1 message:", evt.msg) def sub_test2_cb(evt): print("sub test2 message:", evt.msg) def sub_test3_cb(evt): print("sub test3 message:", evt.msg) def disconnect_cb(): print("mqtt disconnect") def test(): # MQTTS c = MQTT("broker-cn.emqx.io", 8883, clientID="pikaone", username="pikascript123", password="123456", ca=open("/ca.crt").read()) # Test a mentary c.setWill("/device/will", "{"name":"pikascript"}", 0, True) # Set the dis connection callback c.setDisconnectHandler(disconnect_cb) # connect to server result = c.connect() if result == 0: print("connect success!") else: print("connect faild id={}".format(result)) return # Subscribe to a subject c.subscribe("/pikascript/test1", sub_test1_cb, 0) c.subscribe("/pikascript/test2", sub_test2_cb, 1) c.subscribe("/pikascript/test3", sub_test3_cb, 2) print("list subscribe topics:") print(c.listSubscribeTopics()) print("start publish") # Send topic message c.publish("/pikascript/test1", "{'msg'}:'hello from test1'", 0) c.publish("/pikascript/test2", "{'msg'}:'hello from test2'", 1) c.publish("/pikascript/test3", "{'msg'}:'hello from test3'", 2) print("end publish") # Discount result = c.disconnect() if result == 0: print("disconnect success!") else: print("disconnect faild id={}".format(result)) return # run test() ``` -------------------------------- ### Import and use PikaStdData C module in main.py Source: https://pikadoc-en.readthedocs.io/en/latest/module_import.html The first block shows the PikaStdData.pyi interface file, which declares a List class with methods for appending, getting, setting, and returning the length. The second block is a main.py example that imports PikaStdData, creates a List object, appends mixed-type values, and prints them to verify the C module binding. ```python # PikaStdData.pyi class List: def __init__(self): ... # add an arg after the end of list def append(self, arg: any): ... # get an arg by the index def get(self, i: int) -> any: ... # set an arg by the index def set(self, i: int, arg: any): ... # get the length of list def len(self) -> int: ... ... ``` ```python import PikaStdLib import PikaStdData print('test start...') list = PikaStdData.List() list.append(1) list.append('test') list.append(2.34) print(list.get(0)) print(list.get(1)) print(list.get(2)) print('test end...') ``` -------------------------------- ### listSubscribeTopics() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Lists the topics to which the client is currently subscribed. Returns a tuple of topics. ```python t = c.listSubscribeTopics() print(t) ``` -------------------------------- ### Registering callback functions in Python Source: https://pikadoc-en.readthedocs.io/en/latest/coreapi_event.html Example of defining a callback function and registering it with a TemplateDevice GPIO instance. ```python import TemplateDevice io1 = TemplateDevice.GPIO() io1.setPin('PA8') io1.setMode('in') io1.enable() EVENT_SIGAL_IO_RISING_EDGE = 0x01 EVENT_SIGAL_IO_FALLING_EDGE = 0x02 def callBack1(signal): if signal == EVENT_SIGAL_IO_RISING_EDGE: print('get rising edge!') elif signal == EVENT_SIGAL_IO_FALLING_EDGE: print('get falling edge!') io1.addEventCallBack(callBack1) ``` -------------------------------- ### Switch to PIKA_OPTIMIZE_SPEED in pika_config.h Source: https://pikadoc-en.readthedocs.io/en/latest/%E4%BC%98%E5%8C%96%E5%86%85%E5%AD%98%E5%8D%A0%E7%94%A8%E3%80%81%E9%85%8D%E7%BD%AE%20libc.html Example override in pika_config.h to switch from the default PIKA_OPTIMIZE_SIZE to speed optimization mode. ```c #define PIKA_OPTIMIZE PIKA_OPTIMIZE_SPEED ``` -------------------------------- ### Start interactive shell with pikaScriptShell() Source: https://pikadoc-en.readthedocs.io/en/latest/%E6%94%AF%E6%8C%81%E4%BA%A4%E4%BA%92%E5%BC%8F%E8%BF%90%E8%A1%8C.html Start the interactive PikaPython shell by passing the root object returned by pikaScriptInit() to pikaScriptShell(). This is the recommended way to launch interactive operation after implementing __platform_getchar(). ```c pikaScriptShell(pikaScriptInit()); ``` -------------------------------- ### Content-Type header configuration Source: https://pikadoc-en.readthedocs.io/en/latest/lib_requests.html Example of the Content-Type header string including the boundary definition. ```text Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrEPACvZYkAbE4bYB ``` -------------------------------- ### Add module entry to packages.toml Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%A6%82%E4%BD%95%E8%B4%A1%E7%8C%AE%20PikaScript%20%E6%A8%A1%E5%9D%97.html Example entry for packages.toml when adding a new module. Fill in the module name, version name, and current commit id after forking and committing. ```toml [[packages]] name = "" releases = [ " ", ] ``` -------------------------------- ### subscribe() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Subscribes to a topic with a callback function. The callback receives an event object with 'msg' and 'topic' attributes. The 'qos' parameter is optional and defaults to QOS0. ```python def sub_cb(evt): print(evt.msg, evt.topic) c.subscribe("/topic/sub", sub_cb) ``` -------------------------------- ### Example Test Case: Signed Integer Source: https://pikadoc-en.readthedocs.io/en/latest/contribute_to_stdlib.html A typical test case demonstrating object initialization, script execution, and assertion. ```cpp TEST(pikaMain, a_signed) { /* init */ pikaMemInfo.heapUsedMax = 0; PikaObj* pikaMain = newRootObj("pikaMain", New_PikaMain); /* run */ obj_run(pikaMain, "a = -1\n"); /* collect */ int a = obj_getInt(pikaMain, "a"); /* assert */ EXPECT_EQ(-1, a); /* deinit */ obj_deinit(pikaMain); EXPECT_EQ(pikaMemNow(), 0); } ``` -------------------------------- ### publish() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Publishes a message to the MQTT topic "/topic/pub" with QoS 0. The payload is a JSON string. The function returns 0 on success or an error code from Attachment 1 on failure. ```python c.publish("/topic/pub", 0, "{"msg":"hello pikascript"}") ``` -------------------------------- ### Write main.py to test PikaPython Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8D%81%E5%88%86%E9%92%9F%E9%83%A8%E7%BD%B2%E5%88%B0%E6%96%B0%E5%B9%B3%E5%8F%B0.html Imports the standard library (mandatory even if unused) and prints a test message to verify PikaPython starts normally. ```python import PikaStdLib print('hello PikaPython!') ``` -------------------------------- ### Example request.txt file Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8C%85%E7%AE%A1%E7%90%86%E5%99%A8%E4%B8%8E%E6%A8%A1%E5%9D%97%E7%AE%A1%E7%90%86.html Lists module names and optional version numbers in pip-like format. Supports direct module names and strict version matching with '=='. The special version 'latest' pulls the latest master branch, but is discouraged for module users due to compatibility risks. ```text pikascript-core PikaStdLib PikaStdDevice==v1.6.0 STM32G0==v1.2.0 PikaPiZero==v1.1.3 ``` -------------------------------- ### Generic property APIs Source: https://pikadoc-en.readthedocs.io/en/latest/Pika%20%E5%AF%B9%E8%B1%A1%20PikaObj.html Set and get APIs for generic properties using Arg pointers. ```c int32_t obj_setArg(PikaObj* self, char* argPath, Arg* arg); Arg* obj_getArg(PikaObj* self, char* argPath); ``` -------------------------------- ### GPIO LED Blinking Example Source: https://pikadoc-en.readthedocs.io/en/latest/Pika%20%E6%B4%BE%E5%BC%80%E5%8F%91%E6%9D%BF%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B.html A Python script that initializes a GPIO pin and toggles it to blink an LED, while also printing memory usage statistics. ```python import PikaStdLib import machine mem = PikaStdLib.MemChecker() io1 = machine.GPIO() time = machine.Time() io1.init() io1.setPin('PA8') io1.setMode('out') io1.enable() io1.low() print('hello pikascript') print('mem.max:') mem.max() print('mem.now:') mem.now() while True: io1.low() time.sleep_ms(500) io1.high() time.sleep_ms(500) ``` -------------------------------- ### Modified main.py with new code Source: https://pikadoc-en.readthedocs.io/en/latest/Keil%20%E4%BB%BF%E7%9C%9F%E5%B7%A5%E7%A8%8B.html Modified main.py script that adds four new lines to the original example, demonstrating how to add new code and run it on the device. ```python import Device import PikaStdLib led = Device.LED() uart = Device.Uart() mem = PikaStdLib.MemChecker() print('hello wrold') uart.setName('com1') uart.send('My name is:') uart.printName() print('mem used max:') mem.max() print('mem used now:') mem.now() # new code start print('add new code start') uart.setName('com2') uart.printName() print('add new code end') # new code end ``` -------------------------------- ### setPassword() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the password, overriding the value provided at instantiation. The function returns true on success and false on failure. ```c c.setPassword("pikascript") ``` -------------------------------- ### Startup script in main.py (outermost method calls) Source: https://pikadoc-en.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html The startup script portion of main.py, which is written in the outermost method calls. This is the part that gets executed when the initialization function runs. ```python led = Device.LED() uart = Device.Uart() mem = PikaStdLib.MemChecker() print('hello wrold') uart.setName('com1') uart.send('My name is:') uart.printName() print('mem used max:') mem.max() print('mem used now:') mem.now() ``` -------------------------------- ### Define Adder class in Math.pyi Source: https://pikadoc-en.readthedocs.io/en/latest/Pikascript%20%E6%8B%93%E5%B1%95%E6%A8%A1%E5%9D%97%E5%BC%80%E5%8F%91%E6%B5%81%E7%A8%8B.html Example of defining an Adder class with integer and floating-point addition methods using pass. ```python # Math.pyi class Adder: def byInt(self, a:int, b:int)->int: pass def byFloat(self, a:float, b:float)->float: pass ``` -------------------------------- ### setUsername() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the username, overriding the value provided at instantiation. The function returns true on success and false on failure. ```c c.setUsername("pikascript") ``` -------------------------------- ### Keyword arguments: example output Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html Output of calling test.keys(1, b=2, c=3). Shows positional argument a=1 and keyword arguments keys['b']=2, keys['c']=3. ```python >>> test.keys(1, b=2, c=3) a: 1 keys['b']: 2 keys['c']: 3 >>> ``` -------------------------------- ### Example usage of PikaDebug.Debuger Source: https://pikadoc-en.readthedocs.io/en/latest/PikaDebug%20%E8%B0%83%E8%AF%95%E5%99%A8.html Shows how to import PikaDebug, create a Debuger object, and use set_trace() to set a breakpoint inside a loop. ```python import PikaDebug pkdb = PikaDebug.Debuger() i = 0 while i < 10: i = i + 1 print('i:' + str(i)) # set a breakpoint here pkdb.set_trace() ``` -------------------------------- ### setVersion() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the MQTT version, overriding the value provided at instantiation. The comment indicates that the version can be "3.1" or "3.1.1". The function returns true on success and false on failure. ```c # choosable "3.1" "3.1.1" c.setVersion("3.1") ``` -------------------------------- ### Constants: usage example Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html Shows how to use class constants directly without creating an object. Note that class properties are read-only. ```python print(cJSON.cJSON_Invalid) ``` -------------------------------- ### setClientID() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the client ID, overriding the value provided at instantiation. The function returns true on success and false on failure. ```c c.setClientID("pikascript") ``` -------------------------------- ### Make a GET request with requests.request Source: https://pikadoc-en.readthedocs.io/en/latest/lib_requests.html Call requests.request with method and URL to perform a GET request. ```python result = requests.request("GET", "http://pikascript.com/") ``` -------------------------------- ### Build and test commands for PikaPython standard library Source: https://pikadoc-en.readthedocs.io/en/latest/contribute_to_stdlib.html Commands to initialize, compile, test, and run the PikaPython standard library in the linux port. Run them in order: pull-core.sh updates the kernel source, init.sh pre-compiles and configures CMake, only_make.sh compiles, gtest.sh/ci_benchmark.sh/valgrind.sh run tests, and run.sh starts the REPL. ```sh sh pull-core.sh # Update kernel source code ``` ```sh sh init.sh ``` ```sh sh only_make.sh ``` ```sh sh gtest.sh # run google test sh ci_benchmark.sh # run benchmark sh valgrind.sh # run valgrind ``` ```sh sh run.sh # Start REPL ``` -------------------------------- ### Implement class methods with visibility access Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%A6%82%E4%BD%95%E8%B4%A1%E7%8C%AE%E5%86%85%E6%A0%B8.html Example of defining the __DATA_MEMORY_CLASS_IMPLEMENT__ macro before including the header to gain access to private members within the implementation file. ```c #define __DATA_MEMORY_CLASS_IMPLEMENT__ #include "dataMemory.h" #include "PikaPlatform.h" ... ``` -------------------------------- ### Create object and execute test script Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Demonstrates creating the root object, running a Python script to call the add method, retrieving the result, and cleaning up resources. ```c void main(){ // create a new root object PikaObj *root = newRootObj("root", New_MYROOT); //Run the script (also supports the calling method of "res = test.add(val1 = 1, val2= 2)") obj_run(root , "res = test.add(1, 2)"); // Get the attribute value res from the root object int res = obj_getInt(root, "res"); //destroy the root object obj_deinit(root); /* print return value res = 3*/ printf("%d\r\n", res); } ``` -------------------------------- ### MQTT.__init__() Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Constructor for creating an MQTT client instance with configurable connection parameters. ```APIDOC ## MQTT.__init__() ### Description Instantiate one MQTT Client with configurable connection parameters. ### Method Constructor ### Endpoint MQTT.__init__(ip, port=1883, clientID=None, username=None, password=None, version='MQTT-3.1.1', ca=None, keepalive=60) ### Parameters #### Arguments - **ip** (string) - Required - The MQTT broker IP address. - **port** (int) - Optional - The MQTT broker port. Default is 1883. - **clientID** (string) - Optional - The client identifier. Default is the MAC address. - **username** (string) - Optional - The username for authentication. Default is null. - **password** (string) - Optional - The password for authentication. Default is null. - **version** (string) - Optional - The MQTT protocol version. Default is 'MQTT-3.1.1'. - **ca** (string) - Optional - The CA certificate content for TLS. Default is empty. - **keepalive** (int) - Optional - The keepalive interval in seconds. Default is 60. ### Request Example ```python # Minimalist creation c = MQTT("broker-cn.emqx.io") # Create a custom port c = MQTT("broker-cn.emqx.io", 1111) # Create a custom clientID c = MQTT("broker-cn.emqx.io", clientID="pikascript") # Requires the creation of a user name and password c = MQTT("broker-cn.emqx.io", username="pikascript123", password="123456") # The creation of an encrypted mqtt c = MQTT("broker-cn.emqx.io", 8883, username="pikascript123", password="123456", ca=open(cert_file).read()) ``` ### Response #### Success Response - **mqtt event** (MQTT) - The instantiated MQTT client object. #### Response Example ```python c = MQTT("broker-cn.emqx.io") ``` ``` -------------------------------- ### Initialize the Linux port Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_linux.html Navigate to the Linux port directory and run the initialization scripts. ```bash cd port/linux sh pull-core.sh sh init.sh ``` -------------------------------- ### Dict.__getitem__ Source: https://pikadoc-en.readthedocs.io/en/latest/PikaStdData%20%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84.html Gets an argument from the dictionary by key. ```APIDOC ## Dict.__getitem__ ### Description Gets an argument from the dictionary by key. ### Method __getitem__ ### Signature `def __getitem__(self, key: str) -> any` ### Parameters - **key** (str) - Required - The key of the argument to get. ### Returns - **any** - The argument associated with the key. ### Example ```python dict = PikaStdData.Dict() dict['a'] = 1 value = dict['a'] # equivalent to dict.__getitem__('a') ``` ``` -------------------------------- ### List.__getitem__ Source: https://pikadoc-en.readthedocs.io/en/latest/PikaStdData%20%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84.html Gets an argument from the list by index. ```APIDOC ## List.__getitem__ ### Description Gets an argument from the list by index. ### Method __getitem__ ### Signature `def __getitem__(self, i: int) -> any` ### Parameters - **i** (int) - Required - The index of the argument to get. ### Returns - **any** - The argument at the specified index. ### Example ```python list = PikaStdData.List() list.append(1) item = list[0] # equivalent to list.__getitem__(0) ``` ``` -------------------------------- ### Run tests, benchmarks, and valgrind Source: https://pikadoc-en.readthedocs.io/en/latest/get-start_linux.html Execute the GoogleTest, benchmark, and valgrind scripts to verify the environment. ```bash sh gtest.sh sh ci_benchmark.sh sh valgrind.sh ``` -------------------------------- ### Basic usage of Args parameter list Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Demonstrates creating, modifying, retrieving, and destroying an Args parameter list. ```c // create a new parameter list Args *args = New_Args(); // Store an integer parameter a into the parameter list with a value of 1 args_setInt(args, "a", 1); // Take the parameter a, the value is 1 int a = args_getInt(args, "a"); // modify the value of a to 2 args_setInt(args, "a", 2); // Take out a again, the value is 2 a = args_getInt(args, "a"); // destroy the parameter list args_deinit(args); ``` -------------------------------- ### Make a GET request with requests.request Source: https://pikadoc-en.readthedocs.io/en/latest/lib_requests.html This snippet shows a basic GET request using the requests library in PikaPython. It passes the method, URL, query parameters, and headers. The response object provides content_length, text, header, and status_code. ```python result = requests.request("GET", "http://pikascript.com/package", params = {"name":"get-test"}, headers = {"Connection":"keep-alive"}) ``` -------------------------------- ### TemplateDevice GPIO override Source: https://pikadoc-en.readthedocs.io/en/latest/coreapi_event.html Example of overriding platformGetEventId in a TemplateDevice GPIO class. ```python # TemplateDevice.pyi class GPIO(PikaStdDevice.GPIO): # overrid ... def platformGetEventId(self): ... ... ``` -------------------------------- ### main.py: Create and animate an Arm2D box Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%9F%BA%E4%BA%8E%20ARM-2D%20%E7%9A%84%20GUI%20%E4%BB%BF%E7%9C%9F%E5%B7%A5%E7%A8%8B.html This is the main.py content for the simulation project. It creates a window and a box, sets the background color to white, and animates the box by moving, changing alpha, and resizing it in a loop. It also prints memory usage. Modify the color or coordinates to see changes, or create another element like win.elems.b2. ```python import PikaStdLib import Arm2D mem = PikaStdLib.MemChecker() win = Arm2D.Window() win.init() win.background.setColor('white') win.elems.b1 = Arm2D.Box() win.elems.b1.init() win.elems.b1.setColor('blue') win.elems.b1.move(100, 100) i = 0 x0 = 100 y0 = 100 sizeX0 = 50 sizeY0 = 50 alpha0 = 180 isIncrace = 1 loopTimes = 0 print('hello pikaScript') print('mem used max:') mem.max() print('mem used now:') mem.now() while True: win.elems.b1.move(x0 + i * 2, y0 + i * 1) win.elems.b1.setAlpha(alpha0 - i * 1) win.elems.b1.setSize(sizeX0 + i * 2, sizeY0 + i * 1) win.update() if isIncrace > 0: i = i + 1 if i > 160: isIncrace = 0 if isIncrace < 1: i = i - 1 if i < 0: isIncrace = 1 loopTimes = loopTimes + 1 ``` -------------------------------- ### Get type of generic property Source: https://pikadoc-en.readthedocs.io/en/latest/Pika%20%E5%AF%B9%E8%B1%A1%20PikaObj.html API to determine the current type of a generic property. ```c ArgType arg_getType(Arg* self); ``` -------------------------------- ### Module initialization: main.py Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html Python script that imports the module and calls hello(). Demonstrates delayed module loading. ```python # main.py import test print('before run test.hello()') test.hello() print('after run test.hello()') ``` -------------------------------- ### Module initialization: C implementation Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html C implementation of __init__ and hello functions. __init__ is triggered when the module is first used. ```c //test.c void test___init__(PikaObj* self){ printf("now loading module test...\n"); } void test_hello(PikaObj* self){ printf("hello!\n"); }; ``` -------------------------------- ### disconnect() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Disconnects from the MQTT server. No parameters are required. Returns 0 on success or an error code. ```python c.disconnect() ``` -------------------------------- ### Defining an event callback with a return value Source: https://pikadoc-en.readthedocs.io/en/latest/coreapi_event.html Example of a Python callback function that returns the received signal. ```python def callBack1(signal): return signal io1.addEventCallBack(callBack1) ``` -------------------------------- ### Construct SYS class with sub-objects Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Demonstrates how to import a class and mount a sub-object within a parent object's constructor. ```c PikaObj * New_SYS(Args *args){ // inherited from MimiObj base class PikaObj *self = New_PikaObj(args); // Import the LED class through the constructor of the LED class obj_import(self, "LED", New_LED); // Use the LED class to create a new led object, and the led object is used as a sub-object of the sys object obj_newObj(self, "led", "LED"); return self; } ``` -------------------------------- ### Invalid multi-line script block (incomplete block) Source: https://pikadoc-en.readthedocs.io/en/latest/%E6%94%AF%E6%8C%81%E4%BA%A4%E4%BA%92%E5%BC%8F%E8%BF%90%E8%A1%8C.html Example of a script that does not work because the while block content is missing. ```python # The content of the while block is missing while a < 10: ``` -------------------------------- ### Initialize and configure GPIO pin Source: https://pikadoc-en.readthedocs.io/en/latest/Pika%20%E6%B4%BE%E5%BC%80%E5%8F%91%E6%9D%BF%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B.html Initializes the GPIO object, sets pin PA8 to output mode, enables it, and sets the level low. ```python io1.init() io1.setPin('PA8') io1.setMode('out') io1.enable() io1.low() ``` -------------------------------- ### Concatenate URL with GET parameters Source: https://pikadoc-en.readthedocs.io/en/latest/lib_requests.html Demonstrates using the requests.request method to concatenate a URL with parameters provided as a dictionary. ```python result = requests.request("GET", "http://pikascript.com/package", params = {"name":"get-test", "id":"23"}) ``` -------------------------------- ### Create sys root object Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Initializes the sys root object which contains the mounted led sub-object. ```c PikaObj *sys = newRootObj("sys", New_SYS); ``` -------------------------------- ### Generic Parameter API Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8F%82%E6%95%B0%E8%A1%A8%20Args.html APIs for handling generic parameters, including setting, getting, and retrieving the argument type. ```c int32_t args_setArg(Args* self, Arg* arg); Arg* args_getArg(Args* self, char* name); ArgType args_getType(Args* self, char* name); ``` -------------------------------- ### unsubscribe() example Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Unsubscribes from a topic. Requires the topic string as a parameter. Returns 0 on success or an error code. ```python c.unsubscribe("/topic/sub") ``` -------------------------------- ### Invalid multi-line script block (missing newline) Source: https://pikadoc-en.readthedocs.io/en/latest/%E6%94%AF%E6%8C%81%E4%BA%A4%E4%BA%92%E5%BC%8F%E8%BF%90%E8%A1%8C.html Example of a script that does not work due to a missing final newline. ```python # Missing final newline while a < 10: a = a + 1 print(a) ``` -------------------------------- ### main.py: Import Device and PikaStdLib, create objects, and call methods Source: https://pikadoc-en.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html The entry file for PikaPython. Imports the Device and PikaStdLib modules, creates instances of LED, Uart, and MemChecker, then prints a greeting, sets and sends a UART name, and checks memory usage. All .py and .pyi files must be placed in the root directory of the pikascript fileshelf. ```python # main.py import Device import PikaStdLib led = Device.LED() uart = Device.Uart() mem = PikaStdLib.MemChecker() print('hello wrold') uart.setName('com1') uart.send('My name is:') uart.printName() print('mem used max:') mem.max() print('mem used now:') mem.now() ``` -------------------------------- ### Import PikaStdLib Source: https://pikadoc-en.readthedocs.io/en/latest/PikaStdLib%20%E6%A0%87%E5%87%86%E5%BA%93.html Import the library in main.py. ```python #main.py import PikaStdLib ``` -------------------------------- ### Constructor for LED1 class Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Creates the LED1 class constructor and binds the on() method using obj_defineMethod. ```c PikaObj * New_LED1(Args *args){ // Inherited from PikaObj base class MimiObj *self = New_PikaObj(args); // Bind the on() method to the LED1 object obj_defineMethod(self, "on()", onFun); return self; } ``` -------------------------------- ### Triggering signals with PikaEventListener Source: https://pikadoc-en.readthedocs.io/en/latest/coreapi_event.html Demonstrates initializing the Pika VM, running a script, and sending rising and falling edge signals to the event listener. ```cpp extern PikaEventListener* g_pika_device_event_listener; #define EVENT_SIGAL_IO_RISING_EDGE 0x01 #define EVENT_SIGAL_IO_FALLING_EDGE 0x02 #define GPIO_PA8_EVENT_ID 0x08 TEST(event, gpio) { /* init */ PikaObj* pikaMain = newRootObj("pikaMain", New_PikaMain); /* run */ pikaVM_runFile(pikaMain, "... /... /examples/TemplateDevice/gpio_cb.py"); /* simulate run in the call back */ pks_eventLisener_sendSignal(g_pika_device_event_listener, GPIO_PA8_EVENT_ID, EVENT_SIGAL_IO_RISING_EDGE); pks_eventLisener_sendSignal(g_pika_device_event_listener, GPIO_PA8_EVENT_ID, EVENT_SIGAL_IO_FALLING_EDGE); ... } ``` -------------------------------- ### Configure Git User Information Source: https://pikadoc-en.readthedocs.io/en/latest/contribute_to_stdlib.html Set up your identity and repository URL for the first commit. ```bash git config --global user.name < your user name > git config --global user.email < your email > git config remote.origin.url < your forked git repo url > ``` -------------------------------- ### Primitive Type Set and Get API Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8F%82%E6%95%B0%E8%A1%A8%20Args.html APIs for reading and writing primitive type parameters in an Args table. These methods do not support nesting. ```c /* set API */ int32_t args_setInt(Args* self, char* name, int64_t int64In); int32_t args_setFloat(Args* self, char* name, float argFloat); int32_t args_setPtr(Args* self, char* name, void* argPointer); int32_t args_setStr(Args* self, char* name, char* strIn); /* get API */ int64_t args_getInt(Args* self, char* name); float args_getFloat(Args* self, char* name); void* args_getPtr(Args* self, char* name); char* args_getStr(Args* self, char* name); ``` -------------------------------- ### Define a class with private members using PLOOC Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%A6%82%E4%BD%95%E8%B4%A1%E7%8C%AE%E5%86%85%E6%A0%B8.html Example of defining a Pool class in dataMemory.h using private_member() to encapsulate class members. ```c #if defined(__DATA_MEMORY_CLASS_IMPLEMENT__) #define __PLOOC_CLASS_IMPLEMENT__ #elif defined(__DATA_MEMORY_CLASS_INHERIT__) #define __PLOOC_CLASS_INHERIT__ #endif #include "__pika_ooc.h" ... struct Pool{ private_member( BitMap bitmap; uint8_t* mem; uint8_t aline; uint32_t size; uint32_t first_free_block; uint32_t purl_free_block_start; ) }; ``` -------------------------------- ### Create Args table with New_args Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8F%82%E6%95%B0%E8%A1%A8%20Args.html Creates a new parameter table from the heap and returns its pointer. Pass NULL as the reserved auxiliary parameter table. The created table must be destroyed manually with args_deinit to avoid memory leaks. ```c Args* New_args(Args* args); ``` -------------------------------- ### Override PIKA_STACK_BUFF_SIZE in pika_config.h Source: https://pikadoc-en.readthedocs.io/en/latest/%E4%BC%98%E5%8C%96%E5%86%85%E5%AD%98%E5%8D%A0%E7%94%A8%E3%80%81%E9%85%8D%E7%BD%AE%20libc.html Example override in pika_config.h to increase the runtime stack size of the PikaPython virtual machine from the default 256 to 512. ```c #define PIKA_STACK_BUFF_SIZE 512 ``` -------------------------------- ### Initialize PikaPython in main Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8D%81%E5%88%86%E9%92%9F%E9%83%A8%E7%BD%B2%E5%88%B0%E6%96%B0%E5%B9%B3%E5%8F%B0.html Add the pikaScriptInit function to your main function to initialize the PikaScript environment and obtain the pikaMain object pointer. ```c PikaObj* pikaMain = pikaScriptInit(); ``` -------------------------------- ### Setting properties on object and sub-object Source: https://pikadoc-en.readthedocs.io/en/latest/Pika%20%E5%AF%B9%E8%B1%A1%20PikaObj.html Shows how to set an Int property on the current object and on a sub-object using the property path. ```c // set an Int type arg, the arg name is "a". obj_setInt(self, "a", 1); // set an Int type arg for subObjcet , the arg path is "subObj.a". obj_setInt(self, "subObj.a", 1); ``` -------------------------------- ### setKeepAlive() - Set keepalive time Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the keepalive time, overriding the parameter at instantiation time. The `time` parameter is required and is an integer. The example uses 120 seconds. ```python # cgs unit c.setKeepAlive(120) ``` -------------------------------- ### Execute script via obj_run Source: https://pikadoc-en.readthedocs.io/en/latest/%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B.html Demonstrates how to execute a script string received from a serial port using the obj_run function. ```c obj_run(sys, uartReceiveBuff); ``` -------------------------------- ### Push Core Script Source: https://pikadoc-en.readthedocs.io/en/latest/contribute_to_stdlib.html Run the core push script. ```bash sh push-core.sh ``` -------------------------------- ### Valid multi-line script block Source: https://pikadoc-en.readthedocs.io/en/latest/%E6%94%AF%E6%8C%81%E4%BA%A4%E4%BA%92%E5%BC%8F%E8%BF%90%E8%A1%8C.html A complete multi-line code block example. Note the 0-indentation on the 4th line to mark the end of the block and the required trailing newline. ```python while a < 10: a = a + 1 print(a) print('the end') ``` -------------------------------- ### Module initialization: .pyi declaration Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html Declares __init__ and hello functions for module initialization. ```python # test.pyi def __init__():... def hello():... ``` -------------------------------- ### Module initialization: output Source: https://pikadoc-en.readthedocs.io/en/latest/cmodule_enhance.html Output of running main.py. Shows that __init__ is called when test.hello() is first used, not at import time. ```python before run test.hello() now loading module test... hello! after run test.hello() ``` -------------------------------- ### setDisconnectHandler() - Set disconnection callback Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Sets the disconnection callback. The `callback` parameter is required and should be a callback function. The example defines a callback that prints a message when the MQTT connection is disconnected. ```python def disconnect_cb(): print("mqtt disconnect") c.setDisconnectHandler(disconnect_cb) ``` -------------------------------- ### Demo 03 Try reading an ADC Source: https://pikadoc-en.readthedocs.io/en/latest/Demo%20%E5%B1%95%E7%A4%BA.html A script that initializes an ADC on pin PA1 and continuously reads and prints the analog value. ```python import PikaStdLib import machine time = machine.Time() adc1 = machine.ADC() adc1.setPin('PA1') adc1.enable() while True: val = adc1.read() print('adc1 value:') print(val) time.sleep_ms(500) ``` -------------------------------- ### connect() Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Connects to the server. This method takes no parameters and returns an integer status code. ```APIDOC ## connect() ### Description Connects to the server. ### Method connect() ### Parameters None ### Request Example ``` c.connect() ``` ### Response #### Success Response - **OK:0** (int) - Success code - **Error code** (int) - Error code if failed ``` -------------------------------- ### MQTT.connect() Source: https://pikadoc-en.readthedocs.io/en/latest/lib_mqtt.html Connects the MQTT client to the broker. ```APIDOC ## MQTT.connect() ### Description Connects the MQTT client to the broker. ### Method Method ### Endpoint MQTT.connect() ### Parameters None. ### Request Example ```python c.connect() ``` ### Response No return value. ``` -------------------------------- ### Import Math module in main.py Source: https://pikadoc-en.readthedocs.io/en/latest/Pikascript%20%E6%8B%93%E5%B1%95%E6%A8%A1%E5%9D%97%E5%BC%80%E5%8F%91%E6%B5%81%E7%A8%8B.html Registering the Math module in main.py to trigger the Pika precompiler. ```python # main.py import Math ```