The sensor object contains the interface to the actual sensor. A buffer is required because PycURL does not provide stor-
age for the network response. After each sensor request, the HTTP response code is checked for success.
The first operation is to reset the sensor. After a delay, the script changes a couple of sensor parameters. Waiting another
10 seconds (for the motor to spin up), sensor status is obtained and printed to standard out.
import pycurl
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import urllib2
import json
import time
def sensor_do(s, url, pf, buf):
s.setopt(s.URL, url)
s.setopt(s.POSTFIELDS, pf)
s.setopt(s.WRITEDATA, buf)
s.perform()
rcode = s.getinfo(s.RESPONSE_CODE)
success = rcode in range(200, 207)
print('%s %s: %d (%s)' % (url, pf, rcode, 'OK' if success else 'ERROR'))
return success
Base_URL = 'http://192.168.1.201/cgi/'
sensor = pycurl.Curl()
buffer = BytesIO()
rc = sensor_do(sensor, B'reset', urlencode({'data':'reset_system'}), buffer)
if rc:
time.sleep(10)
rc = sensor_do(sensor, B'setting', urlencode({'rpm':'300'}), buffer)
if rc:
time.sleep(1)
rc = sensor_do(sensor, B'setting', urlencode({'laser':'on'}), buffer)
if rc:
time.sleep(10)
response = urllib2.urlopen(B'status.json')
if response:
status = json.loads(response.read())
print 'Sensor laser is %s, motor rpm is %s' % \
(status['laser']['state'], status['motor']['rpm'])
sensor.close()
Typical output looks like the following:
http://192.168.1.201/cgi/reset data=reset_system: 204 (OK)
http://192.168.1.201/cgi/setting rpm=300: 204 (OK)
Chapter 10 • Sensor Communication
85