[WIZwiki_W7500ECO] HTTPClient with JSON parser

JSON is easy for machines to parse and generate which is based on a subset of the JavaScript Programming Language. Currently many Web Services allow to access data in JSON format. However, JSON parser is too big for low-end device as like a ARMmbed platform which has limited-resource. This post shows how to use HTTPClient parse Json data in ARMmbed platform.
IMG_20151029_165139//embedr.flickr.com/assets/client-code.js

Preparation materials

  1. Software

* JSON Parser: MbedJSONValue libs
* Ethernet Networking : WIZnetInterface
* HTTP Server with JSON : Fraka6 Blog – No Free Lunch: The simplest python server example 😉
2. Hardware
* WIZwiki-W7500ECONET: WIZwiki-W7500 + ECO Shield Ethernet
IMG_20151029_164448//embedr.flickr.com/assets/client-code.js

Simplest python JSON server on PC

def run(port=8000): #set port

print('http server is starting...')
#ip and port of server
#server_address = ('127.0.0.1', port)
server_address = ('192.168.0.223', port)#set port
httpd = HTTPServer(server_address, Handler)
print('http server is running...listening on port %s' %port)
httpd.serve_forever()
  • Modify JSON form in do_GET handler
#handle GET command
def do_GET(self):
if format == 'html':
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header('Content-type','text-html')
self.end_headers()
self.wfile.write("body")
elif format == 'json':
#self.request.sendall(json.dumps({'path':self.path}))
#self.request.sendall(json.dumps({'pi':3.14}))
self.request.sendall(json.dumps({'name':'John snow', 'age': 30, 'gender':'male'}))
else:
self.request.sendall("%s\t%s" %('path', self.path))
return

Make main.cc

// Enter a MAC address for your controller below.
uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x00, 0x01, 0x02};

printf("initializing Ethernet\r\n");
// initializing MAC address
eth.init(mac_addr, "192.168.0.34", "255.255.255.0", "192.168.0.1");

// Check Ethenret Link
if(eth.link() == true) printf("- Ethernet PHY Link-Done \r\n");
else printf("- Ethernet PHY Link- Fail\r\n");

// Start Ethernet connecting: Trying to get an IP address using DHCP
if (eth.connect() 0) {
http_rx_msg[returnCode] = '\0';
printf("Received %d chars from server:\n\r%s\n", returnCode, http_rx_msg);
}
  • Do JSON parse
parse(parser, http_rx_msg);
  • Output the parsed data
// parsing "string" in string type
printf("name =%s\r\n" , parser["name"].get().c_str());
// parsing "age" in integer type
printf("age =%d\r\n" , parser["age"].get());
// parsing "gender" in string type
printf("gender =%s\r\n" , parser["gender"].get().c_str());

Demo. HTTPClient with JSON parser

  1. Network config.
  2. Confirm Received JSON data
  3. Print-out the pasing data
    2015-10-29_16-42-55//embedr.flickr.com/assets/client-code.js

Packet Capture

  1. TCP-Connection
  2. Target board sends GET Form to simple python JSON server
  3. simple python JSON server sends JSON data to Target board
    2015-10-29_16-22-56//embedr.flickr.com/assets/client-code.js
Advertisements

Tweepy

Tweepy

You can write your own twitter’s bot with tweepy which is twitter API library for python.

An easy-to-user Python library for accessing the Twitter API.
Tweepy github

Let’s make the own twitter’bot with tweepy
* Step 1 : Create a Twitter Application
* Step 2 : Install the Tweepy
* Step 3 : Make Twitter’ bot with Tweepy

Create a Twitter Application

Go https://apps.twitter.com/ and sign with your twitter account to create twitter application.

Select the option to create a new application and fill in the required information as like Name, Description and Website.
TwitterTweepy

When then new application is created, check your cunsumer Key (API Key) and comsum Secret (API Secret) and modify app permission to Read, Write, and direct messages.
Key and Access Tokens

Install the Tweepy

  • Download Tweepy

sudo apt-get install python-pip
pip install tweepy

  • Install Tweepy

sudo python setup.py install

  • Run test

./run_test.sh
sudo apt-get install curl

Make Twitter’ Bot with Tweepy

We will tweet a post after OAuth.

  • OAuth
    import webbrowser
    import tweepy
    
    C_KEY    = 'enter your cunsumer key'
    C_SECRET = 'enter your cunsumer secret'
    
    auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
    auth_url = auth.get_authorization_url()
    print ('Open the URL:'+auth_url)
    webbrowser.open(auth_url)
    
    input_pin = raw_input ('PIN:').strip()
    token = auth.get_access_token(verifier=input_pin)
    print 'ACCESS KEY = %s' % token[0]
    print 'ACCESS SECRET = %s' % token[1]
    

    When “webbrowser.open()” is executed, Web-browser is open and sign with your twitter account.
    Then, click button of “Authoize app” to be able to your application, as like below figure.
    Authrioze

    Next, you can get PIN number for the authorization.
    AuthorizePin

  • Tweet
    You can post on your twitter with update_status() API.

    import tweepy
    C_KEY    = 'enter your cunsumer key'
    C_SECRET = 'enter your cunsumer secret'
    A_KEY    = 'enter your access key'
    A_SECRET = 'enter your access secret'
    
    auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
    auth.set_access_token(A_KEY, A_SECRET)
    
    api = tweepy.API(auth_handler=auth, api_root='/1.1')
    api.update_status('This message has been sent through Twitter API')
    
  • Confirm your post on your twitter

    posting

Python Simple Script for WIZ107SR

Source Github Link

WIZ107SR

WIZ107SR is a gateway module that converts serial protocol (RS-232) into TCP/IP protocol by using W7100A.

Link WIZ107SR materials – WIZ107SR

SW – Download & Install

Script descriptions – TCPClient

  • Init. serial port number and baudrate
serial.Serial("COM1", 57600)
  • Change to serial commond mode

Change to serial command mode; when serial command switch code is ‘123’.
Just only input serial command mode switch code of 3bytes without ‘\r\n’.
Serial command mode switch code is set by using ConfigTool.

ser.write(b'123')
  • Setting TCPClient mode
ser.write(b'LP5000rn') # Source port number : ex.) 5000
ser.write(b'RP3000rn') # TCP server port number : ex.) 3000
ser.write(b'RH192.168.10.100rn') # TCP server IP address : ex.) '192.168.10.100'
ser.write(b'OP0rn') # Set TCP Client mode : OP0 - TCPClinet
ser.write(b'SVrn') # Save Setting
ser.write(b'RTrn') # Reboot
  • Send
ser.write(b'hellorn')
  • recv
serial_recv_buf = 10
line = ser.read(serial_recv_buf)

FAQ; How know the status of TCP connections ?

We can know the TCP connection by using 8pin.

In the initial time, this pin is INPUT for Hardware Trigger(for
serial command mode). After that, this pin is OUTPUT for
connection status. When the connection is established, this pin
goes Low. And, it will go HIGH when connection is closed.