#!/usr/bin/tclsh

package require http

###############################################
##    Ozeki NG - SMS Gateway Tcl example    ###
###############################################


###############################################
##          Functions for url-encoding        ###
###############################################
proc init {} {
    variable map
    variable alphanumeric a-zA-Z0-9
    for {set i 0} {$i <= 256} {incr i} {
	set c [format %c $i]
	if {![string match \[$alphanumeric\] $c]} {
	    set map($c) %[format %.2x $i]
	}
    }
    array set map { " " + \n %0d%0a }
}

proc url-encode {string} {
    variable map
    variable alphanumeric

    regsub -all \[^$alphanumeric\] $string {$map(&)} string
    regsub -all {[][{})\\]\)} $string {\\&} string

    return [subst -nocommand $string]
}

init


###############################################
###            Ozeki NG informations        ###
###############################################
set host "127.0.0.1"
set port "9501"
set username [url-encode "admin"]
set password [url-encode "abc123"]
set recipient [url-encode "+00123456"]
set message [url-encode "Test Message from Tcl"]


###############################################
### Putting together the final HTTP Request ###
###############################################
set url "http://$host:$port/api?action=sendmessage&username=$username&password=$password&recipient=$recipient&messagetype=SMS:TEXT&messagedata=$message"


################################################
####            Sending the message          ###
################################################
set http [::http::geturl $url]


################################################
###        Verifying the response            ###
################################################
upvar #0 $http state

if {$state(http) == "HTTP/1.1 200 OK"} {
   puts "Message successfully sent\n"
} else {
   puts "Message not sent! Please check your settings!\n"
}

exit