55
Internet Controlled Applications Your automation everywhere you are. ICA Thermostat Milestone 2 Technical Documentation (Document revision 0.4 – ATMega162) Barry de Graaff Project group Internet Controlled Applications: Barry de Graaff Tom Haeldermans David Jacobsons Linda Vandenbroeck

ICA_Technical_Doc

Embed Size (px)

Citation preview

Page 1: ICA_Technical_Doc

Internet Controlled Applications Your automation everywhere you are.

ICA Thermostat Milestone 2 Technical Documentation (Document revision 0.4 – ATMega162)

Barry de Graaff

Project group Internet Controlled Applications: Barry de Graaff

Tom Haeldermans David Jacobsons

Linda Vandenbroeck

Page 2: ICA_Technical_Doc

2

Internet Controlled Applications Your automation everywhere you are.

Page 3: ICA_Technical_Doc

3

Table of contents

Preface 5 1. What is our project? 7 1.1 What are our project objectives? 7 1.2 Basic project operation 7 1.2.1 Temperature hysteresis 9 1.2.2 Controlled through the Internet 9 1.2.3 Controlled locally 9 1.2.4 Administrative tasks over RS-232 9 2 Understanding TCP/IP 11 2.1 Layered protocol TCP 11 2.1.1 Link layer 13 2.1.2 Network Layer 13 2.1.3 Transport Layer 15 2.1.4 Application Layer 15 2.1.5 Layer summary 15 2.2 Internet Protocol IP 17 2.2.1 Packets 17 3 Understanding HTTP 19 3.1 What is HTTP? 19 3.2 What are “Resources”? 19 3.3 Structure of HTTP Transactions 19 3.3.1 Initial Request Line 21 3.3.2 Initial Response Line (Status Line) 21 3.3.3 The Message Body 23 3.3.4 The HEAD Method 23 3.4 Sample HTTP Exchange 25 4 Thermostat’s block diagram and schematics 27 4.1 The block diagram torn apart 27 4.1.1 In system programming connection 29 4.1.2 Serial connection RS-232 29 4.1.3 Ethernet Interface 31 4.1.3.1 Initialize IIM7000A 31 4.1.3.2 HTTP Initial request and response lines 33 4.1.3.3 Get the URL and send HTML 35 4.1.3.4 IIM7000A 37 4.1.4 Controller ATMega162 39 4.1.5 I²C bus 41 4.1.6 Local push buttons 43 4.1.7 Relay output 43 4.1.8 LCD-display 43 4.2 Putting part 1 thru 8 together 45 5 Security and security risks 47 6 Memory map and usage 49 7 Compiler specific settings 51 Gratitude’s and after word 53 Annexes 55 Copyright and disclaimer 55

Page 4: ICA_Technical_Doc

4

Figure 1, The ICA group with from left to right, David Jacobsons, Tom Haeldermans,

Barry de Graaff and Linda Vandenbroeck.

Page 5: ICA_Technical_Doc

5

Preface

Please allow us to introduce ourselves. We are The Internet Controlled Applications project group. The ICA group is formed by three Belgium bachelor electronics students of the De Nayer Institute in Sint Katelijne Waver and one Dutch bachelor electronics student of The Hague University for Professional Education. Under the umbrella of the VLAJO (Flemish Youth Association) we created a Small Business Project (SBP). Our SBP is financed by stock holders. More marketing and business considerations can be found in our business plan on our site. (www.barrydegraaff.tk/ica) Our slogan is our goal: “Your Automation Everywhere You Are”, which basically means that we connect you to your automation electronics everywhere you are. We provide full services for our products. This includes installation but also customer specific modifications. This technical document is devoted to our first product “The Web server Thermostat”. The first chapter is devoted to the basic functions and objectives of our product. The second and third chapter show some technical backgrounds needed to understand the forth chapter which handles the practical implementation. Chapter five and six are for your information only. They should not be read if you are not interested in reproducing this product. For specific support, enquiries or sales please contact our managing director Linda Vandenbroeck. ([email protected]) The ICA Group

Page 6: ICA_Technical_Doc

6

Page 7: ICA_Technical_Doc

7

1. What is our project?

Our project is a web server thermostat for in door use and is meant for the consumer market.

1.1 What are our project objectives?

• Creation of a web server that enables a user to monitor and modify the

temperature of his home.

• Monitoring and modification can be done locally with push buttons and an LCD display. Remote monitoring and modification can be done through the Internet. The user then needs is a PC connected with the Internet and a commonly used graphic browser. (No further requirements, no installs or setups.)

• Stand alone temperature control. (PC doesn’t have to run all the time)

• User authentication.

• The thermostat will be adapted to customers needs and is fully modifiable.

• The project will not be sold as a stand alone product but will always be

installed by the project members. The connection settings (IP, Gateway, Subnet mask) and password list can only be changed locally thru an RS-232 interface.

For marketing and commercial objectives please consult ICA Business plan that is available in PDF from www.barrydegraaff.tk/ica. The business plan is only available in Dutch language.

1.2 Basic project operation

Paragraph 1.2 is a brief summary of the users interface and the functioning of the thermostat. A full user manual will become available on www.barrydegraaff.tk/ica. First of all two definitions:

• The Set point temperature is the desired temperature value. (Dutch: Gewenste temperatuur)

• The Current temperature is the current environmental temperature. (Dutch: Huidige temperatuur)

When the set point is set to zero (0) the Thermostat is switched off! This means that heating will NEVER occur, not even if the current temperature is below zero degrees centigrade. The set point is an integer value from zero to and including thirty degrees centigrade.

Page 8: ICA_Technical_Doc

8

Figure 2, Hysteresis in temperature regulation

Switch heating on Switch heating off

Setpoint - 1 Setpoint Setpoint + 1

Temperature progress

Temperature progress

< Colder Warmer >

Page 9: ICA_Technical_Doc

9

1.2.1 Temperature hysteresis

Temperature hysteresis is +/- one degree as can be seen in figure 1. Hysteresis is meant to avoid heating oscillations. Basically it means there is a dead zone around the set point where the thermostat doesn’t switch the heating on or off.

1.2.2 Controlled through the Internet

User connects to the server by use of a browser. A typical URL for the web server thermostat is: http://76.251.73.162:5000/ This URL specifies the protocol, the IP and the port number of our thermostat. But DNS can also be used then you could enter a URL like http://www.mythermostat.com/ After the URL is given the user will be asked for a username and password. After a successful logon the time and temperature can be set through a form input.

1.2.3 Controlled locally

Locally you can set the temperature with pushbuttons. No authentications or what so ever is used. The desired and current temperature can be read from an LCD display.

1.2.4 Administrative tasks over RS-232

To provide a fail save and secure system some settings can only be changed locally with the help of a PC with Hillgraves HyperTerminal. These setting are only meant for installing the thermostat and they are not part of the daily users interface. These settings are:

• Configure server IP. • Configure server Gateway. • Configure server subnet mask. • Thermostat reset • EEPROM dump • Version number lookup • Generate new password list

The end user can generate a new password list with the help of our own terminal program for windows.

Page 10: ICA_Technical_Doc

10

Figure 3, TCP/IP Header (Source: University of Illinois at Chicago)

Page 11: ICA_Technical_Doc

11

2 Understanding TCP/IP

Before we can understand how the Thermostat works, we need to know some things about the way we communicate with the Internet. Therefore this essay contains two chapters with general theory on the functioning of TCP/IP and HTTP. Chapter two is on TCP/IP while chapter three learns us about HTTP. TCP/IP is a commonly used network protocol used on LANs, WANs and the Internet. It’s possible to use TCP/IP with little more than knowledge of how to configure the protocol stack, but a better understanding will give you a clearer picture of what is going on in your network and why the protocol needs to be set up in a particular way. TCP/IP stands for Transmission Control Protocol/ Internet Protocol. If this leads you to think that it is not just one protocol, you’re right. In fact, it is not just two protocols, either. TCP/IP is a suite of protocols. We’ll cover the most important ones in this chapter. Figure 4, The TCP/IP Protocol stack with our implementation

2.1 Layered protocol TCP

Like most network protocols, TCP/IP is a layered protocol. Each layer builds upon the layer below it, adding new functionality. The lowest level protocol is concerned purely with the business of sending and receiving data - any data - using specific network hardware. At the top are protocols designed specifically for tasks like transferring files or delivering email. In between are levels concerned with things like routing and reliability. The benefit that the layered protocol stack gives you is that, if you invent a new network application or a new type of hardware, you only need to create a protocol for that application or that hardware: you don’t have to rewrite the whole stack.

TCP/IP protocol stack

Application layer

Link layer

Network layer

Transport layer

HTTP (FTP, SMTP)

IEEE802.x

IP

TCP (UDP)

Basic code in ATMega

RTL8201bl

W3100A

W3100A

Page 12: ICA_Technical_Doc

12

Figure 5, Ethernet frame (Source: David R. Frick & Co Accountancy)

Page 13: ICA_Technical_Doc

13

2.1.1 Link layer

TCP/IP is a four- layer protocol. The lowest level, the link layer, is implemented within the network adapter and its device driver. In the thermostat project this layer is handled by the RTL8201bl Ethernet chip. Like all the TCP/IP protocols, it is defined by standards. The standards for generic Ethernet- type networks are defined by the IEEE 802 Committee: for example, IEEE 802.3 for Ethernet networks, IEEE 802.11 for wireless Ethernet or IEEE 802.5 for Token Ring networks. Since Ethernet is the most common type of network, we will look at it in a bit more detail. The Ethernet protocol is designed for carrying blocks of data called frames. A frame consists of a header containing 48- bit hardware destination and source addresses (which identify specific network adapters), a 2- byte length field, and some control fields. There follows the data, and then a trailer which is simply a 32- bit cyclic redundancy check (CRC) field. The data portion of an Ethernet frame must be at least 38 bytes long, so filler bytes are inserted if necessary. All this means that frames are at least 64 bytes long, even if they carry only one byte of user data: a significant overhead in some types of application. Frames also have a maximum size. Less headers, the maximum size for an Ethernet frame is 1492 bytes, which is the maximum transmission unit (MTU) for Ethernet. All link layer protocols have an MTU. It is one hardware characteristic that the higher- level protocol needs to be aware of, because larger blocks of data must be fragmented into chunks that fit within the MTU and then reassembled on arrival at their destination.

2.1.2 Network Layer

The next layer up from the link layer is called the network layer. In the thermostat project the Network Layer is handled by the W3100A glue chip. The most important protocol at this level is IP, the Internet Protocol. Its job is to send packets or datagram’s - a term which basically means “blocks of data” - from one point to another. It uses the link layer protocol to achieve this. Both the network layer and the link layer are concerned with getting data from point A to point B. However, whilst the network layer works in the world of TCP/IP, the link layer has to deal with the real world. Everything it does is geared towards the network hardware it uses.

Page 14: ICA_Technical_Doc

14

Page 15: ICA_Technical_Doc

15

2.1.3 Transport Layer

In the thermostat project the Transport Layer is handled by the W3100A glue chip. Protocols running at the transport layer are charged with providing several important services to enable software applications in higher layers to work over a network. They are typically responsible for allowing connections to be established and maintained between software services on possibly distant machines. Perhaps most importantly, they serve as the bridge between the needs of many higher-layer applications to send data in a reliable way without needing to worry about error correction, lost data or flow management, and network-layer protocols, which are often unreliable and unacknowledged. Transport layer protocols are often very tightly-tied to the network layer protocols directly below them, and designed specifically to take care of functions that they do not deal with.

2.1.4 Application Layer

The Application Layer is a Layer that is familiar for everyone. As a matter of fact the applications that we use are considered part of the Application Layer. Popular applications are: HTTP FTP SMTP The HTTP application itself is discussed in chapter 3. In the thermostat project the ‘HTTP Application’ is implemented in the Basic source code in the ATMega162.

2.1.5 Layer summary

• Application layer (Process layer)

Consists of applications and processes that use the network. HTTP, SMTP, FTP

• Transport layer (Host-to-host layer)

Provides end-to-end data delivery services.

• Network layer Defines the datagram and handles the routing of data.

• Link layer (Network access Layer)

Accessing the physical networks.

Page 16: ICA_Technical_Doc

16

Page 17: ICA_Technical_Doc

17

2.2 Internet Protocol IP

IP is the fundamental protocol of TCP/IP. Every message and every piece of data sent over any TCP/IP network is sent as an IP packet. The main purpose of IP is to enable data to be transmitted across and between networks. Hence the name: inter- net protocol. IP is a connectionless protocol. This means that it has no concept of a job or a session. Each packet is treated as an entity in itself. IP is rather like a postal worker sorting letters. He is not concerned with whether a packet is one of a batch. He simply routes packets, one at a time, to the next location on the delivery route. IP is also unconcerned with whether a packet reaches its eventual destination, or whether packets arrive in the original order. There is no information in a packet to identify it as part of a sequence or as belonging to a particular job. Consequently, IP cannot tell if packets were lost or whether they were received out of order. IP (on its own) is an unreliable protocol. Any mechanisms for ensuring that data sent arrives correct and intact are provided by the higher- level protocols in the suite.

2.2.1 Packets

An IP packet consists of the IP header and data. The header includes a 4- bit protocol version number, a header length, a 16- bit total length, some control fields, a header checksum and the 32- bit source and destination IP addresses. This totals 20 bytes in all. We won’t go into the detail of all the IP control fields. However, the protocol field is important. It identifies which higher- level TCP/IP protocol sent the data. When data arrives at its destination (either the packet’s destination address equals the host’s own IP address, or it is a broadcast address) this field tells IP which protocol module to pass it on to. One control field, the time-to-live (TTL) field, is interesting. It is initialized by the sender to a particular value, usually 64, and decremented by one (or the number of seconds it is held on to) by every router that the packet passes through. When it reaches zero the packet is discarded and the sender notified using the Internet Control Message Protocol (ICMP), a network layer protocol for sending network- related messages. The TTL field is a safety mechanism which prevents packets from traveling the Internet forever in routing loops. It is exploited in a novel way by the Traceroute diagnostic tool. Although the total field length in the IP protocol header is 16 bits, IP packets are usually much smaller than the 64 KB maximum this implies. For one thing, the link layer will have to split this into smaller chunks anyway, so most of the efficiency advantages of sending data in large blocks is lost. For another, IP standards did not historically require a host to accept a packet of more than 576 bytes in length. Many TCP/IP applications limit themselves to using 512- byte blocks for this reason, but today most implementations of the protocol aren’t so restricted.

Page 18: ICA_Technical_Doc

18

Page 19: ICA_Technical_Doc

19

3 Understanding HTTP

As we found out in the previous chapter TCP/IP is a 4 layer protocol. In this chapter we discuss HTTP. HTTP is part of the Application layer of the TCP/IP model. We use HTTP to send and receive data through HTML files.

3.1 What is HTTP?

HTTP stands for Hypertext Transfer Protocol. It's the network protocol used to deliver virtually all files and other data (collectively called resources) on the World Wide Web, whether they're HTML files, image files, query results, or anything else. Usually, HTTP takes place through TCP/IP sockets. A browser is an HTTP client because it sends requests to an HTTP server (Web server), which then sends responses back to the client. The standard (and default) port for HTTP servers to listen on is 80, though they can use any port.

3.2 What are “Resources”?

HTTP is used to transmit resources, not just files. A resource is some chunk of information that can be identified by a URL (it's the R in URL). The most common kind of resource is a file, but a resource may also be a dynamically-generated query result, the output of a CGI script, a document that is available in several languages, or something else. While learning HTTP, it may help to think of a resource as similar to a file, but more general. As a practical matter, almost all HTTP resources are currently either files or server-side script output.

3.3 Structure of HTTP Transactions

Like most network protocols, HTTP uses the client-server model: An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection (making HTTP a stateless protocol, i.e. not maintaining any connection information between transactions). The formats of the request and response messages are similar, and English-oriented. Both kinds of messages consist of:

• an initial line, • zero or more header lines, • a blank line (i.e. a CRLF by itself), and • an optional message body (e.g. a file, or query data, or query output).

Put another way, the format of an HTTP message is:

Page 20: ICA_Technical_Doc

20

Page 21: ICA_Technical_Doc

21

<initial line, different for request vs. response> Header1: value1 Header2: value2 Header3: value3 <optional message body goes here, like file contents or query data;

3.3.1 Initial Request Line

The initial line is different for the request than for the response. A request line has three parts, separated by spaces: a method name, the local path of the requested resource, and the version of HTTP being used. A typical request line is: GET /path/to/file/index.html HTTP/1.0 Notes:

• GET is the most common HTTP method; it says "give me this resource". Other methods include POST and HEAD. Method names are always uppercase.

• The path is the part of the URL after the host name, also called the request URI (a URI is like a URL, but more general).

• The HTTP version always takes the form "HTTP/x.x", uppercase.

3.3.2 Initial Response Line (Status Line)

The initial response line, called the status line, also has three parts separated by spaces: the HTTP version, a response status code that gives the result of the request, and an English reason phrase describing the status code. Typical status lines are: HTTP/1.0 200 OK or HTTP/1.0 404 Not Found Notes:

• The HTTP version is in the same format as in the request line, "HTTP/x.x". • The status code is meant to be computer-readable; the reason phrase is

meant to be human-readable, and may vary. • The status code is a three-digit integer, and the first digit identifies the general

category of response: o 1xx indicates an informational message only o 2xx indicates success of some kind o 3xx redirects the client to another URL o 4xx indicates an error on the client's part o 5xx indicates an error on the server's part

Page 22: ICA_Technical_Doc

22

Page 23: ICA_Technical_Doc

23

The most common status codes are: 200 OK The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body. 404 Not Found The requested resource doesn't exist. 301 Moved Permanently 302 Moved Temporarily 500 Server Error An unexpected server error. The most common cause is a server-side script that has bad syntax, fails, or otherwise can't run correctly.

3.3.3 The Message Body

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server. If an HTTP message includes a body, there are usually header lines in the message that describe the body. In particular,

• The Content-Type: header gives the MIME-type of the data in the body, such as text/html or image/gif.

• The Content-Length: header gives the number of bytes in the body.

3.3.4 The HEAD Method

A HEAD request is just like a GET request, except it asks the server to return the response headers only, and not the actual resource (i.e. no message body). This is useful to check characteristics of a resource without actually downloading it, thus saving bandwidth. Use HEAD when you don't actually need a file's contents. The response to a HEAD request must never contain a message body, just the status line and headers.

Page 24: ICA_Technical_Doc

24

Page 25: ICA_Technical_Doc

25

3.4 Sample HTTP Exchange

To retrieve the file at the URL: http://www.somehost.com/path/file.html First open a socket to the host www.somehost.com, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket: GET /path/file.html HTTP/1.0 From: [email protected] User-Agent: HTTPTool/1.0 [blank line here] The server should respond with something like the following, sent back through the same socket: HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 <html> <body> <h1>Happy New Millennium!</h1> (more file contents) . . . </body> </html> After sending the response, the server closes the socket. To familiarize yourself with requests and responses, manually experiment with HTTP using telnet.

Page 26: ICA_Technical_Doc

1.) 2.) 3.) 4.) 5.)

6.) 7.) 8.) Figure 6, Block Diagram of the web server thermostat

Page 27: ICA_Technical_Doc

27

4 Thermostat’s block diagram and schematics

In chapter four we’ll discuss the block diagram of our web server thermostat and relate it to the practical implementation. Both software (basic code) and hardware (chips and components) is discussed.

4.1 The block diagram torn apart

First we will take the block diagram and divide it into eight separate parts. You can see these eight parts in figure 6.

1. In system programming connection Used to update the firmware of the thermostat, also used to reprogram the device in design time.

2. Serial connection RS-232 Used to change the password list in run time, also used by the installer to set the connection settings. (As seen in paragraph 1.2.4)

3. Ethernet interface Used to access the thermostat thru a network. (remote)

4. Controller The controller takes care of the temperature regulation and handles inbound and outbound communication. The controller is in fact the hart of the web server thermostat.

5. I²C Bus Part 5 represents an I²C bus. Time keeping chips and thermometer chips use this bus to communicate with the controller.

6. Local push buttons Up and down button to set the set point locally.

7. Relay output Relay output to actually switch the heating.

8. LCD-display Local display to see the current temperature and de set point/desired value.

We will now discuss this eight parts in detail.

Page 28: ICA_Technical_Doc

28

1.) Figure 7, In system programming connection (Source: Atmel)

2.)

Figure 8, Serial connection RS-232 (Source: MCS-Electronics)

Page 29: ICA_Technical_Doc

29

4.1.1 In system programming connection

Atmel AVR chips can be programmed in circuit with a simple dongle which is attached to the parallel port. As you can see in figure 7 the dongle can be built cheaply, making it an ideal starting point for developing with ATMEL AVR micros. The ISP connection is by hardware and doesn’t require additional basic code. If you want to know all details on the ISP connection, you could read the “ATMEL AVR ISP Dongle” article in the annexes.

4.1.2 Serial connection RS-232

In figure 8 we see a standard serial interface that can be found in lots of applications. It’s not in the interest of this essay to discuss the hardware more thoroughly. A summary of serial communications in Bascom:

'Compiler directions $regfile = "m162def.dat" $crystal = 4000000 $baud = 19200 'Declare RAM for administrator terminal Dim Serialcharwaiting As Byte Serialcharwaiting = 0 Dim Serialchar As Byte Dim Dumpcnt As Word 'etc, etc. Print "Druk op B voor het instellingen menu" Serialcharwaiting = Ischarwaiting() If Serialcharwaiting = 1 Then Serialchar = Inkey() If Serialchar = 66 Or Serialchar = 98 Then Goto Terminal End If End If Terminal: Serialchar = Inkey() Serialchar = Asc(serialchar) Select Case Serialchar Case "I" : Goto I_routine Case "i" : Goto I_routine 'etc, etc. End Select Goto Terminal

Serial communications in Bascom are easy. When you use the standard hardware serial port you only need to define the baud rate. And some variables. The "Print" statement prints a text or variable to the serial port. The "Ischarwaiting()" functions checks for a byte in the uart receive buffer. If there is a byte check if its B or b, (66 or 98 ASCII) then start the terminal.) The "Inkey" function returns a char from the receive buffer. We then use a CASE statement to launch the selected commands.

Page 30: ICA_Technical_Doc

30

3.)

Figure 9, Ethernet Interface (Source: MCS-Electronics)

Page 31: ICA_Technical_Doc

31

4.1.3 Ethernet Interface

In figure 9 we see how the IIM7000A is interfaced to the microcontroller. Basically it is connected as if it where external memory. The only thing different from external memory is the Ethernet connector that is seen at the at most right of the figure. The software actually sees the IIM7000A as memory. Bascom handles the low level routines. The only thing our software does is calling the routines through statements.

4.1.3.1 Initialize IIM7000A

'Compiler directions $regfile = "m162def.dat" $lib "tcpip.lbx" $crystal = 4000000 $baud = 19200 'Declare RAM for TCP/IP and HTTP usage Dim Tcpstring As String * 140 At &H300 Dim Shtml As String * 19 Dim Sheader As String * 30 Dim Tempw ... etc,etc. 'Socket status can be referenced from TCPIP.LBX file 'Socket status can be found thru socketstat command Const Sock_closed = $00 ' Status Of Connection Closed Const Sock_arp = $01 ' Status Of Arp Const Sock_listen = $02 ' Status Of Waiting For Tcp Conn. Setup Const Sock_synsent = $03 ' Status Of Setting Up Tcp Connection Const Sock_synsent_ack = $04 ' Status Of Setting Up Tcp Connection Const Sock_synrecv = $05 ' Status Of Setting Up Tcp Connection Const Sock_established = $06 ' Status Of Tcp Connection Established 'etc,etc. Enable Interrupts 'Configure TCP/IP Config Tcpip = Int0 , Mac = 00.40.12.34.56.78 , Ip = 192.168.2.8 , Submask = 255.255.255.0 , Gateway = 192.168.2.1 , Localport = 1000 , Tx = $55 , Rx = $55 , Noinit = 1 Settcp 00.40.12.34.56.78 , New_ip , New_subnetmask , New_gateway The “Config Tcpip” Statement initializes the IIM7000A. This statement can only be used one time. After that you can change the settings with the “Settcp” statement. The above code only initializes it doesn’t handle other communication.

Page 32: ICA_Technical_Doc

32

Tempw = Socketstat(connectionnr , 0) 'Finally we start TCP/IP communication Reset Watchdog Select Case Tempw Case Sock_established If Getdstip(connectionnr) <> Ipcon Then Bauth = 0 End If Tempw = Socketstat(connectionnr , Sel_recv) If Tempw > 0 Then Do Tempw = Tcpread(connectionnr , Tcpstring) If Left(tcpstring , 3) = "GET" Then Gosub Page Elseif Left(tcpstring , 4) = "HEAD" Then Gosub Page Elseif Left(tcpstring , 15) = "Content-Length:" Then Tcpstring = Mid(tcpstring , 16) Elseif Left(tcpstring , 20) = "Authorization: Basic" Then Tcpstring = Mid(tcpstring , 22) If Base64dec(tcpstring) = Passwordanduser Then Bauth = 1 Ipcon = Getdstip(connectionnr) End If End If Loop Until Tcpstring = "" Reset Watchdog If Bauth = 0 Then Increase = 1 Str_passwordcnt = Str(passwordcnt) Tempw = Tcpwrite(connectionnr , "HTTP/1.0 401 OK{013}{010}") Tempw = Tcpwrite(connectionnr , "WWW-Authenticate: Basic realm={034}Geef_wachtwoord_") Tempw = Tcpwrite(connectionnr , Str_passwordcnt , 3) Tempw = Tcpwrite(connectionnr , "{034}{013}{010}") Goto Continue Else Tempw = Tcpwrite(connectionnr , "HTTP/1.0 200 OK{013}{010}") End If

Page 33: ICA_Technical_Doc

33

4.1.3.2 HTTP Initial request and response lines

This page explains how the code on the previous page handles the HTTP initial request and response lines. The HTTP principle was introduced in chapter 3. The ‘Socketstat’ statement gets the value of the status register of the IIM. If data is being send or received thru TCP/IP the socket status goes as follows: 2 Sock_listen, 6 Sock_established, 0 Sock_closed, 2 Sock_listen. ‘Getdstip’ gets the IP of the remote computer. We use that to see if the user already has gives his/her password. (Authentication) The Do…Loop function reads the HTTP initial request lines. These lines are send by the client’s browser. Normally a GET will occur. Then if the user isn’t already authenticated we will send a “WWW-Authenticate: Basic...“. The browser will prompt the user for “username:password”. The controller checks if the “username:password” is OK. Then the GET will be repeated by the client and the page is send. How the HTML page is send can be seen in the next paragraph.

Page 34: ICA_Technical_Doc

34

'Get html page out of data Page: P1 = Instr(tcpstring , " ") P1 = P1 + 1 P2 = Instr(p1 , Tcpstring , " ") P2 = P2 - P1 Shtml = Mid(tcpstring , P1 , P2) Shtml = Lcase(shtml) Return 'Send html page Stuur: Reset Watchdog Dim Wsize As Word Dim Shortshtml As String * 4 Shortshtml = Left(shtml , 4) Reset Watchdog Select Case Shortshtml Case "/set" : Goto Settemp Case "/tim" : Goto Settime Case "/tes" : Tcpstring = "<html><body>P P</Body></Html>" Case "/ind" : Tcpstring = "<html><body><p><b>Verbon... </Html>" Case Else : Tcpstring = "<html><body><p><b>U heft...</Html>" End Select Send_data: Reset Watchdog Wsize = Len(tcpstring) Sheader = "Content-Length: " + Str(wsize) + "{013}{010}" Tempw = Tcpwritestr(connectionnr , Sheader , 255) Tempw = Tcpwrite(connectionnr , Tcpstring , Wsize) Return

Page 35: ICA_Technical_Doc

35

4.1.3.3 Get the URL and send HTML

The “Page” routine removes the headers from received data so typically a request like this: GET /path/file.html HTTP/1.0 Will be stored into shtml like this: /path/file.html The “Page” routine also replaces upper case with lower case. The “Stuur” routine is basically a case statement that does specific tasks when a URL is received. A request like /index.html will fill “Tcpstring” with the data of the index.html page. And then send the index with help of the “Send_data” routine.

• There is one small design consideration here. Since we want every browser to be able to control our thermostat, we don’t want to use complex programs on the client side to send data. Therefore we use the URL to send data. The stuur routine only checks the first 4 characters. So “/ind” and “/index.html” wil both lead to the index of the thermostat. And “/set30” will show a page with “You have successfully changed the temperature” The “30” will elsewhere be used to set the set point.

The “Send_data” routine is a complement to the “Page” routine. It adds headers to data so the data can be send back to the browser.

Page 36: ICA_Technical_Doc

29

Figure 10, IIM7000A (Source: IINchip / Wiznet)

Page 37: ICA_Technical_Doc

37

4.1.3.4 IIM7000A

Just for your information, the IIM7000A is not just one chip. Actually it consists of two chips. The W3100A glue-chip which interfaces the RTL8201bl physical Ethernet chip to our controller the ATmega162. Also notice the RJ45 connector which has build in magnetics and filters. (P02-102-11A9)

Page 38: ICA_Technical_Doc

38

4.) Figure 11, ATMega162

Figure 12, Reset generation and brownout protection (Source: MCS-Electronics)

Page 39: ICA_Technical_Doc

39

4.1.4 Controller ATMega162

As from September 19 2005 software version Milestone 2 is active. This code is developed for the ATMega162 but is backwards compatible. For the ATMega161:

1. The internal brownout(* cannot be used, Atmel errata. 2. Location 0 of EEPROM cannot be used, Atmel errata.

Since the internal brownout(* cannot be used, and the IIM7000 requires a positive and a negative reset signal we added the reset generation circuit as shown in figure 12. For the ATMega162: Do not place the ZSM560 but enable the internal brown out detection. *) Brownout A brownout detection circuit generates a reset if the power supply voltage falls below a certain value. This is meant to avoid the controller to stuck in idle on power supply problems. (For the ATMega161 the brownout detection is handled by the ZSM560C, the ATMega162 has internal Brown Out.

Page 40: ICA_Technical_Doc

40

5.) Figure 13, I²C Chips on “Add-on” print

Figure 14, I²C bus data (Source: Maxim / Dallas semiconductor)

Page 41: ICA_Technical_Doc

41

4.1.5 I²C bus

I²C is a serial and synchronous bus protocol. In our project this bus is used to communicate with a real-time clock IC (DS1307) and a temperature IC (DS1631). As we can see in figure 14, I²C data is send over two lines. Normally this happens like this: Start condition Slave address + write bit Data to slave (Repeated) start condition Slave address + read bit Data from slave Data from slave + Not acknowledge Stop condition In basic this is done like this: 'Initialize I²C Config Scl = Portd.3 Config Sda = Portd.4 'Init temperature sensor I2cstart I2cwbyte Ds1624wr I2cwbyte &HAC 'Access the CONFIG register I2cwbyte &H00 'Set continuous conversion I2cstop Waitms 25 I2cstart I2cwbyte Ds1624wr I2cwbyte &HEE 'Start conversion command I2cstop Waitms 25 The next code in the main program loop: 'Get the current temperature I2cstart I2cwbyte Ds1624wr I2cwbyte &HAA 'Read temperature command I2cstart I2cwbyte Ds1624rd I2crbyte I2ctemp I2crbyte I2ctemp , Nack I2cstop Waitms 25 This sample sets the DS1624 in continuous temperature conversion mode, starts the conversion and reads the temperature. You can find more about the addressing of this chip in the DS1624 datasheet.

Page 42: ICA_Technical_Doc

42

Figure 15, Local I/O

Figure 16, LCD connections (Source: MCS-Electronics)

Page 43: ICA_Technical_Doc

43

4.1.6 Local push buttons

Local push buttons are just I/O pins with a switch and a pull up resistor. In basic: 'Configure I/O Key_down Alias Pinb.6 Key_up Alias Pinb.7 Relay Alias Pind.5 Config Key_down = Input Config Key_up = Input Config Relay = Output If Key_up = 0 Then 'If UP key pressed then... 'etc, etc... End If

4.1.7 Relay output

'I/O actions Switch_off: Reset Portd.5: Goto Continuep 'I/O actions Switch_on: Set Portd.5: Goto Continuep

4.1.8 LCD-display

'Configure and initialize HD44780 compatible LCD display Config Lcdpin = Pin , Db4 = Portb.0 , Db5 = Portb.1 , Db6 = Portb.2 , Db7 = Portb.3 , E = Portb.4 , Rs = Portb.5 Config Lcd = 16 * 2 Deflcdchar 0 , 6 , 9 , 9 , 6 , 32 , 32 , 32 , 32 'Degrees char Deflcdchar 1 , 14 , 17 , 17 , 17 , 14 , 32 , 32 , 32 'Heating ON char Deflcdchar 2 , 14 , 31 , 31 , 31 , 14 , 32 , 32 , 32 'Heating OFF char Deflcdchar 3 , 31 , 5 , 2 , 32 , 14 , 17 , 17 , 32 'PC remote char Cursor Off Noblink 'No cursor on display Now show something: Locate 1 , 1 : Lcd "Huidig: " ; Str(i2ctemp) ; Chr(0) ; "C " Locate 2 , 1 : Lcd "Gewenst: " ; Str(setpoint) ; Chr(0) ; "C " The “Str” function converts a variable in its string representation. (The “Lcd” function only shows strings.)

Page 44: ICA_Technical_Doc

AVR ISP

Figure 17, Thermostat board (Source: MCS-Electronics)

Page 45: ICA_Technical_Doc

45

4.2 Putting part 1 thru 8 together

If we now put the components of part 1 thru 8 together we’ll get the schematics of figure 17 and 18. Figure 18, ICA add-on one

Page 46: ICA_Technical_Doc

46

Normal situation Attack situation Figure 19, Man-in-the-middle attack

Auth. user ICA

Internet

Auth. user

Internet

M-I-T-M ICA

Page 47: ICA_Technical_Doc

47

5 Security and security risks

The Internet is a place full of hackers, so how safe is our thermostat? Security comes in two. You have login authentication on one hand and encryption on the other. Roughly there are two kinds of attacks, login attempts and man-the-middle-attacks. “Login attempts” - a hacker can try to login trying all possible password combinations. (This is also known as brute-force-attack) Man-in-the-middle is a little more complicated. A simple representation is shown in figure 19. Man-in-the-middle basically means that something (a person or program) manipulates data that is transieved. The ICA thermostat is NOT vulnerable for brute-force-attacks, because our login works with a password list (TAN system*). This means that the user needs a new password EVERY time he/she logs in. So when one password is used it is no longer valid the next time. In our project the practical implementation is a password list that needs to be refreshed every 75 passwords thru the serial interface. The password itself is:

• A 5 character password (Hk7$e) • 26 uppercase letters 26 lowercase letters 10 numbers 22 other characters ! # $ % ( ) * + - < = > [ ] ^ _ { } | ? @ & If we add this we have 84 possible characters.

That gives 84^5 = 4.182.119.424 combinations 2 seconds per attempt 2 * 73^5 = 8.364.238.848 Seconds in a year: 365,25 * 24 * 60 * 60 = 31.557.600 8.364.238.848 / 31.557.600 = 265,05 year (to try all possible combinations) Optional IP's blocking or waiting times can be implemented. The thermostat doesn’t use any encryption so it IS VULNERABLE for man-in-the-middle-attacks after a logon has occurred. But it is not worth for a hacker to do a Man-in-the-middle-attack on this system because there is no profit in there for him. We conclude that the thermostat is sufficiently secured for hackers. *) TAN = TrAnsaction Number, A system that changes the password at every login, with each password only used once.

Page 48: ICA_Technical_Doc

48

RAM Usage table (Milestone 1 version) Softstack 512 Dim Tcpstring As String * 140 At &H300 'Read and write HTTP data 141 Dim Shtml As String * 19 'Browser addressline 20 Dim Sheader As String * 30 'HTTP content type and length 31 Dim Tempw As Word 'Storage for socket status 2 Dim Connectionnr As Byte 'Number of maximum connections per time =1 1 Dim P1 As Byte Dim P2 As Byte 2 Dim Bauth As Bit 'If authorisation complete = 1 else 0 0,125 Dim Ipcon As Long 'Stores the IP of the last authenticated user 4 Dim Password As String * 5 6 Dim Passwordanduser As String * 17 18 Dim Eram_passwordcnt As Eram Byte At 01 0 Dim Passwordcnt As Byte 1 Dim Real_passwordcnt As Word 2 Dim Str_passwordcnt As String * 3 4 Dim Increase As Bit 0,125 Dim Username As String * 8 9 Const Ddot = ":" 0 Dim Userlength As Byte 1 Dim Seconds As Byte , Minutes As Byte , Hours As Byte 'Registry for time date 3 Dim Day As Byte , Month As Byte , Year As Byte 3 Dim I2ctemp As Byte 'Storage for the temperature 1 Dim Eram_setpoint As Eram Byte At 02 0 Dim Setpoint As Byte 'Storage for the setpoint e.g. desired temperature 1 Dim Eram_change As Bit 0,125 Dim Verwstatus As String * 3 'If heating is on(in) or off(uit) 4 Dim Local_remote As String * 2 'If temperature set via the Internet string = pc else " " 3 Dim Timedecimal As String * 1 2 Dim Timebyte As Byte 1 Dim Timebyte2 As Byte 1 Dim Adrtimedecimal As Byte 1 Dim Shtmlcounter As Byte 1 Dim I2cadrcount As Byte 1 Dim Serialcharwaiting As Byte 1 Dim Serialchar As Byte 1 Dim Dumpcnt As Word 2 Dim New_password As String * 5 6 Dim New_pass_byte As Byte 1 Dim New_pass_str_cnt As Byte 1 Dim New_pass_str_adr As Byte 1 Dim Eram_new_ip As Eram Long At 3 0 Dim New_ip As Long 4 Dim Eram_new_gateway As Eram Long At 7 0 Dim New_gateway As Long 4 Dim Eram_new_subnetmask As Eram Long At 11 0 Dim New_subnetmask As Long 4 Dim Offset1 As Byte, Dim Offset2 As Byte 2 Dim Wsize As Word 2 Dim Shortshtml As String * 4 5 Dim Tempdecimal As String * 2 3 Dim New_ip_str As String * 3 4 Dim New_ip_char As Byte 1 Dim New_ip_str_cnt As Byte, Dim New_ip_byte As Byte 2 Dim New_ip_str_adr As Byte, Dim Ip_routines_adr_cnt Byte 2

Page 49: ICA_Technical_Doc

49

6 Memory map and usage

Chapter six and seven are - reference - only. This means that you don’t have to read them if you are not interested in reproduction or modification of the Milestone 2 program code. Overview of our current resources (in bytes): used Of Ram used: 834 1024 81% Flash used: 12124 16384 74% EEPROM used: 470 512 92% EEPROM memory map Location 0 at 000 1 Eram_passwordcnt at 001 1 Eram_setpoint at 002 1 IP at 003 5 Gateway at 007 5 Subnetmask at 011 5 Portnumber at 015 2 45 bytes free Password 1 at 062 6 Password 2 at 069 6 …etc, etc. Password 75 at 506 6 1 byte free

Page 50: ICA_Technical_Doc

50

Page 51: ICA_Technical_Doc

51

7 Compiler specific settings

Bascom AVR settings to be able to compile the device. Normally stored in Bascom .cfg file. Select menu: Options → Compiler → Chip Chip = m162.def.dat XRAM = 64k Hw. Stack = 64k Soft Stack = 64k Framesize = 64k XRAM waitstate = false External access enable = true Select menu: Options → Programmer Choose STK200/STK300 Programmer (Set LPT port) Compiler directions for use of ATMega162 Fusebit 7 --> 1:Divide clock by 16 disabled FusebitDCBA --> 1111:CKSEL=111X External Crystal/Resonator High Frequency Fusebit D --> 1:Disable JTAG (for use of TCP)

Page 52: ICA_Technical_Doc

52

Figure 20, The ICA group goes teambuilding in Antwerp Zoo

Page 53: ICA_Technical_Doc

53

Gratitude’s and after word

We hope this document has cleared your view on our project. But if you still have questions on your side, don’t hesitate to contact us thru our website or mail our managing director Linda Vandenbroeck ([email protected]). We like to thank some people that made us what we are today. (Alphabetical) Advisor Business plan Vlekho Evert Verlinden Brussel Advisor EMC and stock holder Ruud Zandbergen Lisse - Netherlands Basic support MCS Electronics Mark Alberts Almere-Haven - Netherlands Business consultants and stock holders Stefan Meert Mechelen Dave De Muyer Duffel Promotor at The Nayer Institute Christian Daemen Antwerpen Stock holders M. en M. Does Noordwijkerhout - Netherlands Ann Geerts Schiplaken H.P. De Graaff Voorhout - Netherlands Godfried Haeldermans Boutersem Jeroen Haeldermans Boutersem Jolanda Hak Arkel - Netherlands Koos Hendriks Zoetermeer - Netherlands Jasper Leemans Lier Sven Lenseclaes Heverlee Lutgarde Roesems Boutersem Robert Roesems Sint-Katherina-Lombeek Mariska Van Rootselaar Voorhout - Netherlands Vlajo VZW Heverlee Thanks to you all, we couldn’t have done it without you!

Page 54: ICA_Technical_Doc

54

Figure 21, The final product (with ISP and serial cable)

Page 55: ICA_Technical_Doc

55

Annexes

Annexes available from separate PDF files. Annexes 1 AN001 Milestone One - Basic code AN002 Cisco - Understanding TCP/IP

AN003 PC Network Advisor - Understanding TCP/IP Issue 87 (9/1997) AN004 James Marshall - HTTP Made Really Easy AN005 Realtec - RTL8201bl datasheet (PHY Ethernet chip) AN006 IINChip - W3100A datasheet (MCU Interface) AN007 Bascom - (partial) Language reference

Annexes 2 AN041 Atmel - ATMega162 datasheet (Controller) AN042 *** AN042 is no longer present ***

AN043 Maxim Dallas - DS1307 datasheet (Timekeeper) AN044 Maxim Dallas - DS1624 datasheet (Thermometer) AN045 Maxim Dallas - MAX232 datasheet (RS232 transeiver) AN046 Zetex - ZSM560 (Brown-out protection) AN047 Philips - 74HC/HCT00 datasheet (NAND port) AN048 Philips - 74HC/HCT573 datasheet (D-latch) AN049 E-tech - P02-102-11A9 datasheet (RJ45 connector) AN050 STMicroelectronics - LD1117 datasheet (3V regulator) AN051 Varta - 3/V80H datasheet (NiMH backup battery) AN052 Truly - MCC162B3-1 datasheet (2x16 LCD display) AN053 Tyco Schrack - PE014-005 datasheet (Relay) AN054 Siemens - V23105-A5501-A201 datasheet (Relay) AN055 Pac-Tec - HPL62040-510-039 drawing (Enclosure) Annexes 3 AN080 RFC2616 HTTP1.1 Protocol specification

Copyright and disclaimer

No rights can be claimed out of the contents of this essay. The contents of this document are subject to national and international copyright laws and are the property of Internet Controlled Applications © 2005 unless another “source” is specified. Paragraph 2, 2.1, 2.1.1, 2.2, 2.2.1 are the property of PC Network Advisor. Paragraph 3.1, 3.2, 3.3, 3.3.1, 3.3.2, 3.3.3, 3.3.4, 3.4 are the property of James Marshall. This document may not be reproduced, copied, stored, manipulated in any way, or used whole or in part of a derivative work, without the written permission of Barry de Graaff (www.barrydegraaff.tk). All rights reserved. Terms and product names used in this document may be trademarks of others.