as django project, first commit

This commit is contained in:
j 2011-07-05 16:33:02 +05:30
commit 154efd3115
10 changed files with 391 additions and 0 deletions

0
__init__.py Normal file
View File

11
manage.py Executable file
View File

@ -0,0 +1,11 @@
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)

196
run_socket.py Normal file
View File

@ -0,0 +1,196 @@
import SocketServer
import sys
class IncomingPacketHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(6).strip()
handler_keyboard_cmd(self.data)
if __name__ == "__main__":
#TODO
#1. get serial port parameter from command line arguements
#2. print usage with examples before Enter your input
#3. add debug mode
#initialize global vars
sys_up = False
run = True
valid_cmd = False
int_ser_data = [0,0,0,0,0,0,0,0,0,0,0,0,0]
hex_ser_data = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
#functions defined here
def write_serial(ser, out_ser_pkt):
#function writes 13 bytes to serial port
# ser.write(out_ser_pkt)
import time
time.sleep(5 / 1000000.0)
for i in range(0, 13):
ser.write(chr(out_ser_pkt[i]))
# ser.write(out_ser_pkt[i])
# print "wrote i=%i out_ser_pkt=%i" % (i,out_ser_pkt[i])
# time.sleep(5)
#serial port packet handler
def handler_serial_pkt():
global sys_up
global int_ser_data
global out_ser_pkt
global valid_cmd
#print "in hsp int_ser_data[4]= %i", (int_ser_data[4])
#print "in hsp valid_cmd= %i", (valid_cmd)
#do the needful for sys up
if sys_up == False and int_ser_data[4] == 01:
out_ser_pkt=[0x7e,0x7e,0xff,0xfa,0x0,0x01,0x01,0x0,0x61,0x0,0x0,0xff,0x7e]
write_serial(ser,out_ser_pkt)
sys_up = True
print "sent packet sys up"
else:
#the basic switch which was used in c is here
#print "looping back"
if int_ser_data[4] == 01:
#send device cmd & data to panel
if valid_cmd == True:
out_ser_pkt=[0x7e,0x7e,0xff,0xfa,0x0,0x01,dev_cmd,0x01,0xAA,panel_dev,dev_no,0xff,0x7e]
print "prepared out_ser_pkt "
write_serial(ser,out_ser_pkt)
print "sent packet out_ser_pkt "
#if device cmd & data ack from panel
elif int_ser_data[4] == 0x5a:
valid_cmd = False
print "Done device cmd"
elif int_ser_data[4] == 0x55:
valid_cmd = False
print "FATAL ERROR!!! Received NAK from panel"
#no data for panel send keep alive
else:
out_ser_pkt=[0x7e,0x7e,0xff,0xfa,0x0,0x01,0x0,0x01,0xAA,0x52,0x01,0xff,0x7e]
write_serial(ser,out_ser_pkt)
#keyboard command handler
def handler_keyboard_cmd(kbd_cmd):
# global kdb_cmd
global dev
global str_dev_no
global dev_no
global dev_cmd
global str_dev_cmd
global valid_cmd
global panel_dev
print kbd_cmd
#if lenght of keyboard cmd equals 6, parse keyboard input
if kbd_cmd[0] == 'r' or kbd_cmd[0] == 'R'or kbd_cmd[0] == 'd' or kbd_cmd[0] == 'D':
import string
dev=string.upper(kbd_cmd[0])
print "dev=%s" % (dev)
str_dev_no=kbd_cmd[1] + kbd_cmd[2]
print "str_dev_no=%s" %str_dev_no
if str_dev_no =='01':
dev_no=1
elif str_dev_no =='02':
dev_no=2
elif str_dev_no =='03':
dev_no=3
elif str_dev_no =='04':
dev_no=4
elif str_dev_no =='05':
dev_no=5
elif str_dev_no =='06':
dev_no=6
elif str_dev_no =='07':
dev_no=7
elif str_dev_no =='08':
dev_no=8
elif str_dev_no =='09':
dev_no=9
elif str_dev_no =='10':
#print "debug in 10"
dev_no=0xa
elif str_dev_no =='11':
#print "debug in 11"
dev_no=0xb
elif str_dev_no =='12':
#print "debug in 12"
dev_no=0xc
elif str_dev_no =='13':
#print "debug in 13"
dev_no=0xd
elif str_dev_no =='14':
#print "debug in 14"
dev_no=0xe
elif str_dev_no =='15':
#print "debug in 15"
dev_no=0xf
elif str_dev_no =='16':
#print "debug in 16"
dev_no=0x10
else:
dev_no=0
#print "invalid device no"
if dev_no >= 1 and dev_no <= 0x10:
print "--- valid device no.---"
str_dev_cmd = kbd_cmd[4] + kbd_cmd[5]
dev_cmd=int(str_dev_cmd, 16)
print "str_dev_cmd=%s" % (str_dev_cmd)
print "dev_cmd= %x " %(dev_cmd)
if dev == 'R':
if dev_cmd == 00 or dev_cmd == 01:
valid_cmd = True
panel_dev=0x52
#print "valid_cmd = %s" % (valid_cmd)
else:
valid_cmd = False
print "for relay valid_cmd = %s" % (valid_cmd)
else:
if dev_cmd >= 0x0 and dev_cmd <= 0xff:
valid_cmd = True
panel_dev=0x44
dev_no=dev_no-1
#print "for dac valid_cmd = %s" % (valid_cmd)
else:
valid_cmd = False
print "valid_cmd = %s" % (valid_cmd)
else:
print "Invlaid device"
else:
print "Invalid Command"
#---- main program here
#init serial port
import serial
ser = serial.Serial('/dev/ttyS0', 115200,timeout=20)#init serial port TODO serial port params should be command line arguements
sys_up=False;
print "Connecting to Panel. Please wait..."
while run:
ser_data = ser.read(13)#read 1 packet of 13bytes from panel
for i in range(0, 13):
int_ser_data[i]=ord(ser_data[i])#convert packet received from char to integer
# print "i = %i int_ser_data = %i" % (i,int_ser_data[i])
#validate packet byte 1, byte 2, byte 13 =126 viz 0x7e
if int_ser_data[0] == 126 and int_ser_data[1] == 126 and int_ser_data[12] == 126:
#print "b4 hsp int_ser_data[4]= %i", (int_ser_data[4])
handler_serial_pkt()
# else:
# print "imporper packet"
if valid_cmd == False:
HOST, PORT = "127.0.0.1", 4321
server = SocketServer.TCPServer((HOST, PORT), IncomingPacketHandler)
server.serve_forever()
# l=len(kbd_cmd)
# print "kbd_cmd=%s l=%i " % (kbd_cmd,l)
# if l==6:
# handler_keyboard_cmd(kbd_cmd)
# else:
# print "Invalid Input"

0
sendmsg/__init__.py Normal file
View File

3
sendmsg/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

23
sendmsg/tests.py Normal file
View File

@ -0,0 +1,23 @@
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}

17
sendmsg/views.py Normal file
View File

@ -0,0 +1,17 @@
# Create your views here.
from django.http import HttpResponse
import socket
from django.shortcuts import render_to_response
def sendMsg(request):
msg = request.GET.get("msg", "")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 4321))
s.send(msg)
return HttpResponse("ok")
def index(request):
d = {
'foo': 'jtd'
}
return render_to_response("index.html", d)

101
settings.py Normal file
View File

@ -0,0 +1,101 @@
# Django settings for jtd project.
import os
from os.path import join
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
PROJECT_PATH = os.path.dirname(__file__)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'lr5&u!qf%kxmkvd9uxg=i_n8+&0r7@5j*76e9z+)m^z9(zdu-m'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'jtd.urls'
TEMPLATE_DIRS = (
join(PROJECT_PATH, 'templates')
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'sendmsg',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)

22
templates/index.html Normal file
View File

@ -0,0 +1,22 @@
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#sendmsg').click(function() {
var msg = $('#msg').val();
$.get("/testmsg/", {
'msg': msg
}, function(response) {
alert(response);
});
});
});
</script>
</head>
<body>
Hello {{ foo }}: <br />
Cmd: <input type="text" id="msg" /> <button id="sendmsg">Send</button>
</body>
</html>

18
urls.py Normal file
View File

@ -0,0 +1,18 @@
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'testmsg/', 'sendmsg.views.sendMsg'),
(r'^$', 'sendmsg.views.index'),
# Example:
# (r'^jtd/', include('jtd.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)