1

Hello I'am tring to send a cURL command to a Orion Context Broker via a Python script. I am running the script on OpenWRT, so i am not able to install the requests or urllib2 library, for memory issues, additionally libraries like subprocess fail to compile. So I am using os.system() to execute the cURL command. This is the code of the script:

import sys
import os
from urllib import urlencode
sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient

value = bridgeclient()


header="(curl 10.130.1.228:1026/v1/updateContext -s -S --header 'Content-Type: application/json' \
--header 'Accept: application/json'     -d @- | python -mjson.tool) <<EOF"

json_string="""
{
    "contextElements": [
        {
            "type": "Room",
            "isPattern": "false",
            "id": "R1",
            "attributes": [
                {
                    "name": "temperature",
                    "type": "float",
                    "value": "firstValue"
                },
                {
                    "name": "pressure",
                    "type": "float",
                    "value": "secondValue"
                }
            ]    
        }
    ],
    "updateAction": "UPDATE"
}
EOF""" 


while(True):

    all=value.getall()
    sentValue1=""
    sentValue2=""
    if all['Tmp'] is None:
        sentValue1=all['Tmp']
    else:
        sentValue1="NoValue"
    if all['Prs'] is None:
        sentValue2=all['Prs']
    else:
        sentValue2="NoValue"
    json_string=json_string.replace("firstValue",sentValue1)
    json_string=json_string.replace("secondValue",sentValue2)   
    os.system(header+json_string)

If I copy and paste the command i give to os.system(), as it is in the terminal window, everything works smoothly and my Orion instance gets updated. But if i run the same command via the said script i get this response from the server:

{
    "errorCode": {
        "code": "400",
        "details": "JSON Parse Error",
        "reasonPhrase": "Bad Request"
    }
}

I think is some formatting issue and i have tried everything to make it work but with no luck.

UPDATE:

I found in the contextBroker log this message:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected end of input

and this one:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected object

Both repeated for each cURL request I made.

UPDATE 2:

I managed to make subprocess.call() to work, but it gives the exact same response.

7
  • would it be worth if you specified /usr/bin/python in your header variable? Commented Nov 9, 2017 at 15:34
  • @Shan-Desai I tried but it didn't work. Also as I said the string header+json_string copied and paste in the terminal works with no problems. Commented Nov 9, 2017 at 15:55
  • 1
    Try using pycurl if you can. However to address the issue. Use import json and then instead of writing a string create your json_string as a python dictionary and use json.dumps(json_string) Commented Nov 9, 2017 at 16:01
  • for reference stackoverflow.com/questions/37117195/… Commented Nov 9, 2017 at 16:02
  • @Shan-Desai Thank you very much for your help. But how can i make a python dictionary if i need a nested json? Commented Nov 9, 2017 at 16:07

1 Answer 1

1

Thanks to @Shan-Desai I solved the problem.

I built the json string using json.dump and used pycurl.

this is the working code:

import sys
import os
import subprocess
import json
from urllib import urlencode
from collections import OrderedDict
import StringIO
import pycurl

sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient


fout = StringIO.StringIO()
value = bridgeclient()
apiurl = '10.130.1.228:1026/v1/updateContext'
headers=['Content-Type: application/json','Accept: application/json']

firstValue = 'firstValue'

secondValue = 'secondValue'

d_attributes = [{'name': 'temperature', 'type': 'float', 'value': firstValue},
            {'name': 'pressure', 'type': 'float', 'value': secondValue}]

d_context = [{'type': 'Room', 'isPattern': 'false', 'id': 'R1', 'attributes': d_attributes}]

d_json = {'contextElements': d_context, 'updateAction': 'UPDATE'}

c = pycurl.Curl()

while (True):

        all = value.getall()

        if all['Tmp'] is not None:
            firstValue = all['Tmp']
        else:
            firstValue = "NoValue"
        if all['Prs'] is not None:
            secondValue = all['Prs']
        else:
            secondValue = "NoValue"
        d_json["contextElements"][0]["attributes"][0]["value"]=firstValue
        d_json['contextElements'][0]['attributes'][1]['value']=secondValue
        c.setopt(pycurl.WRITEFUNCTION, fout.write)
        c.setopt(pycurl.URL, apiurl)
        c.setopt(pycurl.HTTPHEADER, headers)
        c.setopt(pycurl.POST, 1)
    s_json=json.dumps(d_json)
        c.setopt(pycurl.POSTFIELDS,s_json)
        c.perform()
        c.getinfo(pycurl.RESPONSE_CODE)
        print(json.dumps(OrderedDict(d_json)))
        print(fout.getvalue())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.