MicroPython & Thingworx

To interact with Thingworx, we will use the "urequests" and "ujson" modules which come included with the MicroPython firmware.

Example code to interact with Thingworx in various ways is shown below.


PUT and GET

import urequests
import ujson
import utime

# Info
url = 'http://pp-1804271345f2.portal.ptc.io:8080/Thingworx/Things/CEEO_Summer/Properties/'
headers = {
        'Content-Type':'application/json',
        'Accept':'application/json',
        'appKey':'[YOUR APPKEY GOES HERE]'
        }
varName = 'ptest'
varValu = ['This was a successful GET/PUT... huzzah!',
           'HUZZAH!!!',
           'You did it',
           'Yay!',
           'MicroPython <3 ThingWorx 5eva',
           'yeehaw, pardner',
           'nice work',
           'somebody call security',
           'success',
           'whoopity scoop']

# Get random(ish) number to select one varValu to assign to varName
now = str(utime.ticks_cpu())
index = int((now)[len(now)-3])
payload = {varName:varValu[index]}

# PUT
urequests.put(url+'*',headers=headers,json=payload)

# GET (the next section of code can be reformatted as one line,but is separated to show the process of parsing)
text = urequests.get(url+varName,headers=headers).text
#print(text)
json = ujson.loads(text)
#print(json)
rows = json.get('rows')
#print(rows)
value = rows[0][varName]
print(value)


TEXT (Be sure to change "yournumber" to your actual phone number. Keep the quotation marks!)

import urequests

url = "https://academic-dev1.cloud.thingworx.com/Thingworx/Things/NIPhoneCommunication/Services/sendText"

payload = "{\n\t\"message\":\"Greetings, Earthling. I am Huzzah. Good day.\",\n\t\"toNumber\":\"yournumber\"\n}"
headers = {
    'appKey': "[YOUR APPKEY GOES HERE]",
    'Content-Type': "application/json"
    }

response = urequests.request("POST", url, data=payload, headers=headers)

print(response.text)


MORE LIKE THE EXAMPLES ABOVE AVAILABLE HERE: Common Thingworx API Calls in Python (link)

Note: These examples are in Python syntax, not MicroPython syntax. In order to fix that, change every instance of "requests" to "urequests" (there are usually two instances).

In order to parse the JSON to extract just the variable value for GET requests, use the MicroPython module "ujson".